import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink } from "lucide-react";
import { Button } from "@/components/Button";
import { getProcedureForAdmin } from "@/lib/consentiq/queries";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  StatusBadge,
  ConfirmButton,
  RepeaterField,
  type RepeaterFieldDef,
} from "@/components/admin";
import { updateProcedure, setProcedureStatus, deleteProcedure } from "../actions";

export const dynamic = "force-dynamic";

const statusOptions = ["draft", "published", "archived"] as const;

const severityOptions = [
  { value: "", label: "(unspecified)" },
  { value: "common", label: "Common" },
  { value: "rare", label: "Rare" },
  { value: "serious", label: "Serious" },
];

const optionKindOptions = [
  { value: "text", label: "Free text" },
  { value: "select", label: "Dropdown" },
  { value: "radio", label: "Radio buttons" },
];

const riskFields: RepeaterFieldDef[] = [
  { key: "title", label: "Risk title", type: "text", span: 2, maxLength: 200 },
  { key: "severity", label: "Severity", type: "select", options: severityOptions, span: 1 },
  { key: "detail", label: "Detail / frequency", type: "textarea", rows: 3, span: 3, maxLength: 1000 },
];

const optionFields: RepeaterFieldDef[] = [
  { key: "id", label: "Option ID (machine)", type: "text", span: 1, maxLength: 60 },
  { key: "label", label: "Label", type: "text", span: 1, maxLength: 160 },
  { key: "kind", label: "Input kind", type: "select", options: optionKindOptions, span: 1 },
  { key: "defaultValue", label: "Default value (optional)", type: "text", span: 2, maxLength: 160 },
  { key: "help", label: "Help text (optional)", type: "textarea", rows: 2, span: 3, maxLength: 400 },
];

export default async function AdminConsentIQEditor({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const p = await getProcedureForAdmin(id);
  if (!p) notFound();

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/consentiq"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          All procedures
        </Link>
      </div>

      <AdminHeading
        eyebrow={`Procedure · ${p.slug}`}
        title={p.name}
        lede={`${p.region} · ~${p.approxDurationMin} min`}
        actions={
          <div className="flex items-center gap-2">
            <StatusBadge label={p.status} dot />
            <Link
              href={`/products/consentiq/builder/${p.slug}`}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-1 rounded-md border border-[var(--color-line)] px-3 py-1.5 text-[12px] font-semibold text-[var(--color-slate)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
            >
              <ExternalLink className="h-3.5 w-3.5" aria-hidden />
              Open in builder
            </Link>
          </div>
        }
      />

      <div className="grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,1fr)]">
        <form action={updateProcedure} className="flex flex-col gap-6">
          <input type="hidden" name="id" value={p.id} />

          <FormSection title="Basics">
            <div className="grid gap-4 md:grid-cols-3">
              <InputField
                label="Name"
                name="name"
                defaultValue={p.name}
                required
                maxLength={200}
                wrapClassName="md:col-span-2"
              />
              <InputField
                label="Body region"
                name="region"
                defaultValue={p.region}
                required
                maxLength={100}
              />
              <InputField
                label="Approx duration (minutes)"
                name="approxDurationMin"
                type="number"
                defaultValue={String(p.approxDurationMin)}
              />
              <TextareaField
                label="Anaesthesia options (one per line)"
                name="anaesthesia"
                defaultValue={(p.anaesthesia ?? []).join("\n")}
                rows={3}
                wrapClassName="md:col-span-2"
              />
              <TextareaField
                label="Summary (shown on builder header)"
                name="summary"
                defaultValue={p.summary}
                rows={4}
                maxLength={4000}
                wrapClassName="md:col-span-3"
              />
            </div>
          </FormSection>

          <FormSection
            title="What the operation involves"
            description="One step per line. Rendered as a bullet list on the consent leaflet."
          >
            <TextareaField
              label="Involves"
              name="involves"
              defaultValue={(p.involves ?? []).join("\n")}
              rows={6}
              maxLength={8000}
            />
          </FormSection>

          <FormSection
            title="Intra-operative options"
            description="Controls the surgeon can configure on the consent form — e.g. side, anaesthesia, approach."
          >
            <RepeaterField
              name="options"
              label="Options"
              fields={optionFields}
              defaultValue={p.options as unknown as Array<Record<string, string>>}
              addLabel="Add option"
              emptyRow={{ id: "", label: "", kind: "text", defaultValue: "", help: "" }}
              max={20}
            />
          </FormSection>

          <FormSection
            title="Risks"
            description="Per-risk title, detail with frequency, and severity. Orthopaedic surgeons should review the wording before publishing."
          >
            <RepeaterField
              name="risks"
              label="Risks"
              fields={riskFields}
              defaultValue={p.risks as unknown as Array<Record<string, string>>}
              addLabel="Add risk"
              emptyRow={{ title: "", detail: "", severity: "" }}
              max={40}
            />
          </FormSection>

          <FormSection title="Benefits, alternatives, recovery, warnings">
            <div className="grid gap-4 md:grid-cols-2">
              <TextareaField
                label="Benefits (one per line)"
                name="benefits"
                defaultValue={(p.benefits ?? []).join("\n")}
                rows={6}
                maxLength={6000}
              />
              <TextareaField
                label="Alternatives (one per line)"
                name="alternatives"
                defaultValue={(p.alternatives ?? []).join("\n")}
                rows={6}
                maxLength={6000}
              />
              <TextareaField
                label="Recovery steps (one per line)"
                name="recovery"
                defaultValue={(p.recovery ?? []).join("\n")}
                rows={6}
                maxLength={6000}
              />
              <TextareaField
                label="Warning signs (one per line)"
                name="warnings"
                defaultValue={(p.warnings ?? []).join("\n")}
                rows={6}
                maxLength={6000}
                hint="When to call the clinic — shown to the patient after discharge."
              />
            </div>
          </FormSection>

          <div className="sticky bottom-4 z-10 flex items-center justify-between rounded-xl border border-[var(--color-line)] bg-white p-4 shadow-md">
            <p className="text-[13px] text-[var(--color-slate)]">
              Changes publish immediately to <code>/products/consentiq/procedures</code>.
            </p>
            <Button type="submit" variant="primary" className="!px-5 !py-2.5 !text-[13px]">
              Save procedure
            </Button>
          </div>
        </form>

        <aside className="flex flex-col gap-6">
          <FormSection title="Publication status">
            <div className="flex flex-col gap-2">
              {statusOptions.map((s) => (
                <form key={s} action={setProcedureStatus}>
                  <input type="hidden" name="id" value={p.id} />
                  <input type="hidden" name="status" value={s} />
                  <button
                    type="submit"
                    disabled={p.status === s}
                    className={
                      p.status === s
                        ? "w-full rounded-lg bg-[var(--color-blue)] px-3 py-2 text-[13px] font-semibold text-white"
                        : "w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                    }
                  >
                    {p.status === s ? `Current · ${s}` : `Set to ${s}`}
                  </button>
                </form>
              ))}
            </div>
          </FormSection>

          <FormSection title="Danger zone" tone="danger">
            <form action={deleteProcedure}>
              <input type="hidden" name="id" value={p.id} />
              <ConfirmButton
                label="Delete procedure"
                confirmLabel="Click again to delete permanently"
                tone="danger"
              />
            </form>
          </FormSection>
        </aside>
      </div>
    </>
  );
}
