"use client";

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 MachineRow {
  id: string;
  name: string;
  kind: string;
  location: string | null;
  notes: string | null;
  active: boolean;
  createdAt: string;
  updatedAt: string;
}

const KINDS = ["NCT_PUNCH", "PRESS_BRAKE", "RIVET", "WELD", "LASER", "SHEAR", "ASSEMBLY", "OTHER"] as const;

const KIND_LABEL: Record<string, string> = {
  NCT_PUNCH: "NCT punch",
  PRESS_BRAKE: "Press brake",
  RIVET: "Rivet",
  WELD: "Weld",
  LASER: "Laser",
  SHEAR: "Shear",
  ASSEMBLY: "Assembly",
  OTHER: "Other",
};

export default function MachinesClient({ initial }: { initial: MachineRow[] }) {
  const router = useRouter();
  const [edit, setEdit] = useState<MachineRow | null>(null);
  const [newOpen, setNewOpen] = useState(false);

  return (
    <div className="mx-auto max-w-5xl px-4 py-8">
      <PageHeader
        title="Machines"
        description="Shop-floor equipment. Deactivated machines are preserved so historical operations retain their references."
        actions={<Button onClick={() => setNewOpen(true)}>New machine</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">Name</th>
              <th className="px-4 py-2 font-medium">Type</th>
              <th className="px-4 py-2 font-medium">Location</th>
              <th className="px-4 py-2 font-medium">Status</th>
              <th className="px-4 py-2"></th>
            </tr>
          </thead>
          <tbody>
            {initial.map((m) => (
              <tr key={m.id} className="border-b border-slate-100 last:border-0">
                <td className="px-4 py-3 font-medium">{m.name}</td>
                <td className="px-4 py-3 text-slate-600">{KIND_LABEL[m.kind] ?? m.kind}</td>
                <td className="px-4 py-3 text-slate-600">{m.location ?? "—"}</td>
                <td className="px-4 py-3">
                  <Badge tone={m.active ? "green" : "amber"}>{m.active ? "active" : "inactive"}</Badge>
                </td>
                <td className="px-4 py-3 text-right">
                  <Button variant="ghost" size="sm" onClick={() => setEdit(m)}>
                    Edit
                  </Button>
                </td>
              </tr>
            ))}
            {initial.length === 0 && (
              <tr>
                <td colSpan={5} className="px-4 py-10 text-center text-slate-500">
                  No machines yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </Card>

      {newOpen && <MachineModal onClose={() => setNewOpen(false)} onSaved={() => router.refresh()} />}
      {edit && <MachineModal machine={edit} onClose={() => setEdit(null)} onSaved={() => router.refresh()} />}
    </div>
  );
}

function MachineModal({
  machine,
  onClose,
  onSaved,
}: {
  machine?: MachineRow;
  onClose: () => void;
  onSaved: () => void;
}) {
  const editing = !!machine;
  const [name, setName] = useState(machine?.name ?? "");
  const [kind, setKind] = useState(machine?.kind ?? "OTHER");
  const [location, setLocation] = useState(machine?.location ?? "");
  const [notes, setNotes] = useState(machine?.notes ?? "");
  const [active, setActive] = useState(machine?.active ?? true);
  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 {
      if (editing) {
        await apiFetch(`/api/v1/machines/${machine!.id}`, {
          method: "PATCH",
          body: JSON.stringify({ name, kind, location, notes, active }),
        });
      } else {
        await apiFetch("/api/v1/machines", {
          method: "POST",
          body: JSON.stringify({ name, kind, location, notes }),
        });
      }
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Save failed");
    } finally {
      setBusy(false);
    }
  }

  async function deactivate() {
    if (!machine || !confirm(`Deactivate ${machine.name}?`)) return;
    setBusy(true);
    setError(null);
    try {
      await apiFetch(`/api/v1/machines/${machine.id}`, { method: "DELETE" });
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Deactivate failed");
      setBusy(false);
    }
  }

  return (
    <Modal
      open
      onClose={onClose}
      title={editing ? `Edit ${machine!.name}` : "New machine"}
      footer={
        <>
          {editing && machine!.active && (
            <Button variant="danger" size="sm" onClick={deactivate} disabled={busy}>
              Deactivate
            </Button>
          )}
          <div className="flex-1" />
          <Button variant="secondary" onClick={onClose} disabled={busy}>
            Cancel
          </Button>
          <Button type="submit" form="machine-form" disabled={busy}>
            {busy ? "Saving…" : editing ? "Save" : "Create"}
          </Button>
        </>
      }
    >
      <form id="machine-form" onSubmit={submit} className="space-y-4">
        <Field label="Name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} required maxLength={200} />
        </Field>
        <Field label="Type" required>
          <Select value={kind} onChange={(e) => setKind(e.target.value)}>
            {KINDS.map((k) => (
              <option key={k} value={k}>
                {KIND_LABEL[k]}
              </option>
            ))}
          </Select>
        </Field>
        <Field label="Location" hint="Where on the floor, or empty.">
          <Input value={location} onChange={(e) => setLocation(e.target.value)} />
        </Field>
        <Field label="Notes">
          <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
        </Field>
        {editing && (
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} />
            <span>Active</span>
          </label>
        )}
        <ErrorBanner message={error} />
      </form>
    </Modal>
  );
}
