import { Link } from "@tanstack/react-router";
import { Compass, GraduationCap, Shield } from "lucide-react";
import { APPLICATION_KINDS, MEMBER_CATEGORIES, ROLE_DISPLAY, STATUS_LABEL } from "@/lib/privileges";
import { formatDateTime } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import type { HubApplication } from "@/lib/server/api-hub";

const PIPELINE_GROUPS = [
  { id: "pending", label: "New", statuses: ["pending"] },
  { id: "in_review", label: "In Review", statuses: ["in_review"] },
  { id: "offered", label: "Offered / seated", statuses: ["approved", "offered_fan", "offered_volunteer"] },
  { id: "declined", label: "Declined", statuses: ["declined"] },
] as const;

export function StatusPill({ status }: { status: string }) {
  const variant =
    status === "approved" || status === "posted" || status === "live" || status === "active" || status === "published" || status === "offered_fan" || status === "offered_volunteer"
      ? "success"
      : status === "in_review" || status === "assembling" || status === "scheduled" || status === "pending"
        ? "warning"
        : status === "declined" || status === "archived" || status === "not_approved" || status === "unpublished"
          ? "destructive"
          : "muted";
  return <Badge variant={variant}>{STATUS_LABEL[status] ?? status.replaceAll("_", " ")}</Badge>;
}

export function MemberOverview({
  members,
}: {
  members: { id: string; label: string; count: number }[];
}) {
  return (
    <section className="mb-6">
      <p className="mb-3 text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Member overview</p>
      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {members.map((m) => (
          <Link
            key={m.id}
            to="/admin/users"
            search={{ category: m.id }}
            className="rounded-xl bg-card p-5 shadow-[var(--shadow-border)] transition-shadow hover:shadow-[var(--shadow-border-hover)]"
          >
            <p className="font-display text-3xl tabular leading-none">{m.count}</p>
            <p className="mt-2 text-sm font-medium">{m.label}</p>
            <p className="mt-3 text-sm font-semibold text-primary">View details →</p>
          </Link>
        ))}
      </div>
    </section>
  );
}

export function ApplicationRequests({ counts }: { counts: Record<string, number> }) {
  const items = [
    { kind: "ambassador", label: "Ambassador Applications" },
    { kind: "internship", label: "Internship Applications" },
    { kind: "sponsorship", label: "Sponsorship Requests" },
    { kind: "team", label: "Submit Venture Requests" },
  ];
  return (
    <section className="mb-6">
      <p className="mb-3 text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">
        Applications & requests
      </p>
      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {items.map((item) => (
          <Link
            key={item.kind}
            to="/applications"
            search={{ kind: item.kind }}
            className="flex items-center justify-between gap-3 rounded-xl bg-card p-5 shadow-[var(--shadow-border)] transition-shadow hover:shadow-[var(--shadow-border-hover)]"
          >
            <div>
              <p className="text-sm font-medium">{item.label}</p>
              <p className="mt-1 text-sm font-semibold text-primary">Review applications →</p>
            </div>
            <p className="font-display text-3xl tabular">{counts[item.kind] ?? 0}</p>
          </Link>
        ))}
      </div>
    </section>
  );
}

export function LeagueApps() {
  const apps = [
    {
      to: "/forge-control",
      title: "Forge Control",
      body: "Contractors, payments, repository, Grant Scout — Super Admin console",
      icon: Compass,
    },
    {
      to: "/admin-hub",
      title: "Admin Hub",
      body: "People, applications, Forge Control, Donor Scout — dawn-stone-cedar-wood",
      icon: Shield,
    },
    {
      to: "/capstone",
      title: "Capstone",
      body: "Financial literacy studio — teams, packets, deal rooms",
      icon: GraduationCap,
    },
  ] as const;
  return (
    <section className="mb-6">
      <p className="mb-3 text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">League apps</p>
      <div className="grid gap-3 md:grid-cols-3">
        {apps.map((app) => {
          const Icon = app.icon;
          return (
            <Link
              key={app.to}
              to={app.to}
              className="rounded-xl bg-card p-5 shadow-[var(--shadow-border)] transition-shadow hover:shadow-[var(--shadow-border-hover)]"
            >
              <span className="flex size-10 items-center justify-center rounded-lg bg-primary/12 text-primary">
                <Icon className="size-4" />
              </span>
              <p className="mt-3 font-display text-lg">{app.title}</p>
              <p className="mt-1 text-sm text-muted-foreground">{app.body}</p>
              <p className="mt-3 text-sm font-semibold text-primary">Open →</p>
            </Link>
          );
        })}
      </div>
    </section>
  );
}

export function ApplicationPipeline({ rows }: { rows: HubApplication[] }) {
  return (
    <section className="mb-6">
      <div className="mb-3 flex items-end justify-between gap-3">
        <div>
          <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Applications pipeline</p>
          <p className="text-sm text-muted-foreground">
            {APPLICATION_KINDS.map((k) => k.label.replace(" Applications", "")).join(" · ")}
          </p>
        </div>
        <Link to="/applications" search={{ kind: "all" }} className="text-sm text-primary hover:underline">
          Open inbox
        </Link>
      </div>
      <div className="grid gap-3 lg:grid-cols-4">
        {PIPELINE_GROUPS.map((col) => {
          const list = rows.filter((r) => (col.statuses as readonly string[]).includes(r.status));
          return (
            <Card key={col.id}>
              <CardContent className="pt-5">
                <div className="mb-3 flex items-baseline justify-between">
                  <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">
                    {col.label}
                  </p>
                  <span className="font-display text-xl tabular">{list.length}</span>
                </div>
                <ul className="space-y-3">
                  {list.slice(0, 6).map((r) => (
                    <li key={r.id}>
                      <p className="text-[11px] font-medium tracking-wide text-primary uppercase">{r.kind}</p>
                      <p className="font-medium">{r.full_name}</p>
                      <p className="text-xs text-muted-foreground">{formatDateTime(r.submitted_at)}</p>
                    </li>
                  ))}
                  {list.length === 0 ? (
                    <li className="text-sm text-muted-foreground">Nothing here</li>
                  ) : null}
                </ul>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </section>
  );
}

export function DirectoryTable({
  users,
  showPassword = false,
}: {
  users: {
    id: string;
    full_name: string;
    email: string;
    title: string | null;
    role: string;
    category: string | null;
    location: string | null;
    org_name: string | null;
    status: string;
    password_hint?: string;
  }[];
  showPassword?: boolean;
}) {
  const catLabel = Object.fromEntries(MEMBER_CATEGORIES.map((c) => [c.id, c.label]));
  return (
    <Card>
      <CardContent className="overflow-x-auto pt-5">
        <table className="w-full min-w-[44rem] text-left text-sm">
          <thead className="text-[11px] font-semibold tracking-wide uppercase">
            <tr className="border-b border-border">
              <th className="pb-2 font-medium">Name</th>
              <th className="pb-2 font-medium">Email</th>
              <th className="pb-2 font-medium">Category</th>
              <th className="pb-2 font-medium">Sign-in role</th>
              <th className="pb-2 font-medium">Status</th>
              {showPassword ? <th className="pb-2 font-medium">Demo password</th> : null}
            </tr>
          </thead>
          <tbody>
            {users.map((u) => (
              <tr key={u.id} className="border-b border-border/70">
                <td className="py-2.5">
                  <p className="font-medium">{u.full_name}</p>
                  <p className="mt-1 inline-block rounded-sm bg-primary/20 px-1.5 py-0.5 text-xs font-medium text-navy">
                    {[u.title, u.location, u.org_name].filter(Boolean).join(" · ")}
                  </p>
                </td>
                <td className="py-2.5 font-mono text-xs font-medium text-navy">{u.email}</td>
                <td className="py-2.5">
                  <Badge>{catLabel[u.category ?? ""] ?? ROLE_DISPLAY[u.category ?? ""] ?? u.category ?? "—"}</Badge>
                </td>
                <td className="py-2.5">
                  <Badge>{u.role}</Badge>
                </td>
                <td className="py-2.5">
                  <StatusPill status={u.status} />
                </td>
                {showPassword ? <td className="py-2.5 font-mono text-xs">{u.password_hint}</td> : null}
              </tr>
            ))}
            {users.length === 0 ? (
              <tr>
                <td className="py-6 text-sm text-muted-foreground" colSpan={showPassword ? 6 : 5}>
                  No people in this list.
                </td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </CardContent>
    </Card>
  );
}
