import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink } from "lucide-react";
import { Button } from "@/components/Button";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  SelectField,
  StatusBadge,
  ConfirmButton,
} from "@/components/admin";
import {
  getConditionForAdmin,
  listRegionsForAdmin,
} from "@/lib/atlas/queries";
import { updateCondition, deleteCondition } from "../../actions";

export const dynamic = "force-dynamic";

const statusOptions = ["draft", "published", "archived"] as const;
const categoryOptions = [
  "Degenerative",
  "Traumatic",
  "Inflammatory",
  "Congenital",
  "Infectious",
  "Neoplastic",
] as const;

export default async function AdminAtlasConditionEditor({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const [condition, regions] = await Promise.all([
    getConditionForAdmin(id),
    listRegionsForAdmin(),
  ]);
  if (!condition) notFound();

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/atlas"
          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 />
          Back to Atlas
        </Link>
      </div>

      <AdminHeading
        eyebrow={`Condition · ${condition.slug}`}
        title={condition.name}
        lede={`${condition.regionSlug} · ${condition.category}`}
        actions={
          <div className="flex items-center gap-2">
            <StatusBadge label={condition.status} dot />
            <Link
              href={`/products/atlas/conditions/${condition.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 />
              View live
            </Link>
          </div>
        }
      />

      <form action={updateCondition} className="flex flex-col gap-6">
        <input type="hidden" name="id" value={condition.id} />

        <FormSection title="Metadata">
          <div className="grid gap-4 md:grid-cols-6">
            <InputField
              label="Name"
              name="name"
              defaultValue={condition.name}
              required
              maxLength={200}
              wrapClassName="md:col-span-4"
            />
            <InputField
              label="Slug"
              name="slug"
              defaultValue={condition.slug}
              required
              maxLength={80}
              wrapClassName="md:col-span-2"
            />
            <SelectField
              label="Region"
              name="regionSlug"
              defaultValue={condition.regionSlug}
              wrapClassName="md:col-span-2"
            >
              {regions.map((r) => (
                <option key={r.id} value={r.slug}>
                  {r.name}
                </option>
              ))}
            </SelectField>
            <SelectField
              label="Category"
              name="category"
              defaultValue={condition.category}
              wrapClassName="md:col-span-2"
            >
              {categoryOptions.map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </SelectField>
            <SelectField
              label="Status"
              name="status"
              defaultValue={condition.status}
              wrapClassName="md:col-span-1"
            >
              {statusOptions.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </SelectField>
            <InputField
              label="Position"
              name="position"
              type="number"
              defaultValue={String(condition.position)}
              wrapClassName="md:col-span-1"
            />
            <TextareaField
              label="Summary (shown on list card)"
              name="summary"
              defaultValue={condition.summary}
              rows={3}
              maxLength={2000}
              wrapClassName="md:col-span-6"
            />
          </div>
        </FormSection>

        <FormSection
          title="Full text — 7 structured sections"
          description="Each section renders as a block on the condition detail page. Use plain prose; paragraph breaks are preserved."
        >
          <div className="grid gap-4">
            <TextareaField
              label="Overview"
              name="overview"
              defaultValue={condition.sections.overview}
              rows={6}
              maxLength={8000}
            />
            <TextareaField
              label="Epidemiology"
              name="epidemiology"
              defaultValue={condition.sections.epidemiology}
              rows={4}
              maxLength={4000}
            />
            <TextareaField
              label="Symptoms & examination"
              name="symptoms"
              defaultValue={condition.sections.symptoms}
              rows={4}
              maxLength={4000}
            />
            <TextareaField
              label="Imaging"
              name="imaging"
              defaultValue={condition.sections.imaging}
              rows={4}
              maxLength={4000}
            />
            <TextareaField
              label="Classification"
              name="classification"
              defaultValue={condition.sections.classification}
              rows={4}
              maxLength={4000}
            />
            <TextareaField
              label="Management"
              name="management"
              defaultValue={condition.sections.management}
              rows={6}
              maxLength={6000}
            />
            <TextareaField
              label="Outcomes"
              name="outcomes"
              defaultValue={condition.sections.outcomes}
              rows={4}
              maxLength={4000}
            />
          </div>
        </FormSection>

        <FormSection
          title="References"
          description="One citation per line. Rendered as a numbered list at the bottom of the detail page."
        >
          <TextareaField
            label="References"
            name="referencesList"
            defaultValue={(condition.referencesList ?? []).join("\n")}
            rows={6}
            maxLength={4000}
          />
        </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)]">
            Saving publishes to <code>/products/atlas/conditions/{condition.slug}</code>.
          </p>
          <Button type="submit" variant="primary" className="!px-5 !py-2.5 !text-[13px]">
            Save condition
          </Button>
        </div>
      </form>

      <FormSection title="Danger zone" tone="danger" className="mt-6">
        <form action={deleteCondition}>
          <input type="hidden" name="id" value={condition.id} />
          <ConfirmButton
            label="Delete condition"
            confirmLabel="Click again to delete permanently"
            tone="danger"
          />
        </form>
      </FormSection>
    </>
  );
}
