"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, Select, Textarea } from "@/components/ui";
import { apiFetch, ApiClientError } from "@/lib/client-api";

interface ProjectRow {
  id: string;
  code: string;
  name: string;
  customerCode: string | null;
  status: string;
  dueDate: string | null;
  assemblyCount: 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 "—";
  const d = new Date(iso);
  return d.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
}

export default function ProjectsClient({ initial }: { initial: ProjectRow[] }) {
  const router = useRouter();
  const [newOpen, setNewOpen] = useState(false);

  return (
    <div className="mx-auto max-w-6xl px-4 py-8">
      <PageHeader
        title="Projects"
        description="Top-level jobs. Each project groups assemblies, parts, and operations."
        actions={<Button onClick={() => setNewOpen(true)}>New project</Button>}
      />
      <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">Customer</th>
              <th className="px-4 py-2 font-medium">Due</th>
              <th className="px-4 py-2 font-medium">Assemblies</th>
              <th className="px-4 py-2 font-medium">Status</th>
              <th className="px-4 py-2"></th>
            </tr>
          </thead>
          <tbody>
            {initial.map((p) => (
              <tr key={p.id} className="border-b border-slate-100 last:border-0">
                <td className="px-4 py-3 font-mono text-slate-700">{p.code}</td>
                <td className="px-4 py-3 font-medium">{p.name}</td>
                <td className="px-4 py-3 text-slate-600">{p.customerCode ?? "—"}</td>
                <td className="px-4 py-3 text-slate-600">{formatDate(p.dueDate)}</td>
                <td className="px-4 py-3 text-slate-600">{p.assemblyCount}</td>
                <td className="px-4 py-3">
                  <Badge tone={STATUS_TONE[p.status] ?? "slate"}>{STATUS_LABEL[p.status] ?? p.status}</Badge>
                </td>
                <td className="px-4 py-3 text-right">
                  <Link href={`/admin/projects/${p.id}`} className="text-sm text-blue-600 hover:underline">
                    Open →
                  </Link>
                </td>
              </tr>
            ))}
            {initial.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-10 text-center text-slate-500">
                  No projects yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </Card>

      {newOpen && (
        <NewProjectModal
          onClose={() => setNewOpen(false)}
          onSaved={(id) => {
            setNewOpen(false);
            router.push(`/admin/projects/${id}`);
          }}
        />
      )}
    </div>
  );
}

function NewProjectModal({ onClose, onSaved }: { onClose: () => void; onSaved: (id: string) => void }) {
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [customerCode, setCustomerCode] = useState("");
  const [dueDate, setDueDate] = useState("");
  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<{ project: { id: string } }>("/api/v1/projects", {
        method: "POST",
        body: JSON.stringify({
          code,
          name,
          customerCode: customerCode || null,
          dueDate: dueDate || null,
          notes: notes || null,
        }),
      });
      onSaved(res.project.id);
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Save failed");
      setBusy(false);
    }
  }

  return (
    <Modal
      open
      onClose={onClose}
      title="New project"
      footer={
        <>
          <div className="flex-1" />
          <Button variant="secondary" onClick={onClose} disabled={busy}>
            Cancel
          </Button>
          <Button type="submit" form="project-form" disabled={busy}>
            {busy ? "Creating…" : "Create"}
          </Button>
        </>
      }
    >
      <form id="project-form" onSubmit={submit} className="space-y-4">
        <Field label="Code" required hint="Short identifier, e.g. MP-2026-004">
          <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="Customer code" hint="Optional customer reference.">
          <Input value={customerCode} onChange={(e) => setCustomerCode(e.target.value)} />
        </Field>
        <Field label="Due date">
          <Input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)} />
        </Field>
        <Field label="Notes">
          <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
        </Field>
        <ErrorBanner message={error} />
      </form>
    </Modal>
  );
}

export function EditProjectModal({
  project,
  onClose,
  onSaved,
}: {
  project: { id: string; code: string; name: string; customerCode: string | null; dueDate: string | null; status: string; notes: string | null };
  onClose: () => void;
  onSaved: () => void;
}) {
  const [code, setCode] = useState(project.code);
  const [name, setName] = useState(project.name);
  const [customerCode, setCustomerCode] = useState(project.customerCode ?? "");
  const [dueDate, setDueDate] = useState(project.dueDate ? project.dueDate.slice(0, 10) : "");
  const [status, setStatus] = useState(project.status);
  const [notes, setNotes] = useState(project.notes ?? "");
  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 {
      await apiFetch(`/api/v1/projects/${project.id}`, {
        method: "PATCH",
        body: JSON.stringify({
          code,
          name,
          customerCode: customerCode || null,
          dueDate: dueDate || null,
          status,
          notes: notes || null,
        }),
      });
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Save failed");
      setBusy(false);
    }
  }

  async function remove() {
    if (!confirm(`Delete project ${project.code}? This removes all assemblies, parts, and operations under it.`)) return;
    setBusy(true);
    setError(null);
    try {
      await apiFetch(`/api/v1/projects/${project.id}`, { method: "DELETE" });
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Delete failed");
      setBusy(false);
    }
  }

  return (
    <Modal
      open
      onClose={onClose}
      title={`Edit ${project.code}`}
      footer={
        <>
          <Button variant="danger" size="sm" onClick={remove} disabled={busy}>
            Delete
          </Button>
          <div className="flex-1" />
          <Button variant="secondary" onClick={onClose} disabled={busy}>
            Cancel
          </Button>
          <Button type="submit" form="edit-project-form" disabled={busy}>
            {busy ? "Saving…" : "Save"}
          </Button>
        </>
      }
    >
      <form id="edit-project-form" onSubmit={submit} className="space-y-4">
        <Field label="Code" required>
          <Input value={code} onChange={(e) => setCode(e.target.value)} required />
        </Field>
        <Field label="Name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} required />
        </Field>
        <Field label="Customer code">
          <Input value={customerCode} onChange={(e) => setCustomerCode(e.target.value)} />
        </Field>
        <Field label="Due date">
          <Input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)} />
        </Field>
        <Field label="Status" required>
          <Select value={status} onChange={(e) => setStatus(e.target.value)}>
            <option value="planning">Planning</option>
            <option value="in_progress">In progress</option>
            <option value="completed">Completed</option>
            <option value="cancelled">Cancelled</option>
          </Select>
        </Field>
        <Field label="Notes">
          <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
        </Field>
        <ErrorBanner message={error} />
      </form>
    </Modal>
  );
}
