import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { toast } from "sonner";
import {
  ShieldCheck,
  Building2,
  GraduationCap,
  CheckCircle2,
  XCircle,
  Clock,
  ArrowLeft,
} from "lucide-react";

type Status = "pending" | "active" | "suspended";
type RoleKey = "school" | "trainer" | "government" | "admin";

type Row = {
  id: string;
  full_name: string | null;
  organization: string | null;
  phone: string | null;
  bio: string | null;
  status: Status;
  created_at: string;
  role: RoleKey;
};

export const Route = createFileRoute("/_authenticated/admin/verifications")({
  head: () => ({ meta: [{ title: "Verifications · Admin" }] }),
  component: AdminVerifications,
});

function AdminVerifications() {
  const { hasRole, loading } = useAuth();
  const navigate = useNavigate();
  const [rows, setRows] = useState<Row[] | null>(null);
  const [filter, setFilter] = useState<"all" | "school" | "trainer">("all");

  useEffect(() => {
    if (loading) return;
    if (!hasRole("admin")) {
      navigate({ to: "/dashboard", replace: true });
      return;
    }
    void load();
  }, [loading, hasRole]);

  async function load() {
    const { data: profiles, error } = await supabase
      .from("profiles")
      .select("id, full_name, organization, phone, bio, status, created_at")
      .order("created_at", { ascending: false });
    if (error) {
      toast.error(error.message);
      return;
    }
    const { data: roles } = await supabase
      .from("user_roles")
      .select("user_id, role");
    const roleMap = new Map<string, RoleKey>();
    (roles ?? []).forEach((r) => roleMap.set(r.user_id, r.role as RoleKey));
    const merged = (profiles ?? []).map((p) => ({
      ...p,
      role: roleMap.get(p.id) ?? ("school" as RoleKey),
    })) as Row[];
    setRows(merged.filter((r) => r.role === "school" || r.role === "trainer"));
  }

  async function setStatus(id: string, status: Status) {
    const prev = rows;
    setRows((rs) => rs?.map((r) => (r.id === id ? { ...r, status } : r)) ?? null);
    const { error } = await supabase.from("profiles").update({ status }).eq("id", id);
    if (error) {
      setRows(prev);
      toast.error(error.message);
      return;
    }
    toast.success(
      status === "active"
        ? "Approved"
        : status === "suspended"
          ? "Suspended"
          : "Marked pending",
    );
  }

  const visible = (rows ?? []).filter((r) => filter === "all" || r.role === filter);
  const pendingCount = (rows ?? []).filter((r) => r.status === "pending").length;
  const activeCount = (rows ?? []).filter((r) => r.status === "active").length;
  const suspendedCount = (rows ?? []).filter((r) => r.status === "suspended").length;

  return (
    <div className="min-h-screen bg-background">
      <header className="sticky top-0 z-30 backdrop-blur bg-background/80 border-b border-border/60">
        <div className="max-w-6xl mx-auto flex h-16 items-center gap-3 px-4 sm:px-6">
          <Button asChild variant="ghost" size="sm" className="gap-1.5">
            <Link to="/dashboard">
              <ArrowLeft className="h-4 w-4" />
              <span className="hidden sm:inline">Dashboard</span>
            </Link>
          </Button>
          <div className="flex items-center gap-2">
            <ShieldCheck className="h-5 w-5 text-primary" />
            <h1 className="font-semibold">Verifications</h1>
          </div>
        </div>
      </header>

      <main className="max-w-6xl w-full mx-auto px-4 sm:px-6 py-8 space-y-6">
        <div className="grid sm:grid-cols-3 gap-3">
          <MetricCard icon={Clock} label="Pending" value={pendingCount} tone="warning" />
          <MetricCard icon={CheckCircle2} label="Approved" value={activeCount} tone="success" />
          <MetricCard icon={XCircle} label="Suspended" value={suspendedCount} tone="destructive" />
        </div>

        <Tabs value={filter} onValueChange={(v) => setFilter(v as typeof filter)}>
          <TabsList>
            <TabsTrigger value="all">All</TabsTrigger>
            <TabsTrigger value="school">Schools</TabsTrigger>
            <TabsTrigger value="trainer">Trainers</TabsTrigger>
          </TabsList>
          <TabsContent value={filter} className="mt-4 space-y-3">
            {rows === null && (
              <p className="text-sm text-muted-foreground">Loading…</p>
            )}
            {rows !== null && visible.length === 0 && (
              <Card className="border-border/60">
                <CardContent className="py-10 text-center text-sm text-muted-foreground">
                  Nothing here.
                </CardContent>
              </Card>
            )}
            {visible.map((r) => (
              <VerificationRow key={r.id} row={r} onSetStatus={setStatus} />
            ))}
          </TabsContent>
        </Tabs>
      </main>
    </div>
  );
}

function MetricCard({
  icon: Icon,
  label,
  value,
  tone,
}: {
  icon: typeof ShieldCheck;
  label: string;
  value: number;
  tone: "warning" | "success" | "destructive";
}) {
  const toneClass = {
    warning: "text-amber-600",
    success: "text-success",
    destructive: "text-destructive",
  }[tone];
  return (
    <Card className="border-border/60">
      <CardHeader className="pb-2 flex flex-row items-center justify-between space-y-0">
        <CardDescription>{label}</CardDescription>
        <Icon className={`h-4 w-4 ${toneClass}`} />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
      </CardContent>
    </Card>
  );
}

function VerificationRow({
  row,
  onSetStatus,
}: {
  row: Row;
  onSetStatus: (id: string, status: Status) => void;
}) {
  const RoleIcon = row.role === "trainer" ? GraduationCap : Building2;
  const statusBadge =
    row.status === "active" ? (
      <Badge className="bg-success text-success-foreground">Approved</Badge>
    ) : row.status === "suspended" ? (
      <Badge variant="destructive">Suspended</Badge>
    ) : (
      <Badge variant="secondary">Pending</Badge>
    );

  return (
    <Card className="border-border/60">
      <CardContent className="py-4">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div className="flex items-start gap-3 min-w-0">
            <div className="h-10 w-10 rounded-lg bg-primary/10 text-primary flex items-center justify-center shrink-0">
              <RoleIcon className="h-5 w-5" />
            </div>
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-2">
                <span className="font-semibold truncate">
                  {row.full_name || "Unnamed"}
                </span>
                <Badge variant="outline" className="capitalize">
                  {row.role}
                </Badge>
                {statusBadge}
              </div>
              <div className="text-sm text-muted-foreground mt-0.5 truncate">
                {row.organization || "—"}
                {row.phone ? ` · ${row.phone}` : ""}
              </div>
              {row.bio && (
                <p className="text-sm text-muted-foreground mt-1 line-clamp-2 max-w-prose">
                  {row.bio}
                </p>
              )}
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            {row.status !== "active" && (
              <Button
                size="sm"
                onClick={() => onSetStatus(row.id, "active")}
                className="gap-1.5"
              >
                <CheckCircle2 className="h-4 w-4" />
                Approve
              </Button>
            )}
            {row.status !== "suspended" && (
              <Button
                size="sm"
                variant="outline"
                onClick={() => onSetStatus(row.id, "suspended")}
                className="gap-1.5"
              >
                <XCircle className="h-4 w-4" />
                Suspend
              </Button>
            )}
            {row.status !== "pending" && (
              <Button
                size="sm"
                variant="ghost"
                onClick={() => onSetStatus(row.id, "pending")}
                className="gap-1.5"
              >
                <Clock className="h-4 w-4" />
                Reset
              </Button>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
