import type { Metadata } from "next";
import Link from "next/link";
import { Pencil, Plus, ExternalLink } from "lucide-react";
import { Button } from "@/components/Button";
import {
  listRegionsForAdmin,
  listConditionsForAdmin,
  getAtlasKpis,
} from "@/lib/atlas/queries";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  FormSection,
  InputField,
  SelectField,
  KpiCard,
  Toolbar,
  FilterPill,
  SearchInput,
  formatAdminRelative,
  type Column,
} from "@/components/admin";
import { createRegion, createCondition } from "./actions";

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

const CATEGORY_VALUES = [
  "Degenerative",
  "Traumatic",
  "Inflammatory",
  "Congenital",
  "Infectious",
  "Neoplastic",
] as const;

type RegionRow = Awaited<ReturnType<typeof listRegionsForAdmin>>[number];
type ConditionRow = Awaited<ReturnType<typeof listConditionsForAdmin>>[number];

const regionColumns: Column<RegionRow>[] = [
  {
    key: "name",
    header: "Region",
    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: "summary",
    header: "Summary",
    cell: (r) => (
      <span className="line-clamp-2 text-[13px] text-[var(--color-slate)]">
        {r.summary || "—"}
      </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) => (
      <div className="flex justify-end gap-2">
        <Link
          href={`/products/atlas/regions/${r.slug}`}
          target="_blank"
          rel="noreferrer"
          className="inline-flex items-center gap-1 rounded-md border border-[var(--color-line)] px-2 py-1 text-[12px] font-semibold text-[var(--color-slate)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
        >
          <ExternalLink className="h-3 w-3" aria-hidden />
          View
        </Link>
        <Link
          href={`/admin/atlas/regions/${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 hover:bg-[var(--color-blue-deep)]"
        >
          <Pencil className="h-3 w-3" aria-hidden />
          Edit
        </Link>
      </div>
    ),
  },
];

const conditionColumns: Column<ConditionRow>[] = [
  {
    key: "name",
    header: "Condition",
    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.regionSlug}
      </span>
    ),
  },
  {
    key: "category",
    header: "Category",
    cell: (r) => <StatusBadge label={r.category} />,
  },
  {
    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) => (
      <div className="flex justify-end gap-2">
        <Link
          href={`/products/atlas/conditions/${r.slug}`}
          target="_blank"
          rel="noreferrer"
          className="inline-flex items-center gap-1 rounded-md border border-[var(--color-line)] px-2 py-1 text-[12px] font-semibold text-[var(--color-slate)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
        >
          <ExternalLink className="h-3 w-3" aria-hidden />
          View
        </Link>
        <Link
          href={`/admin/atlas/conditions/${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 hover:bg-[var(--color-blue-deep)]"
        >
          <Pencil className="h-3 w-3" aria-hidden />
          Edit
        </Link>
      </div>
    ),
  },
];

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}` : "";
}

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);
}

export default async function AdminAtlasPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; status?: string; region?: string; category?: 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 category = (params.category ?? "").trim();

  const [regions, conditions, kpis] = await Promise.all([
    listRegionsForAdmin(),
    listConditionsForAdmin({ q, regionSlug: region, category, status }),
    getAtlasKpis(),
  ]);

  return (
    <>
      <AdminHeading
        eyebrow="Content"
        title="Orthopaedic Atlas"
        lede="Edit the 7 body regions and every surgeon-reviewed condition. Published items appear at /products/atlas/regions and /products/atlas/conditions."
      />

      <div className="mb-6 grid gap-3 md:grid-cols-4">
        <KpiCard label="Regions" value={kpis.regions.toLocaleString()} />
        <KpiCard label="Conditions" value={kpis.conditions.toLocaleString()} />
        <KpiCard
          label="Published"
          value={kpis.publishedConditions.toLocaleString()}
          tone="emerald"
        />
        <KpiCard
          label="Categories"
          value={kpis.categories.toLocaleString()}
          tone="slate"
        />
      </div>

      <FormSection
        title="Add a region"
        description="Regions group conditions on /products/atlas."
      >
        <form action={createRegion} className="grid gap-3 md:grid-cols-[2fr_1fr_auto]">
          <InputField
            label="Region name"
            name="name"
            required
            minLength={2}
            maxLength={200}
            placeholder="e.g. Foot & Ankle"
          />
          <InputField
            label="Slug (optional)"
            name="slug"
            maxLength={80}
            placeholder="auto from name"
          />
          <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 region
            </Button>
          </div>
        </form>
      </FormSection>

      <div className="mt-4">
        <DataTable
          columns={regionColumns}
          rows={regions}
          rowKey={(r) => r.id}
          emptyMessage="No regions yet."
        />
      </div>

      <div className="mt-10" />

      <FormSection
        title="Add a condition"
        description="Start with a name, region, and category — full content fields appear on the next screen."
      >
        <form action={createCondition} className="grid gap-3 md:grid-cols-[2fr_1fr_1fr_auto]">
          <InputField
            label="Condition name"
            name="name"
            required
            minLength={2}
            maxLength={200}
            placeholder="e.g. Osteochondritis dissecans"
          />
          <SelectField label="Region" name="regionSlug" required defaultValue={regions[0]?.slug ?? ""}>
            {regions.map((r) => (
              <option key={r.id} value={r.slug}>
                {r.name}
              </option>
            ))}
          </SelectField>
          <SelectField label="Category" name="category" defaultValue="Degenerative">
            {CATEGORY_VALUES.map((c) => (
              <option key={c} value={c}>
                {c}
              </option>
            ))}
          </SelectField>
          <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/atlas" 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}
            {category ? <input type="hidden" name="category" value={category} /> : null}
            <SearchInput
              name="q"
              defaultValue={q}
              placeholder="Search condition name 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/atlas${buildQuery({
              status: s === "all" ? undefined : s,
              q: q || undefined,
              region: region || undefined,
              category: category || undefined,
            })}`}
            label={s === "all" ? "All" : s[0].toUpperCase() + s.slice(1)}
            active={status === s}
          />
        ))}
        <span className="mx-1 text-[var(--color-line)]">|</span>
        <FilterPill
          href={`/admin/atlas${buildQuery({
            status: status === "all" ? undefined : status,
            q: q || undefined,
            category: category || undefined,
          })}`}
          label="All regions"
          active={!region}
        />
        {regions.map((r) => (
          <FilterPill
            key={r.id}
            href={`/admin/atlas${buildQuery({
              status: status === "all" ? undefined : status,
              q: q || undefined,
              region: r.slug,
              category: category || undefined,
            })}`}
            label={r.name}
            active={region === r.slug}
          />
        ))}
      </Toolbar>

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

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