"use client";

import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  Badge,
  Button,
  Card,
  ErrorBanner,
  Field,
  Input,
  Modal,
  PageHeader,
  Textarea,
} from "@/components/ui";
import { apiFetch, ApiClientError } from "@/lib/client-api";
import { EditProjectModal } from "../ProjectsClient";

interface ProjectInfo {
  id: string;
  code: string;
  name: string;
  customerCode: string | null;
  status: string;
  dueDate: string | null;
  notes: string | null;
  fastenerCount: number;
  poCount: number;
}

interface AssemblyRow {
  id: string;
  code: string;
  name: string;
  qty: number;
  notes: string | null;
  partCount: number;
}

const STATUS_TONE: Record<string, "slate" | "blue" | "green" | "amber" | "red"> = {
  planning: "slate",
  in_progress: "blue",
  completed: "green",
  cancelled: "red",
};

const STATUS_LABEL: Record<string, string> = {
  planning: "Planning",
  in_progress: "In progress",
  completed: "Completed",
  cancelled: "Cancelled",
};

function formatDate(iso: string | null) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

export default function ProjectDetailClient({
  project,
  assemblies,
}: {
  project: ProjectInfo;
  assemblies: AssemblyRow[];
}) {
  const router = useRouter();
  const [editOpen, setEditOpen] = useState(false);
  const [newAssemblyOpen, setNewAssemblyOpen] = useState(false);

  return (
    <div className="mx-auto max-w-6xl px-4 py-8">
      <nav className="mb-3 text-sm text-slate-500">
        <Link href="/admin/projects" className="hover:underline">
          ← All projects
        </Link>
      </nav>
      <PageHeader
        title={
          <span className="flex items-center gap-3">
            <span className="font-mono text-slate-500 text-lg">{project.code}</span>
            <span>{project.name}</span>
          </span>
        }
        description={
          <span className="flex flex-wrap items-center gap-2">
            <Badge tone={STATUS_TONE[project.status] ?? "slate"}>
              {STATUS_LABEL[project.status] ?? project.status}
            </Badge>
            <span className="text-slate-500">Customer: {project.customerCode ?? "—"}</span>
            <span className="text-slate-400">·</span>
            <span className="text-slate-500">Due: {formatDate(project.dueDate)}</span>
          </span>
        }
        actions={
          <>
            <Button variant="secondary" onClick={() => setEditOpen(true)}>
              Edit project
            </Button>
            <Button onClick={() => setNewAssemblyOpen(true)}>New assembly</Button>
          </>
        }
      />

      {project.notes ? (
        <Card className="mb-4">
          <div className="p-4 text-sm text-slate-700 whitespace-pre-wrap">{project.notes}</div>
        </Card>
      ) : null}

      <section className="mb-8">
        <h2 className="text-lg font-semibold mb-3">Assemblies</h2>
        <Card>
          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-left text-slate-600 border-b border-slate-200">
              <tr>
                <th className="px-4 py-2 font-medium">Code</th>
                <th className="px-4 py-2 font-medium">Name</th>
                <th className="px-4 py-2 font-medium">Qty</th>
                <th className="px-4 py-2 font-medium">Parts</th>
                <th className="px-4 py-2"></th>
              </tr>
            </thead>
            <tbody>
              {assemblies.map((a) => (
                <tr key={a.id} className="border-b border-slate-100 last:border-0">
                  <td className="px-4 py-3 font-mono text-slate-700">{a.code}</td>
                  <td className="px-4 py-3 font-medium">{a.name}</td>
                  <td className="px-4 py-3 text-slate-600">{a.qty}</td>
                  <td className="px-4 py-3 text-slate-600">{a.partCount}</td>
                  <td className="px-4 py-3 text-right">
                    <Link
                      href={`/admin/projects/${project.id}/assemblies/${a.id}`}
                      className="text-sm text-blue-600 hover:underline"
                    >
                      Open →
                    </Link>
                  </td>
                </tr>
              ))}
              {assemblies.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-4 py-10 text-center text-slate-500">
                    No assemblies yet. Add one to start building parts and operations.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </Card>
      </section>

      <section className="grid gap-4 sm:grid-cols-2">
        <Card>
          <div className="p-4">
            <h3 className="font-semibold mb-1">Fasteners</h3>
            <p className="text-sm text-slate-500 mb-3">
              {project.fastenerCount} item{project.fastenerCount === 1 ? "" : "s"} tracked
            </p>
            <p className="text-xs text-slate-400">Fastener authoring lands in step 6.</p>
          </div>
        </Card>
        <Card>
          <div className="p-4">
            <h3 className="font-semibold mb-1">Purchase orders</h3>
            <p className="text-sm text-slate-500 mb-3">
              {project.poCount} PO{project.poCount === 1 ? "" : "s"}
            </p>
            <p className="text-xs text-slate-400">PO lifecycle and PDFs land in step 6.</p>
          </div>
        </Card>
      </section>

      {editOpen && (
        <EditProjectModal
          project={project}
          onClose={() => setEditOpen(false)}
          onSaved={() => router.refresh()}
        />
      )}
      {newAssemblyOpen && (
        <NewAssemblyModal
          projectId={project.id}
          onClose={() => setNewAssemblyOpen(false)}
          onSaved={(assemblyId) => {
            setNewAssemblyOpen(false);
            router.push(`/admin/projects/${project.id}/assemblies/${assemblyId}`);
          }}
        />
      )}
    </div>
  );
}

function NewAssemblyModal({
  projectId,
  onClose,
  onSaved,
}: {
  projectId: string;
  onClose: () => void;
  onSaved: (id: string) => void;
}) {
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [qty, setQty] = useState("1");
  const [notes, setNotes] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      const res = await apiFetch<{ assembly: { id: string } }>(
        `/api/v1/projects/${projectId}/assemblies`,
        {
          method: "POST",
          body: JSON.stringify({ code, name, qty: Number(qty), notes: notes || null }),
        },
      );
      onSaved(res.assembly.id);
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Save failed");
      setBusy(false);
    }
  }

  return (
    <Modal
      open
      onClose={onClose}
      title="New assembly"
      footer={
        <>
          <div className="flex-1" />
          <Button variant="secondary" onClick={onClose} disabled={busy}>
            Cancel
          </Button>
          <Button type="submit" form="asm-form" disabled={busy}>
            {busy ? "Creating…" : "Create"}
          </Button>
        </>
      }
    >
      <form id="asm-form" onSubmit={submit} className="space-y-4">
        <Field label="Code" required hint="Unique within this project.">
          <Input value={code} onChange={(e) => setCode(e.target.value)} required autoFocus />
        </Field>
        <Field label="Name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} required />
        </Field>
        <Field label="Quantity" required>
          <Input type="number" min={1} value={qty} onChange={(e) => setQty(e.target.value)} required />
        </Field>
        <Field label="Notes">
          <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
        </Field>
        <ErrorBanner message={error} />
      </form>
    </Modal>
  );
}
