import type { Metadata } from "next";
import { desc } from "drizzle-orm";
import Link from "next/link";
import { Users, Download, KeyRound } from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
import {
  AdminHeading,
  FormSection,
  InputField,
  StatusBadge,
  EmptyState,
  Toolbar,
  FilterPill,
  SearchInput,
  KpiCard,
  formatAdminDate,
} from "@/components/admin";
import { Button } from "@/components/Button";
import {
  setMemberRole,
  setMemberStatus,
  updateMemberProfile,
  issueMemberPasswordReset,
} from "./actions";
import { BulkActionBar } from "./BulkActionBar";

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

const STATUS_OPTIONS = ["pending", "active", "rejected", "suspended"] as const;
const STATUS_FILTERS = ["all", "pending", "active", "rejected", "suspended"] as const;
const ROLE_FILTERS = ["all", "admin", "user"] as const;
type StatusFilter = (typeof STATUS_FILTERS)[number];
type RoleFilter = (typeof ROLE_FILTERS)[number];

function isStatusFilter(v: string | undefined): v is StatusFilter {
  return typeof v === "string" && (STATUS_FILTERS as readonly string[]).includes(v);
}
function isRoleFilter(v: string | undefined): v is RoleFilter {
  return typeof v === "string" && (ROLE_FILTERS as readonly string[]).includes(v);
}

export default async function AdminMembersPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; role?: string; q?: string }>;
}) {
  const session = await requireAdmin();
  const selfId = (session.user as { id?: string }).id ?? "";
  const params = await searchParams;
  const statusFilter: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const roleFilter: RoleFilter = isRoleFilter(params.role) ? params.role : "all";
  const query = (params.q ?? "").trim().toLowerCase();

  const rows = await db.select().from(users).orderBy(desc(users.createdAt));
  const totalMembers = rows.length;
  const activeCount = rows.filter((r) => r.status === "active").length;
  const pendingCount = rows.filter((r) => r.status === "pending").length;
  const adminCount = rows.filter((r) => r.role === "admin").length;

  let filtered = rows;
  if (statusFilter !== "all") filtered = filtered.filter((r) => r.status === statusFilter);
  if (roleFilter !== "all") filtered = filtered.filter((r) => r.role === roleFilter);
  if (query) {
    filtered = filtered.filter((r) =>
      [r.name, r.email, r.institution, r.country, r.professionalRole]
        .join(" ")
        .toLowerCase()
        .includes(query),
    );
  }

  const buildHref = (patch: Partial<{ status: StatusFilter; role: RoleFilter }>) => {
    const nextStatus = patch.status ?? statusFilter;
    const nextRole = patch.role ?? roleFilter;
    const parts: string[] = [];
    if (nextStatus !== "all") parts.push(`status=${nextStatus}`);
    if (nextRole !== "all") parts.push(`role=${nextRole}`);
    if (query) parts.push(`q=${encodeURIComponent(query)}`);
    return `/admin/members${parts.length ? `?${parts.join("&")}` : ""}`;
  };

  return (
    <>
      <AdminHeading
        eyebrow="People"
        title="Members"
        lede="Everyone with an OrthoGlobe account — active, pending, or suspended."
        actions={
          <Link
            href="/admin/members/export"
            className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-line)] bg-white px-3 py-1.5 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
          >
            <Download className="h-3.5 w-3.5" aria-hidden />
            Export CSV
          </Link>
        }
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Total members" value={totalMembers} tone="ink" Icon={Users} />
        <KpiCard label="Active" value={activeCount} tone="emerald" />
        <KpiCard label="Pending" value={pendingCount} tone="blue" />
        <KpiCard label="Admins" value={adminCount} tone="slate" />
      </div>

      <div className="mb-4">
        <Toolbar
          actions={
            <form method="GET" action="/admin/members">
              {statusFilter !== "all" && <input type="hidden" name="status" value={statusFilter} />}
              {roleFilter !== "all" && <input type="hidden" name="role" value={roleFilter} />}
              <SearchInput defaultValue={params.q ?? ""} placeholder="Search by name, email, institution…" />
            </form>
          }
        >
          <div className="flex flex-wrap items-center gap-1.5">
            <span className="text-[10px] font-bold uppercase tracking-[0.15em] text-[var(--color-slate)]">
              Status
            </span>
            {STATUS_FILTERS.map((s) => (
              <FilterPill
                key={s}
                href={buildHref({ status: s })}
                label={s}
                active={statusFilter === s}
              />
            ))}
          </div>
          <div className="flex flex-wrap items-center gap-1.5">
            <span className="text-[10px] font-bold uppercase tracking-[0.15em] text-[var(--color-slate)]">
              Role
            </span>
            {ROLE_FILTERS.map((r) => (
              <FilterPill
                key={r}
                href={buildHref({ role: r })}
                label={r}
                active={roleFilter === r}
              />
            ))}
          </div>
        </Toolbar>
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          Icon={Users}
          title="No matching members"
          description="Try a different filter or search term."
        />
      ) : (
        <>
          <BulkActionBar
            memberIds={filtered.map((u) => u.id)}
            selfId={selfId}
          />
          <ul className="space-y-4">
          {filtered.map((u) => {
            const isSelf = u.id === selfId;
            return (
              <li key={u.id}>
                <FormSection
                  title={
                    <span className="inline-flex items-center gap-2">
                      {!isSelf && (
                        <input
                          type="checkbox"
                          data-member-select={u.id}
                          aria-label={`Select ${u.name}`}
                          className="h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)] focus:ring-2 focus:ring-[var(--color-blue)]/20"
                        />
                      )}
                      <span>{u.name}</span>
                    </span>
                  }
                  description={u.email}
                  actions={
                    <div className="flex flex-wrap items-center gap-2">
                      {isSelf && (
                        <StatusBadge label="You" tone="accent" />
                      )}
                      <StatusBadge label={u.status} dot />
                      <StatusBadge label={u.role} />
                    </div>
                  }
                >
                  <div className="flex flex-wrap gap-4 text-[13px] text-[var(--color-slate)]">
                    <span>
                      <strong className="text-[var(--color-ink)]">Institution:</strong>{" "}
                      {u.institution || "—"}
                    </span>
                    <span>
                      <strong className="text-[var(--color-ink)]">Country:</strong>{" "}
                      {u.country || "—"}
                    </span>
                    <span>
                      <strong className="text-[var(--color-ink)]">Role:</strong>{" "}
                      {u.professionalRole || "—"}
                    </span>
                    <span>
                      <strong className="text-[var(--color-ink)]">Joined:</strong>{" "}
                      {formatAdminDate(u.createdAt)}
                    </span>
                  </div>

                  <form
                    action={updateMemberProfile}
                    className="mt-5 grid gap-3 md:grid-cols-2"
                  >
                    <input type="hidden" name="id" value={u.id} />
                    <InputField
                      label="Name"
                      name="name"
                      type="text"
                      required
                      defaultValue={u.name}
                    />
                    <InputField
                      label="Country"
                      name="country"
                      type="text"
                      required
                      defaultValue={u.country}
                    />
                    <InputField
                      label="Institution"
                      name="institution"
                      type="text"
                      required
                      defaultValue={u.institution}
                    />
                    <InputField
                      label="Professional role"
                      name="professionalRole"
                      type="text"
                      required
                      defaultValue={u.professionalRole}
                    />
                    <div className="md:col-span-2">
                      <Button type="submit" variant="secondary" className="!px-4 !py-2 !text-[13px]">
                        Save profile
                      </Button>
                    </div>
                  </form>

                  {!isSelf && (
                    <div className="mt-5 flex flex-wrap items-center gap-2 border-t border-[var(--color-line)] pt-4">
                      <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                        Status
                      </span>
                      {STATUS_OPTIONS.map((s) => (
                        <form key={s} action={setMemberStatus}>
                          <input type="hidden" name="id" value={u.id} />
                          <input type="hidden" name="status" value={s} />
                          <button
                            type="submit"
                            disabled={u.status === s}
                            className={
                              u.status === s
                                ? "rounded-full bg-[var(--color-blue)] px-3 py-1 text-[12px] font-semibold text-white"
                                : "rounded-full bg-[var(--color-line)]/50 px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                            }
                          >
                            {s}
                          </button>
                        </form>
                      ))}
                      <span className="ml-4 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                        Role
                      </span>
                      <form action={setMemberRole}>
                        <input type="hidden" name="id" value={u.id} />
                        <input
                          type="hidden"
                          name="role"
                          value={u.role === "admin" ? "user" : "admin"}
                        />
                        <button
                          type="submit"
                          className="rounded-full bg-white px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] ring-1 ring-[var(--color-line)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                        >
                          {u.role === "admin" ? "Demote to user" : "Promote to admin"}
                        </button>
                      </form>
                      <form action={issueMemberPasswordReset} className="ml-auto">
                        <input type="hidden" name="id" value={u.id} />
                        <button
                          type="submit"
                          aria-label={`Send password-reset email to ${u.name}`}
                          title="Send this member a password-reset email"
                          className="inline-flex items-center gap-1 rounded-full bg-white px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] ring-1 ring-[var(--color-line)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                        >
                          <KeyRound className="h-3 w-3" aria-hidden />
                          Send password reset
                        </button>
                      </form>
                    </div>
                  )}
                </FormSection>
              </li>
            );
          })}
          </ul>
        </>
      )}
    </>
  );
}
