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

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

type Member = Awaited<ReturnType<typeof listTeamMembersForAdmin>>[number];

const ROLE_FILTERS = ["all", "lead", "committee", "contributor"] as const;
type RoleFilter = (typeof ROLE_FILTERS)[number];
function isRoleFilter(v: string | undefined): v is RoleFilter {
  return typeof v === "string" && (ROLE_FILTERS as readonly string[]).includes(v);
}

export default async function AdminTeamPage({
  searchParams,
}: {
  searchParams: Promise<{ role?: string; q?: string }>;
}) {
  const params = await searchParams;
  const roleFilter: RoleFilter = isRoleFilter(params.role) ? params.role : "all";
  const query = (params.q ?? "").trim().toLowerCase();

  const members = await listTeamMembersForAdmin();
  const total = members.length;
  const active = members.filter((m) => m.status === "active").length;
  const leads = members.filter((m) => m.role === "lead").length;
  const committee = members.filter((m) => m.role === "committee").length;

  let filtered = members;
  if (roleFilter !== "all") filtered = filtered.filter((m) => m.role === roleFilter);
  if (query) {
    filtered = filtered.filter((m) =>
      [m.name, m.title, m.institution, m.country]
        .join(" ")
        .toLowerCase()
        .includes(query),
    );
  }

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

  const columns: Column<Member>[] = [
    {
      key: "name",
      header: "Member",
      cell: (m) => (
        <div className="min-w-0">
          <Link
            href={`/admin/team/${m.id}`}
            className="truncate font-semibold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {m.name}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">{m.title}</div>
        </div>
      ),
    },
    {
      key: "institution",
      header: "Institution",
      cell: (m) => <span className="text-[13px] text-[var(--color-ink)]/80">{m.institution}</span>,
    },
    {
      key: "role",
      header: "Role",
      cell: (m) => <StatusBadge label={m.role} />,
    },
    {
      key: "status",
      header: "Status",
      cell: (m) => <StatusBadge label={m.status} dot />,
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (m) => (
        <Link
          href={`/admin/team/${m.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Edit →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="People"
        title="Team"
        lede="Leadership, committee, and contributing surgeons."
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Total" value={total} Icon={UsersRound} tone="ink" />
        <KpiCard label="Active" value={active} tone="emerald" />
        <KpiCard label="Leads" value={leads} tone="blue" />
        <KpiCard label="Committee" value={committee} tone="slate" />
      </div>

      <div className="mb-6">
        <FormSection title="New member">
          <form action={createTeamMember} className="grid gap-4 md:grid-cols-3">
            <InputField label="Name" name="name" required minLength={2} maxLength={200} />
            <InputField label="Title" name="title" maxLength={200} />
            <SelectField
              label="Role"
              name="role"
              defaultValue="contributor"
              options={[
                { value: "lead", label: "Lead" },
                { value: "committee", label: "Committee" },
                { value: "contributor", label: "Contributor" },
              ]}
            />
            <div className="md:col-span-3">
              <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                Create member
              </Button>
            </div>
          </form>
        </FormSection>
      </div>

      <div className="mb-4">
        <Toolbar
          actions={
            <form method="GET" action="/admin/team">
              {roleFilter !== "all" && <input type="hidden" name="role" value={roleFilter} />}
              <SearchInput defaultValue={params.q ?? ""} placeholder="Search name, title, institution…" />
            </form>
          }
        >
          {ROLE_FILTERS.map((r) => (
            <FilterPill key={r} href={buildHref(r)} label={r} active={roleFilter === r} />
          ))}
        </Toolbar>
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          Icon={UsersRound}
          title="No members match"
          description="Try a different role or search term."
        />
      ) : (
        <DataTable columns={columns} rows={filtered} rowKey={(m) => m.id} />
      )}
    </>
  );
}
