"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { createScenario, listScenarios, type Scenario } from "@/lib/api";
import { Button } from "@/components/ui/button";

function ScenarioRow({ scenario }: { scenario: Scenario }) {
  const router = useRouter();
  const statusColor =
    scenario.status === "success"
      ? "text-green-600"
      : scenario.status === "failed"
        ? "text-red-600"
        : scenario.status === "running"
          ? "text-blue-600"
          : "text-yellow-600";

  return (
    <tr
      className="border-b hover:bg-muted/50 cursor-pointer"
      onClick={() => router.push(`/scenarios/${scenario.id}`)}
    >
      <td className="py-3 px-4 font-mono text-xs text-muted-foreground">
        {scenario.id.slice(0, 8)}&hellip;
      </td>
      <td className="py-3 px-4">{scenario.name}</td>
      <td className={`py-3 px-4 font-medium capitalize ${statusColor}`}>
        {scenario.status}
      </td>
      <td className="py-3 px-4 text-muted-foreground text-sm">
        {new Date(scenario.created_at).toLocaleString()}
      </td>
    </tr>
  );
}

export default function HomePage() {
  const router = useRouter();
  const [creating, setCreating] = useState(false);

  const { data: scenarios, refetch } = useQuery({
    queryKey: ["scenarios"],
    queryFn: listScenarios,
    refetchInterval: 5000,
  });

  async function handleNewScenario() {
    setCreating(true);
    try {
      const scenario = await createScenario(
        `Scenario ${new Date().toLocaleTimeString()}`,
      );
      await refetch();
      router.push(`/scenarios/${scenario.id}`);
    } finally {
      setCreating(false);
    }
  }

  return (
    <main className="flex-1 container mx-auto px-4 py-8 max-w-5xl">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">REmodel</h1>
          <p className="text-muted-foreground mt-1">
            Hybrid RE project finance scenarios
          </p>
        </div>
        <Button onClick={handleNewScenario} disabled={creating}>
          {creating ? "Creating…" : "New Dummy Scenario"}
        </Button>
      </div>

      {!scenarios || scenarios.length === 0 ? (
        <div className="text-center text-muted-foreground py-24 border rounded-lg">
          No scenarios yet &mdash; click &ldquo;New Dummy Scenario&rdquo; to
          start.
        </div>
      ) : (
        <div className="border rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr>
                <th className="py-2 px-4 text-left font-medium text-muted-foreground">
                  ID
                </th>
                <th className="py-2 px-4 text-left font-medium text-muted-foreground">
                  Name
                </th>
                <th className="py-2 px-4 text-left font-medium text-muted-foreground">
                  Status
                </th>
                <th className="py-2 px-4 text-left font-medium text-muted-foreground">
                  Created
                </th>
              </tr>
            </thead>
            <tbody>
              {scenarios.map((s) => (
                <ScenarioRow key={s.id} scenario={s} />
              ))}
            </tbody>
          </table>
        </div>
      )}
    </main>
  );
}
