"use client";

import { useRouter } from "next/navigation";
import { useId, useState, useTransition } from "react";
import { Button, Card } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { createFormTemplateAction, deleteFormTemplateAction, updateFormTemplateAction } from "@/lib/actions/modules";
import { FIELD_TYPES, OPTION_TYPES, type FormField } from "@/lib/forms/schema";

const TYPE_LABELS: Record<(typeof FIELD_TYPES)[number], string> = { text: "Short text", email: "Email", phone: "Phone", textarea: "Long text", number: "Number", date: "Date", select: "Dropdown", radio: "Choose one (radio)", checkbox: "Single checkbox", checkboxGroup: "Choose many (checkboxes)" };
const toId = (label: string) => label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^[^a-z]+/, "").replace(/_+$/, "").slice(0, 40);
interface Row extends Omit<FormField, "options"> { options: string; idTouched: boolean }
const toRow = (f: FormField): Row => ({ ...f, options: f.options.join("\n"), idTouched: true });
const blank = (): Row => ({ id: "", type: "text", label: "", required: false, helpText: "", placeholder: "", options: "", idTouched: false });

export interface TemplateInitial { id?: string; name: string; description: string; consentText: string; successMessage: string; fields: FormField[] }

/** Super-admin builder for a reusable form template. Websites copy it into their own forms. */
export function TemplateBuilder({ initial, base }: { initial: TemplateInitial; base: string }) {
  const uid = useId();
  const router = useRouter();
  const [name, setName] = useState(initial.name);
  const [description, setDescription] = useState(initial.description);
  const [consent, setConsent] = useState(initial.consentText);
  const [success, setSuccess] = useState(initial.successMessage);
  const [rows, setRows] = useState<Row[]>(initial.fields.length ? initial.fields.map(toRow) : [{ ...blank(), label: "Your name", id: "name", type: "text", required: true, idTouched: true }, { ...blank(), label: "Email address", id: "email", type: "email", required: true, idTouched: true }]);
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [armed, setArmed] = useState(false);
  const [pending, start] = useTransition();
  const upd = (i: number, p: Partial<Row>) => setRows((r) => r.map((x, j) => (j === i ? { ...x, ...p } : x)));
  const move = (i: number, d: -1 | 1) => setRows((r) => { const a = [...r]; const j = i + d; if (j < 0 || j >= a.length) return r; [a[i], a[j]] = [a[j]!, a[i]!]; return a; });
  const payload = () => ({ name, description, consentText: consent, successMessage: success, fields: rows.map((r) => ({ id: r.id, type: r.type, label: r.label, required: r.required, helpText: r.helpText, placeholder: r.placeholder, ...(r.maxLength ? { maxLength: r.maxLength } : {}), options: OPTION_TYPES.includes(r.type) ? r.options.split("\n").map((o) => o.trim()).filter(Boolean) : [] })) });
  const finish = (r: { ok: boolean; message?: string; error?: string; fieldErrors?: Record<string, string> }, after?: () => void) => { setErrors(r.fieldErrors ?? {}); setMsg({ ok: r.ok, text: r.ok ? (r.message ?? "Saved") : (r.error ?? "Failed") }); if (r.ok) after?.(); };
  const save = () => start(async () => {
    if (!initial.id) { const r = await createFormTemplateAction(payload()); finish(r, () => router.push(`${base}/${r.ok ? r.data?.id : ""}`)); }
    else finish(await updateFormTemplateAction(initial.id, payload()), () => router.refresh());
  });
  const errList = Object.entries(errors);
  return (
    <div className="space-y-4">
      <Card className="space-y-3 p-4">
        <div className="grid gap-3 sm:grid-cols-2">
          <Field id={`${uid}-name`} label="Template name"><input id={`${uid}-name`} className={inputClass} maxLength={120} value={name} onChange={(e) => setName(e.target.value)} /></Field>
          <Field id={`${uid}-desc`} label="Description" help="Shown to admins when they pick a template."><input id={`${uid}-desc`} className={inputClass} maxLength={300} value={description} onChange={(e) => setDescription(e.target.value)} /></Field>
          <Field id={`${uid}-consent`} label="Consent text (optional)"><input id={`${uid}-consent`} className={inputClass} maxLength={500} value={consent} onChange={(e) => setConsent(e.target.value)} /></Field>
          <Field id={`${uid}-ok`} label="Success message (optional)"><input id={`${uid}-ok`} className={inputClass} maxLength={500} value={success} onChange={(e) => setSuccess(e.target.value)} /></Field>
        </div>
      </Card>
      <Card className="space-y-3 p-4">
        <h2 className="text-sm font-semibold">Fields</h2>
        <ul className="space-y-2">
          {rows.map((r, i) => (
            <li key={i} className="rounded-md border border-border p-3">
              <div className="grid gap-2 sm:grid-cols-[10rem_1fr_1fr_auto]">
                <div><label htmlFor={`${uid}-t${i}`} className="mb-1 block text-xs font-medium">Type</label><select id={`${uid}-t${i}`} className={inputClass} value={r.type} onChange={(e) => upd(i, { type: e.target.value as Row["type"] })}>{FIELD_TYPES.map((t) => <option key={t} value={t}>{TYPE_LABELS[t]}</option>)}</select></div>
                <div><label htmlFor={`${uid}-l${i}`} className="mb-1 block text-xs font-medium">Label</label><input id={`${uid}-l${i}`} className={inputClass} maxLength={120} value={r.label} onChange={(e) => upd(i, { label: e.target.value, ...(r.idTouched ? {} : { id: toId(e.target.value) }) })} /></div>
                <div><label htmlFor={`${uid}-i${i}`} className="mb-1 block text-xs font-medium">Field name</label><input id={`${uid}-i${i}`} className={inputClass} maxLength={40} value={r.id} onChange={(e) => upd(i, { id: e.target.value, idTouched: true })} /></div>
                <div className="flex items-end gap-1"><Button variant="ghost" aria-label={`Move field ${i + 1} up`} disabled={i === 0} onClick={() => move(i, -1)}>↑</Button><Button variant="ghost" aria-label={`Move field ${i + 1} down`} disabled={i === rows.length - 1} onClick={() => move(i, 1)}>↓</Button><Button variant="ghost" aria-label={`Remove field ${i + 1}`} onClick={() => setRows((x) => x.filter((_, j) => j !== i))}>Remove</Button></div>
              </div>
              <div className="mt-2 grid gap-2 sm:grid-cols-3">
                <div><label htmlFor={`${uid}-h${i}`} className="mb-1 block text-xs font-medium">Help text</label><input id={`${uid}-h${i}`} className={inputClass} maxLength={250} value={r.helpText} onChange={(e) => upd(i, { helpText: e.target.value })} /></div>
                <div><label htmlFor={`${uid}-p${i}`} className="mb-1 block text-xs font-medium">Placeholder</label><input id={`${uid}-p${i}`} className={inputClass} maxLength={120} value={r.placeholder} onChange={(e) => upd(i, { placeholder: e.target.value })} /></div>
                <label className="flex items-end gap-2 pb-2 text-sm"><input type="checkbox" checked={r.required} onChange={(e) => upd(i, { required: e.target.checked })} />Required</label>
                {OPTION_TYPES.includes(r.type) ? <div className="sm:col-span-3"><label htmlFor={`${uid}-o${i}`} className="mb-1 block text-xs font-medium">Options, one per line (at least two)</label><textarea id={`${uid}-o${i}`} rows={3} className={inputClass} value={r.options} onChange={(e) => upd(i, { options: e.target.value })} /></div> : null}
              </div>
            </li>
          ))}
        </ul>
        <Button variant="secondary" disabled={rows.length >= 40} onClick={() => setRows((r) => [...r, blank()])}>Add field</Button>
      </Card>
      <p role="status" aria-live="polite" className={msg ? (msg.ok ? "text-sm text-success" : "text-sm text-danger") : "sr-only"}>{msg?.text}</p>
      {errList.length ? <ul role="alert" className="list-disc pl-5 text-xs text-danger">{errList.slice(0, 8).map(([k, m]) => <li key={k}>{k.replace(/^fields\.(\d+)/, (_, n) => `Field ${Number(n) + 1}`)}: {m}</li>)}</ul> : null}
      <div className="flex flex-wrap gap-2">
        <Button disabled={pending} onClick={save}>{pending ? "Saving…" : initial.id ? "Save template" : "Create template"}</Button>
        {initial.id ? (armed ? (<><Button variant="danger" disabled={pending} onClick={() => start(async () => { finish(await deleteFormTemplateAction(initial.id!), () => router.push(base)); setArmed(false); })}>Confirm delete</Button><Button variant="ghost" onClick={() => setArmed(false)}>Cancel</Button></>) : <Button variant="ghost" onClick={() => setArmed(true)}>Delete</Button>) : null}
      </div>
      {initial.id ? <p className="text-xs text-muted-foreground">Websites that already copied this template keep their own copy; editing or deleting the template does not change them.</p> : null}
    </div>
  );
}
