import type { Metadata } from "next";
import Link from "next/link";
import { Pencil, Plus } from "lucide-react";
import { Button } from "@/components/Button";
import {
  listProceduresForAdmin,
  listDistinctRegions,
  getProcedureKpis,
} from "@/lib/consentiq/queries";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  FormSection,
  InputField,
  KpiCard,
  Toolbar,
  FilterPill,
  SearchInput,
  formatAdminRelative,
  type Column,
} from "@/components/admin";
import { createProcedure } from "./actions";

export const metadata: Metadata = { title: "ConsentIQ procedures" };
export const dynamic = "force-dynamic";

const STATUS_FILTERS = ["all", "published", "draft", "archived"] as const;
type StatusFilter = (typeof STATUS_FILTERS)[number];
function isStatusFilter(v: string | undefined): v is StatusFilter {
  return typeof v === "string" && (STATUS_FILTERS as readonly string[]).includes(v);
}

type Row = Awaited<ReturnType<typeof listProceduresForAdmin>>[number];

const columns: Column<Row>[] = [
  {
    key: "name",
    header: "Procedure",
    cell: (r) => (
      <div>
        <div className="font-semibold text-[var(--color-ink)]">{r.name}</div>
        <div className="text-[11px] text-[var(--color-slate)]">/{r.slug}</div>
      </div>
    ),
  },
  {
    key: "region",
    header: "Region",
    cell: (r) => (
      <span className="inline-flex items-center rounded-full bg-[var(--color-mist)] px-2.5 py-0.5 text-[11px] font-semibold text-[var(--color-blue)]">
        {r.region || "—"}
      </span>
    ),
  },
  {
    key: "counts",
    header: "Content",
    cell: (r) => (
      <span className="text-[12px] text-[var(--color-slate)]">
        {r.risks.length} risks · {r.options.length} options · {r.recovery.length} recovery steps
      </span>
    ),
  },
  {
    key: "status",
    header: "Status",
    cell: (r) => <StatusBadge label={r.status} dot />,
  },
  {
    key: "updatedAt",
    header: "Updated",
    cell: (r) => (
      <span className="text-[12px] text-[var(--color-slate)]">
        {formatAdminRelative(r.updatedAt)}
      </span>
    ),
  },
  {
    key: "actions",
    header: "",
    align: "right",
    cell: (r) => (
      <Link
        href={`/admin/consentiq/${r.id}`}
        className="inline-flex items-center gap-1 rounded-md bg-[var(--color-blue)] px-2.5 py-1 text-[12px] font-semibold text-white transition-colors hover:bg-[var(--color-blue-deep)]"
      >
        <Pencil className="h-3 w-3" aria-hidden />
        Edit
      </Link>
    ),
  },
];

function buildQuery(q: Record<string, string | undefined>): string {
  const usp = new URLSearchParams();
  Object.entries(q).forEach(([k, v]) => {
    if (!v) return;
    usp.set(k, v);
  });
  const s = usp.toString();
  return s ? `?${s}` : "";
}

export default async function AdminConsentIQPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; status?: string; region?: string }>;
}) {
  const params = await searchParams;
  const q = (params.q ?? "").trim();
  const status: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const region = (params.region ?? "").trim();

  const [rows, regions, kpis] = await Promise.all([
    listProceduresForAdmin({ q, status, region }),
    listDistinctRegions(),
    getProcedureKpis(),
  ]);

  return (
    <>
      <AdminHeading
        eyebrow="Content"
        title="ConsentIQ procedures"
        lede="Author surgical consent scenarios — risks, benefits, alternatives, and recovery. Published items show on /products/consentiq/procedures."
      />

      <div className="mb-6 grid gap-3 md:grid-cols-3">
        <KpiCard label="Total procedures" value={kpis.total.toLocaleString()} />
        <KpiCard label="Published" value={kpis.published.toLocaleString()} tone="emerald" />
        <KpiCard label="Body regions" value={kpis.regions.toLocaleString()} tone="slate" />
      </div>

      <FormSection
        title="Add a new procedure"
        description="Start with a name and body region — you can add risks, options, recovery, and alternatives on the next screen."
      >
        <form action={createProcedure} className="grid gap-3 md:grid-cols-[2fr_1fr_auto]">
          <InputField
            label="Procedure name"
            name="name"
            required
            minLength={3}
            maxLength={200}
            placeholder="e.g. Arthroscopic Rotator Cuff Repair"
          />
          <InputField
            label="Body region"
            name="region"
            required
            defaultValue="Shoulder"
            maxLength={100}
          />
          <div className="flex items-end">
            <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
              <Plus className="mr-1 h-3.5 w-3.5" aria-hidden />
              Create draft
            </Button>
          </div>
        </form>
      </FormSection>

      <div className="mt-6" />

      <Toolbar
        actions={
          <form method="get" action="/admin/consentiq" className="flex items-center gap-2">
            {status !== "all" ? <input type="hidden" name="status" value={status} /> : null}
            {region ? <input type="hidden" name="region" value={region} /> : null}
            <SearchInput name="q" defaultValue={q} placeholder="Search procedure or summary…" />
            <Button type="submit" variant="ghost" className="!px-3 !py-1.5 !text-[12px]">
              Search
            </Button>
          </form>
        }
      >
        {STATUS_FILTERS.map((s) => (
          <FilterPill
            key={s}
            href={`/admin/consentiq${buildQuery({ status: s === "all" ? undefined : s, q: q || undefined, region: region || undefined })}`}
            label={s === "all" ? "All" : s[0].toUpperCase() + s.slice(1)}
            active={status === s}
          />
        ))}
        {regions.length > 0 ? (
          <>
            <span className="mx-1 text-[var(--color-line)]">|</span>
            <FilterPill
              href={`/admin/consentiq${buildQuery({ status: status === "all" ? undefined : status, q: q || undefined })}`}
              label="All regions"
              active={!region}
            />
            {regions.map((r) => (
              <FilterPill
                key={r}
                href={`/admin/consentiq${buildQuery({ status: status === "all" ? undefined : status, q: q || undefined, region: r })}`}
                label={r}
                active={region === r}
              />
            ))}
          </>
        ) : null}
      </Toolbar>

      <p className="mt-4 text-[12px] text-[var(--color-slate)]">
        {rows.length.toLocaleString()} procedure{rows.length === 1 ? "" : "s"}
      </p>

      <DataTable
        columns={columns}
        rows={rows}
        rowKey={(r) => r.id}
        emptyMessage="No procedures match those filters."
      />
    </>
  );
}
