import type { Metadata } from "next";
import Link from "next/link";
import { Pencil, Plus } from "lucide-react";
import { Button } from "@/components/Button";
import {
  listQuestionsForAdmin,
  getQuestionKpis,
} from "@/lib/orthoprep/queries";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  FormSection,
  InputField,
  SelectField,
  KpiCard,
  Toolbar,
  FilterPill,
  SearchInput,
  formatAdminRelative,
  type Column,
} from "@/components/admin";
import { createQuestion } from "./actions";

export const metadata: Metadata = { title: "OrthoPrep questions" };
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 QRow = Awaited<ReturnType<typeof listQuestionsForAdmin>>["rows"][number];

const columns: Column<QRow>[] = [
  {
    key: "number",
    header: "#",
    width: "72px",
    cell: (r) => (
      <span className="font-mono text-[12px] text-[var(--color-slate)]">Q{r.number}</span>
    ),
  },
  {
    key: "stem",
    header: "Question",
    cell: (r) => (
      <div className="max-w-[520px]">
        <div className="line-clamp-2 text-[14px] font-semibold text-[var(--color-ink)]">
          {r.stem}
        </div>
        <div className="mt-0.5 text-[11px] text-[var(--color-slate)]">
          {r.part} · {r.chapter || "—"}
        </div>
      </div>
    ),
  },
  {
    key: "difficulty",
    header: "Difficulty",
    cell: (r) => <StatusBadge label={r.difficulty} />,
  },
  {
    key: "answer",
    header: "Ans",
    width: "60px",
    align: "center",
    cell: (r) => (
      <span className="inline-flex h-6 w-6 items-center justify-center rounded bg-[var(--color-blue)] text-[11px] font-bold text-white">
        {r.answer}
      </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/orthoprep/${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 | number | undefined>): string {
  const usp = new URLSearchParams();
  Object.entries(q).forEach(([k, v]) => {
    if (v === undefined || v === null || v === "") return;
    usp.set(k, String(v));
  });
  const s = usp.toString();
  return s ? `?${s}` : "";
}

export default async function AdminOrthoPrepPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; status?: string; part?: string; page?: string }>;
}) {
  const params = await searchParams;
  const q = (params.q ?? "").trim();
  const status: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const part = (params.part ?? "").trim();
  const page = Math.max(1, Number(params.page ?? 1) || 1);
  const pageSize = 50;

  const [{ rows, total }, kpis] = await Promise.all([
    listQuestionsForAdmin({
      q,
      status,
      part,
      limit: pageSize,
      offset: (page - 1) * pageSize,
    }),
    getQuestionKpis(),
  ]);

  const pageCount = Math.max(1, Math.ceil(total / pageSize));

  return (
    <>
      <AdminHeading
        eyebrow="Content"
        title="OrthoPrep question bank"
        lede="Author, review, and publish FRCS-style questions. Items show on /products/orthoprep/question-bank when published."
      />

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

      <FormSection
        title="Add a new question"
        description="Create a draft — you can flesh out options, answer, explanation and tags on the next screen."
      >
        <form action={createQuestion} className="grid gap-3 md:grid-cols-[2fr_1fr_1fr_auto]">
          <InputField
            label="Stem (question text)"
            name="stem"
            required
            minLength={10}
            maxLength={4000}
            placeholder="A 68-year-old man presents with…"
          />
          <InputField
            label="Part"
            name="part"
            required
            defaultValue="Part 1"
            maxLength={200}
          />
          <SelectField label="Difficulty" name="difficulty" defaultValue="Medium">
            <option value="Easy">Easy</option>
            <option value="Medium">Medium</option>
            <option value="Hard">Hard</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/orthoprep" className="flex items-center gap-2">
            {status !== "all" ? <input type="hidden" name="status" value={status} /> : null}
            {part ? <input type="hidden" name="part" value={part} /> : null}
            <SearchInput
              name="q"
              defaultValue={q}
              placeholder="Search stem, explanation, chapter…"
            />
            <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/orthoprep${buildQuery({
              status: s === "all" ? undefined : s,
              q: q || undefined,
              part: part || undefined,
            })}`}
            label={s === "all" ? "All" : s[0].toUpperCase() + s.slice(1)}
            active={status === s}
          />
        ))}
      </Toolbar>

      <p className="mt-4 text-[12px] text-[var(--color-slate)]">
        {total.toLocaleString()} question{total === 1 ? "" : "s"} · page {page} / {pageCount}
      </p>

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

      {pageCount > 1 ? (
        <div className="mt-4 flex items-center justify-center gap-2 text-[12px]">
          {Array.from({ length: pageCount }, (_, i) => i + 1)
            .filter((p) => p === 1 || p === pageCount || Math.abs(p - page) <= 2)
            .map((p, i, arr) => {
              const prev = arr[i - 1];
              const gap = prev !== undefined && p - prev > 1;
              return (
                <span key={p} className="contents">
                  {gap ? <span className="px-1 text-[var(--color-slate)]">…</span> : null}
                  <Link
                    href={`/admin/orthoprep${buildQuery({
                      page: p,
                      status: status === "all" ? undefined : status,
                      q: q || undefined,
                      part: part || undefined,
                    })}`}
                    className={`rounded-md border px-2 py-1 font-semibold ${p === page ? "border-[var(--color-blue)] bg-[var(--color-blue)] text-white" : "border-[var(--color-line)] text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"}`}
                  >
                    {p}
                  </Link>
                </span>
              );
            })}
        </div>
      ) : null}
    </>
  );
}
