import type { Metadata } from "next";
import Link from "next/link";
import { FlaskConical } from "lucide-react";
import { Button } from "@/components/Button";
import { listStudiesForAdmin } from "@/lib/research/queries";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  FormSection,
  InputField,
  SelectField,
  EmptyState,
  Toolbar,
  FilterPill,
  SearchInput,
  KpiCard,
  type Column,
} from "@/components/admin";
import { createStudy } from "./actions";

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

type Study = Awaited<ReturnType<typeof listStudiesForAdmin>>[number];

const PHASE_FILTERS = ["all", "Planned", "Recruiting", "Active", "Completed"] as const;
type PhaseFilter = (typeof PHASE_FILTERS)[number];
function isPhaseFilter(v: string | undefined): v is PhaseFilter {
  return typeof v === "string" && (PHASE_FILTERS as readonly string[]).includes(v);
}

export default async function AdminResearchPage({
  searchParams,
}: {
  searchParams: Promise<{ phase?: string; q?: string }>;
}) {
  const params = await searchParams;
  const phaseFilter: PhaseFilter = isPhaseFilter(params.phase) ? params.phase : "all";
  const query = (params.q ?? "").trim().toLowerCase();

  const rows = await listStudiesForAdmin();
  const published = rows.filter((r) => r.status === "published").length;
  const draft = rows.filter((r) => r.status === "draft").length;
  const recruiting = rows.filter((r) => r.phase === "Recruiting").length;

  let filtered = rows;
  if (phaseFilter !== "all") filtered = filtered.filter((r) => r.phase === phaseFilter);
  if (query) {
    filtered = filtered.filter((r) =>
      [r.title, r.conditionKeyword, r.sponsor, r.principalInvestigator]
        .join(" ")
        .toLowerCase()
        .includes(query),
    );
  }

  const buildHref = (phase: PhaseFilter) => {
    const parts: string[] = [];
    if (phase !== "all") parts.push(`phase=${phase}`);
    if (query) parts.push(`q=${encodeURIComponent(query)}`);
    return `/admin/research${parts.length ? `?${parts.join("&")}` : ""}`;
  };

  const columns: Column<Study>[] = [
    {
      key: "title",
      header: "Study",
      cell: (s) => (
        <div className="min-w-0">
          <Link
            href={`/admin/research/${s.id}`}
            className="truncate font-semibold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {s.title}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">
            {s.conditionKeyword || s.principalInvestigator || "—"}
          </div>
        </div>
      ),
    },
    {
      key: "phase",
      header: "Phase",
      cell: (s) => <StatusBadge label={s.phase} />,
    },
    {
      key: "enrolment",
      header: "Enrolment",
      cell: (s) => {
        const pct = s.targetEnrolment > 0
          ? Math.min(100, Math.round((s.currentEnrolment / s.targetEnrolment) * 100))
          : 0;
        return (
          <div className="min-w-[120px]">
            <div className="flex items-center justify-between text-[12px] text-[var(--color-slate)]">
              <span>{s.currentEnrolment} / {s.targetEnrolment}</span>
              <span>{pct}%</span>
            </div>
            <div className="mt-1 h-1.5 overflow-hidden rounded-full bg-[var(--color-line)]">
              <div
                className="h-full rounded-full bg-[var(--color-blue)] transition-all"
                style={{ width: `${pct}%` }}
              />
            </div>
          </div>
        );
      },
    },
    {
      key: "status",
      header: "Status",
      cell: (s) => <StatusBadge label={s.status} dot />,
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (s) => (
        <Link
          href={`/admin/research/${s.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Edit →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="Content"
        title="Research portal"
        lede="Multi-centre studies, sites, and investigators."
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Total studies" value={rows.length} Icon={FlaskConical} tone="ink" />
        <KpiCard label="Published" value={published} tone="emerald" />
        <KpiCard label="Recruiting" value={recruiting} tone="blue" />
        <KpiCard label="Drafts" value={draft} tone="amber" />
      </div>

      <div className="mb-6">
        <FormSection title="New study">
          <form action={createStudy} className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Study title"
              name="title"
              required
              minLength={3}
              maxLength={300}
              wrapClassName="md:col-span-2"
            />
            <SelectField
              label="Phase"
              name="phase"
              defaultValue="Planned"
              options={[
                { value: "Planned", label: "Planned" },
                { value: "Recruiting", label: "Recruiting" },
                { value: "Active", label: "Active" },
                { value: "Completed", label: "Completed" },
              ]}
            />
            <InputField
              label="Condition keyword"
              name="conditionKeyword"
              placeholder="e.g. Knee osteoarthritis"
              maxLength={200}
            />
            <div className="md:col-span-2">
              <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                Create study
              </Button>
            </div>
          </form>
        </FormSection>
      </div>

      <div className="mb-4">
        <Toolbar
          actions={
            <form method="GET" action="/admin/research">
              {phaseFilter !== "all" && <input type="hidden" name="phase" value={phaseFilter} />}
              <SearchInput defaultValue={params.q ?? ""} placeholder="Search title, condition, PI…" />
            </form>
          }
        >
          {PHASE_FILTERS.map((p) => (
            <FilterPill key={p} href={buildHref(p)} label={p} active={phaseFilter === p} />
          ))}
        </Toolbar>
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          Icon={FlaskConical}
          title="No studies match"
          description="Create a new study or clear filters."
        />
      ) : (
        <DataTable columns={columns} rows={filtered} rowKey={(s) => s.id} />
      )}
    </>
  );
}
