"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 TemplateRow {
  id: string;
  name: string;
  machineId: string | null;
  machineName: string | null;
  defaultSettings: string | null;
  defaultInstructions: string | null;
  qcRequired: boolean;
  active: boolean;
}

interface MachineOption {
  id: string;
  name: string;
}

export default function TemplatesClient({
  initialTemplates,
  machines,
}: {
  initialTemplates: TemplateRow[];
  machines: MachineOption[];
}) {
  const router = useRouter();
  const [edit, setEdit] = useState<TemplateRow | null>(null);
  const [newOpen, setNewOpen] = useState(false);

  return (
    <div className="mx-auto max-w-5xl px-4 py-8">
      <PageHeader
        title="Operation templates"
        description="Reusable step recipes. Use them when authoring operations on a part, or define ad-hoc operations."
        actions={<Button onClick={() => setNewOpen(true)}>New template</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">Machine</th>
              <th className="px-4 py-2 font-medium">QC</th>
              <th className="px-4 py-2 font-medium">Status</th>
              <th className="px-4 py-2"></th>
            </tr>
          </thead>
          <tbody>
            {initialTemplates.map((t) => (
              <tr key={t.id} className="border-b border-slate-100 last:border-0">
                <td className="px-4 py-3 font-medium">{t.name}</td>
                <td className="px-4 py-3 text-slate-600">{t.machineName ?? "—"}</td>
                <td className="px-4 py-3">
                  {t.qcRequired ? <Badge tone="amber">required</Badge> : <span className="text-slate-400">—</span>}
                </td>
                <td className="px-4 py-3">
                  <Badge tone={t.active ? "green" : "amber"}>{t.active ? "active" : "inactive"}</Badge>
                </td>
                <td className="px-4 py-3 text-right">
                  <Button variant="ghost" size="sm" onClick={() => setEdit(t)}>
                    Edit
                  </Button>
                </td>
              </tr>
            ))}
            {initialTemplates.length === 0 && (
              <tr>
                <td colSpan={5} className="px-4 py-10 text-center text-slate-500">
                  No operation templates yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </Card>

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

function TemplateModal({
  template,
  machines,
  onClose,
  onSaved,
}: {
  template?: TemplateRow;
  machines: MachineOption[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const editing = !!template;
  const [name, setName] = useState(template?.name ?? "");
  const [machineId, setMachineId] = useState(template?.machineId ?? "");
  const [instructions, setInstructions] = useState(template?.defaultInstructions ?? "");
  const [settings, setSettings] = useState(template?.defaultSettings ?? "");
  const [qcRequired, setQcRequired] = useState(template?.qcRequired ?? false);
  const [active, setActive] = useState(template?.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 {
      const body = {
        name,
        machineId: machineId || null,
        defaultInstructions: instructions,
        defaultSettings: settings,
        qcRequired,
        ...(editing ? { active } : {}),
      };
      if (editing) {
        await apiFetch(`/api/v1/operation-templates/${template!.id}`, {
          method: "PATCH",
          body: JSON.stringify(body),
        });
      } else {
        await apiFetch("/api/v1/operation-templates", {
          method: "POST",
          body: JSON.stringify(body),
        });
      }
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Save failed");
    } finally {
      setBusy(false);
    }
  }

  async function deactivate() {
    if (!template || !confirm(`Deactivate ${template.name}?`)) return;
    setBusy(true);
    setError(null);
    try {
      await apiFetch(`/api/v1/operation-templates/${template.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 ${template!.name}` : "New operation template"}
      footer={
        <>
          {editing && template!.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="tpl-form" disabled={busy}>
            {busy ? "Saving…" : editing ? "Save" : "Create"}
          </Button>
        </>
      }
    >
      <form id="tpl-form" onSubmit={submit} className="space-y-4">
        <Field label="Name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} required />
        </Field>
        <Field label="Default machine">
          <Select value={machineId} onChange={(e) => setMachineId(e.target.value)}>
            <option value="">— none —</option>
            {machines.map((m) => (
              <option key={m.id} value={m.id}>
                {m.name}
              </option>
            ))}
          </Select>
        </Field>
        <Field
          label="Default instructions"
          hint="Step-by-step text shown on the traveler card."
        >
          <Textarea value={instructions} onChange={(e) => setInstructions(e.target.value)} />
        </Field>
        <Field
          label="Default settings (JSON)"
          hint='Key/value like {"programNumber":47,"speed":"medium"}. Optional.'
        >
          <Textarea
            value={settings}
            onChange={(e) => setSettings(e.target.value)}
            placeholder='{"programNumber":47}'
          />
        </Field>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={qcRequired} onChange={(e) => setQcRequired(e.target.checked)} />
          <span>QC check required on close-out</span>
        </label>
        {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>
  );
}
