import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { Clock, CheckCircle2, CheckCheck, Ban, XCircle, ArrowRight, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import {
  Building2,
  GraduationCap,
  Landmark,
  ShieldCheck,
  LogOut,
  Sparkles,
  Users,
  CalendarCheck,
  Wallet,
  Star,
  BarChart3,
  AlertTriangle,
  Activity,
  TrendingUp,
  MapPin,
  Award,
  FileCheck2,
  ClipboardList,
  Briefcase,
  Megaphone,
  Settings2,
} from "lucide-react";
import logo from "@/assets/skillkonnect-logo.png.asset.json";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { AppSidebar } from "@/components/app-sidebar";

export const Route = createFileRoute("/_authenticated/dashboard")({
  head: () => ({ meta: [{ title: "Dashboard · SkillKonnect" }] }),
  component: Dashboard,
});

type ProfileRow = {
  full_name: string | null;
  organization: string | null;
  status: "pending" | "active" | "suspended";
};

function Dashboard() {
  const { user, roles, signOut, hasRole } = useAuth();
  const navigate = useNavigate();
  const [profile, setProfile] = useState<ProfileRow | null>(null);

  useEffect(() => {
    if (!user) return;
    supabase
      .from("profiles")
      .select("full_name, organization, status")
      .eq("id", user.id)
      .maybeSingle()
      .then(({ data }) => data && setProfile(data as ProfileRow));
  }, [user]);

  async function handleSignOut() {
    await signOut();
    navigate({ to: "/auth", replace: true });
  }

  const primaryRole = roles[0] ?? "school";
  const roleLabel: Record<string, string> = {
    school: "School",
    trainer: "Skill Professional",
    government: "Ministry of Education",
    admin: "Platform Administrator",
  };

  return (
    <SidebarProvider>
      <div className="min-h-screen flex w-full bg-background">
        <AppSidebar />
        <div className="flex-1 flex flex-col min-w-0">
          <header className="sticky top-0 z-30 backdrop-blur bg-background/80 border-b border-border/60">
            <div className="grid h-16 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 px-3 sm:px-6">
              <div className="flex items-center gap-1 min-w-0">
                <SidebarTrigger className="shrink-0" />
                <Link to="/" className="hidden sm:flex items-center gap-2 ml-1">
                  <img src={logo.url} alt="SkillKonnect" className="h-7 w-auto" />
                </Link>
              </div>
              <div className="min-w-0" />
              <div className="flex items-center gap-2 justify-end">
                <Badge variant="secondary" className="hidden xs:inline-flex truncate max-w-[140px]">
                  {roleLabel[primaryRole] ?? primaryRole}
                </Badge>
                <Button variant="ghost" size="sm" asChild className="hidden md:inline-flex gap-1.5">
                  <Link to="/profile">Profile</Link>
                </Button>
                <Button variant="ghost" size="sm" onClick={handleSignOut} className="gap-1.5 shrink-0">
                  <LogOut className="h-4 w-4" />
                  <span className="hidden sm:inline">Sign out</span>
                </Button>
              </div>
            </div>
          </header>


          <main className="flex-1 px-4 sm:px-6 py-10 space-y-8 max-w-6xl w-full mx-auto">
            <section>
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Sparkles className="h-4 w-4 text-accent" />
                Welcome back
              </div>
              <h1 className="mt-1 text-3xl md:text-4xl font-bold tracking-tight">
                {profile?.full_name || user?.email}
              </h1>
              {profile?.organization && (
                <p className="text-muted-foreground mt-1">{profile.organization}</p>
              )}
            </section>

            {hasRole("admin") && <AdminPanel />}
            {hasRole("government") && <GovernmentPanel />}
            {hasRole("trainer") && <TrainerPanel status={profile?.status ?? "pending"} />}
            {hasRole("school") && <SchoolPanel />}
          </main>
        </div>
      </div>
    </SidebarProvider>
  );
}

function StatCard({
  icon: Icon,
  label,
  value,
  hint,
  tone = "default",
}: {
  icon: typeof Users;
  label: string;
  value: string;
  hint?: string;
  tone?: "default" | "success" | "warning" | "accent";
}) {
  const toneClass: Record<string, string> = {
    default: "text-muted-foreground",
    success: "text-success",
    warning: "text-destructive",
    accent: "text-accent",
  };
  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[tone]}`} />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {hint && <p className="text-xs text-muted-foreground mt-1">{hint}</p>}
      </CardContent>
    </Card>
  );
}

function SectionHeader({
  icon: Icon,
  title,
  description,
}: {
  icon: typeof Users;
  title: string;
  description?: string;
}) {
  return (
    <div className="flex items-start gap-3">
      <div className="h-10 w-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
        <Icon className="h-5 w-5" />
      </div>
      <div>
        <h2 className="text-xl font-semibold tracking-tight">{title}</h2>
        {description && (
          <p className="text-sm text-muted-foreground">{description}</p>
        )}
      </div>
    </div>
  );
}

/* ------------------------------- SCHOOL ------------------------------- */

type SchoolBooking = {
  id: string;
  trade: string;
  scheduled_at: string;
  duration_minutes: number;
  location: string | null;
  status: "requested" | "accepted" | "declined" | "confirmed" | "completed" | "cancelled";
};

const STATUS_META: Record<
  SchoolBooking["status"],
  { label: string; variant: "default" | "secondary" | "destructive" | "outline"; icon: typeof Clock; action: string | null }
> = {
  requested: { label: "Pending", variant: "secondary", icon: Clock, action: "Awaiting trainer response" },
  accepted: { label: "Accepted", variant: "outline", icon: CheckCircle2, action: "Confirm session" },
  confirmed: { label: "Confirmed", variant: "default", icon: CheckCheck, action: "Prepare for session" },
  completed: { label: "Completed", variant: "default", icon: CheckCheck, action: "Leave a rating" },
  declined: { label: "Declined", variant: "destructive", icon: XCircle, action: "Find another trainer" },
  cancelled: { label: "Cancelled", variant: "destructive", icon: Ban, action: "Rebook if needed" },
};

function SchoolPanel() {
  const { user } = useAuth();
  const [bookings, setBookings] = useState<SchoolBooking[]>([]);
  const [loading, setLoading] = useState(true);

  async function refresh() {
    if (!user) return;
    const { data } = await supabase
      .from("bookings")
      .select("id, trade, scheduled_at, duration_minutes, location, status")
      .eq("school_id", user.id)
      .order("scheduled_at", { ascending: true });
    setBookings((data as SchoolBooking[]) ?? []);
    setLoading(false);
  }

  useEffect(() => {
    void refresh();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user]);

  const counts = useMemo(() => {
    const c = { pending: 0, confirmed: 0, completed: 0, cancelled: 0 };
    for (const b of bookings) {
      if (b.status === "requested" || b.status === "accepted") c.pending += 1;
      else if (b.status === "confirmed") c.confirmed += 1;
      else if (b.status === "completed") c.completed += 1;
      else if (b.status === "declined" || b.status === "cancelled") c.cancelled += 1;
    }
    return c;
  }, [bookings]);

  const active = bookings
    .filter((b) => b.status !== "completed" && b.status !== "cancelled" && b.status !== "declined")
    .slice(0, 5);

  return (
    <div className="space-y-6">
      <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard icon={Clock} label="Pending" value={String(counts.pending)} hint="Awaiting trainer / your confirm" />
        <StatCard icon={CheckCheck} label="Confirmed" value={String(counts.confirmed)} tone="accent" />
        <StatCard icon={CheckCircle2} label="Completed" value={String(counts.completed)} tone="success" />
        <StatCard icon={Ban} label="Cancelled / declined" value={String(counts.cancelled)} tone="warning" />
      </div>

      <Card className="border-border/60">
        <CardHeader>
          <div className="flex items-center justify-between gap-2 flex-wrap">
            <div className="flex items-center gap-2">
              <CalendarCheck className="h-5 w-5 text-primary" />
              <CardTitle>Your bookings</CardTitle>
            </div>
            <Button asChild size="sm" variant="ghost" className="gap-1">
              <Link to="/bookings">View all <ArrowRight className="h-4 w-4" /></Link>
            </Button>
          </div>
          <CardDescription>Track status and take the next step on each session.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {loading && <p className="text-sm text-muted-foreground">Loading…</p>}
          {!loading && active.length === 0 && (
            <div className="rounded-lg border border-dashed border-border/70 p-6 text-center">
              <p className="text-sm text-muted-foreground">No active bookings yet.</p>
              <Button asChild size="sm" className="mt-3 gap-2">
                <Link to="/trainers">Find trainers</Link>
              </Button>
            </div>
          )}
          {active.map((b) => {
            const meta = STATUS_META[b.status];
            const Icon = meta.icon;
            const nextAction =
              b.status === "accepted"
                ? { label: "Confirm session", to: "/bookings" as const }
                : b.status === "completed"
                  ? { label: "Leave rating", to: "/bookings" as const }
                  : b.status === "declined" || b.status === "cancelled"
                    ? { label: "Find trainer", to: "/trainers" as const }
                    : { label: "View details", to: "/bookings" as const };
            return (
              <div
                key={b.id}
                className="flex flex-wrap items-start justify-between gap-3 rounded-lg border border-border/60 p-3"
              >
                <div className="min-w-0 space-y-1">
                  <div className="flex items-center gap-2">
                    <span className="font-medium capitalize">{b.trade}</span>
                    <Badge variant={meta.variant} className="gap-1">
                      <Icon className="h-3 w-3" />
                      {meta.label}
                    </Badge>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {new Date(b.scheduled_at).toLocaleString()} · {b.duration_minutes} min
                    {b.location ? ` · ${b.location}` : ""}
                  </p>
                  {meta.action && (
                    <p className="text-xs text-muted-foreground">Next: {meta.action}</p>
                  )}
                </div>
                <div className="flex gap-2">
                  <Button asChild size="sm" variant="outline" className="gap-1">
                    <Link to={nextAction.to}>{nextAction.label} <ArrowRight className="h-3.5 w-3.5" /></Link>
                  </Button>
                  <CancelBookingButton bookingId={b.id} onCancelled={refresh} />
                </div>
              </div>
            );
          })}
        </CardContent>
      </Card>

      <Card className="border-border/60">
        <CardHeader>
          <div className="flex items-center gap-2">
            <Building2 className="h-5 w-5 text-primary" />
            <CardTitle>Find verified trainers</CardTitle>
          </div>
          <CardDescription>Search by trade, location and certification.</CardDescription>
        </CardHeader>
        <CardContent className="flex flex-wrap gap-2">
          <Button asChild className="gap-2">
            <Link to="/trainers">Find trainers</Link>
          </Button>
          <Button asChild variant="outline">
            <Link to="/bookings">View bookings</Link>
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}

export function CancelBookingButton({
  bookingId,
  onCancelled,
  label = "Cancel",
}: {
  bookingId: string;
  onCancelled: () => void | Promise<void>;
  label?: string;
}) {
  const [open, setOpen] = useState(false);
  const [reason, setReason] = useState("");
  const [submitting, setSubmitting] = useState(false);

  async function handleCancel() {
    setSubmitting(true);
    const { error } = await supabase
      .from("bookings")
      .update({
        status: "cancelled",
        cancelled_at: new Date().toISOString(),
        cancel_reason: reason.trim() || null,
      })
      .eq("id", bookingId);
    setSubmitting(false);
    if (error) {
      toast.error(error.message);
      return;
    }
    toast.success("Booking cancelled");
    setOpen(false);
    setReason("");
    await onCancelled();
  }

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>
        <Button size="sm" variant="destructive" className="gap-1">
          <Ban className="h-3.5 w-3.5" /> {label}
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Cancel this booking?</AlertDialogTitle>
          <AlertDialogDescription>
            The other party will be notified that the session is cancelled. This cannot be undone —
            you'll need to create a new booking to reschedule.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <div className="space-y-2">
          <label className="text-sm font-medium">Reason (optional)</label>
          <Textarea
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            placeholder="Let the other party know why you're cancelling"
            rows={3}
          />
        </div>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={submitting}>Keep booking</AlertDialogCancel>
          <AlertDialogAction
            onClick={(e) => {
              e.preventDefault();
              void handleCancel();
            }}
            disabled={submitting}
            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            {submitting ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" /> Cancelling…
              </>
            ) : (
              <>Confirm cancel</>
            )}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}

/* ------------------------------- TRAINER ------------------------------- */

function TrainerPanel({
  status,
}: {
  status: "pending" | "active" | "suspended";
}) {
  const { user } = useAuth();
  const [bookings, setBookings] = useState<SchoolBooking[]>([]);
  const profileCompletion = status === "active" ? 100 : status === "pending" ? 45 : 70;

  async function refresh() {
    if (!user) return;
    const { data } = await supabase
      .from("bookings")
      .select("id, trade, scheduled_at, duration_minutes, location, status")
      .eq("trainer_id", user.id)
      .order("scheduled_at", { ascending: true });
    setBookings((data as SchoolBooking[]) ?? []);
  }

  useEffect(() => {
    void refresh();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user]);

  const upcoming = bookings.filter(
    (b) => b.status !== "completed" && b.status !== "cancelled" && b.status !== "declined",
  );
  const pendingCount = bookings.filter((b) => b.status === "requested").length;
  const upcomingCount = bookings.filter(
    (b) => b.status === "accepted" || b.status === "confirmed",
  ).length;


  return (
    <div className="space-y-6">
      <Card className="border-border/60 overflow-hidden">
        <div className="bg-gradient-to-br from-primary to-primary/80 text-primary-foreground p-6 sm:p-8">
          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div>
              <div className="flex items-center gap-2 text-sm opacity-90">
                <GraduationCap className="h-4 w-4" />
                Skill Professional
              </div>
              <h2 className="text-2xl font-bold mt-1">Your trainer workspace</h2>
              <p className="text-sm opacity-90 mt-1 max-w-md">
                Manage your trade profile, respond to booking requests and grow your reputation
                with schools across the country.
              </p>
            </div>
            <Badge
              variant="secondary"
              className="capitalize bg-white/15 text-primary-foreground border-white/20"
            >
              Verification: {status}
            </Badge>
          </div>
          <div className="mt-6 space-y-2">
            <div className="flex justify-between text-xs opacity-90">
              <span>Profile completion</span>
              <span>{profileCompletion}%</span>
            </div>
            <Progress value={profileCompletion} className="h-2 bg-white/20" />
          </div>
        </div>
        <CardContent className="pt-5 flex flex-wrap gap-2">
          <Button asChild size="sm">
            <Link to="/profile">Complete profile</Link>
          </Button>
          <Button asChild size="sm" variant="outline">
            <Link to="/bookings">View booking requests</Link>
          </Button>
        </CardContent>
      </Card>

      <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard icon={CalendarCheck} label="Upcoming sessions" value={String(upcomingCount)} />
        <StatCard icon={ClipboardList} label="Pending requests" value={String(pendingCount)} hint="Awaiting your reply" />
        <StatCard icon={Wallet} label="Earnings (₦)" value="0" tone="accent" />
        <StatCard icon={Star} label="Average rating" value="—" />
      </div>

      <Card className="border-border/60">
        <CardHeader>
          <div className="flex items-center justify-between gap-2 flex-wrap">
            <div className="flex items-center gap-2">
              <CalendarCheck className="h-5 w-5 text-primary" />
              <CardTitle>Your sessions</CardTitle>
            </div>
            <Button asChild size="sm" variant="ghost" className="gap-1">
              <Link to="/bookings">View all <ArrowRight className="h-4 w-4" /></Link>
            </Button>
          </div>
          <CardDescription>Cancel a session if you can no longer attend.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {upcoming.length === 0 && (
            <p className="text-sm text-muted-foreground">No upcoming sessions.</p>
          )}
          {upcoming.slice(0, 5).map((b) => {
            const meta = STATUS_META[b.status];
            const Icon = meta.icon;
            return (
              <div
                key={b.id}
                className="flex flex-wrap items-start justify-between gap-3 rounded-lg border border-border/60 p-3"
              >
                <div className="min-w-0 space-y-1">
                  <div className="flex items-center gap-2">
                    <span className="font-medium capitalize">{b.trade}</span>
                    <Badge variant={meta.variant} className="gap-1">
                      <Icon className="h-3 w-3" />
                      {meta.label}
                    </Badge>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {new Date(b.scheduled_at).toLocaleString()} · {b.duration_minutes} min
                    {b.location ? ` · ${b.location}` : ""}
                  </p>
                </div>
                <CancelBookingButton bookingId={b.id} onCancelled={refresh} />
              </div>
            );
          })}
        </CardContent>
      </Card>


      <div className="grid lg:grid-cols-2 gap-4">
        <Card className="border-border/60">
          <CardHeader>
            <SectionHeader
              icon={Award}
              title="Build trust"
              description="Add credentials so schools can verify you faster."
            />
          </CardHeader>
          <CardContent className="space-y-3 text-sm">
            <ChecklistRow done={status === "active"} label="Identity verified" />
            <ChecklistRow done={false} label="Trade certifications uploaded" />
            <ChecklistRow done={false} label="Sample work / portfolio added" />
            <ChecklistRow done={false} label="At least one completed session" />
          </CardContent>
        </Card>

        <Card className="border-border/60">
          <CardHeader>
            <SectionHeader
              icon={Briefcase}
              title="Opportunities"
              description="Schools currently looking for your trade."
            />
          </CardHeader>
          <CardContent className="space-y-3 text-sm text-muted-foreground">
            <p>
              When schools post requests matching your skills, they will appear here. Keep your
              availability and trade tags up to date.
            </p>
            <Button asChild size="sm" variant="outline">
              <Link to="/bookings">Open requests</Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function ChecklistRow({ done, label }: { done: boolean; label: string }) {
  return (
    <div className="flex items-center gap-2">
      <span
        className={`h-5 w-5 rounded-full flex items-center justify-center text-[10px] font-bold ${
          done ? "bg-success text-success-foreground" : "bg-muted text-muted-foreground"
        }`}
      >
        {done ? "✓" : ""}
      </span>
      <span className={done ? "" : "text-muted-foreground"}>{label}</span>
    </div>
  );
}

/* ----------------------------- GOVERNMENT ----------------------------- */

function GovernmentPanel() {
  const regions = [
    { name: "Lagos", trainers: 0, schools: 0, sessions: 0 },
    { name: "Abuja (FCT)", trainers: 0, schools: 0, sessions: 0 },
    { name: "Kano", trainers: 0, schools: 0, sessions: 0 },
    { name: "Rivers", trainers: 0, schools: 0, sessions: 0 },
  ];

  return (
    <div className="space-y-6">
      <Card className="border-border/60 overflow-hidden">
        <div className="bg-gradient-to-br from-primary to-primary/80 text-primary-foreground p-6 sm:p-8">
          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div>
              <div className="flex items-center gap-2 text-sm opacity-90">
                <Landmark className="h-4 w-4" />
                Ministry of Education
              </div>
              <h2 className="text-2xl font-bold mt-1">National oversight portal</h2>
              <p className="text-sm opacity-90 mt-1 max-w-xl">
                Monitor vocational training delivery, certification compliance and regional
                participation across all registered schools and skill professionals.
              </p>
            </div>
            <Badge
              variant="secondary"
              className="bg-white/15 text-primary-foreground border-white/20"
            >
              Read-only oversight
            </Badge>
          </div>
        </div>
      </Card>

      <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard icon={ShieldCheck} label="Verified trainers" value="0" tone="success" />
        <StatCard icon={Building2} label="Active schools" value="0" />
        <StatCard icon={BarChart3} label="Sessions this month" value="0" />
        <StatCard icon={Users} label="Students reached" value="0" tone="accent" />
      </div>

      <div className="grid lg:grid-cols-3 gap-4">
        <Card className="lg:col-span-2 border-border/60">
          <CardHeader>
            <SectionHeader
              icon={MapPin}
              title="Regional participation"
              description="Live snapshot by state."
            />
          </CardHeader>
          <CardContent>
            <div className="divide-y divide-border/60">
              {regions.map((r) => (
                <div
                  key={r.name}
                  className="grid grid-cols-4 gap-2 py-3 text-sm items-center"
                >
                  <div className="font-medium">{r.name}</div>
                  <div className="text-muted-foreground">
                    <span className="font-semibold text-foreground">{r.trainers}</span> trainers
                  </div>
                  <div className="text-muted-foreground">
                    <span className="font-semibold text-foreground">{r.schools}</span> schools
                  </div>
                  <div className="text-muted-foreground text-right">
                    <span className="font-semibold text-foreground">{r.sessions}</span> sessions
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card className="border-border/60">
          <CardHeader>
            <SectionHeader
              icon={FileCheck2}
              title="Compliance"
              description="Certification & audit status."
            />
          </CardHeader>
          <CardContent className="space-y-3 text-sm">
            <ComplianceRow label="Certified trainers" value="0%" />
            <ComplianceRow label="Schools with active program" value="0%" />
            <ComplianceRow label="Sessions with completion record" value="0%" />
          </CardContent>
        </Card>
      </div>

      <Card className="border-border/60">
        <CardHeader>
          <SectionHeader
            icon={TrendingUp}
            title="Policy & programs"
            description="Tools for ministry teams (Phase 2)."
          />
        </CardHeader>
        <CardContent className="grid sm:grid-cols-3 gap-3 text-sm">
          <FeatureTile
            icon={Megaphone}
            title="Announcements"
            body="Broadcast circulars to schools and trainers."
          />
          <FeatureTile
            icon={BarChart3}
            title="Reports"
            body="Export quarterly KPIs by state and trade."
          />
          <FeatureTile
            icon={Award}
            title="Accreditation"
            body="Review and approve training providers."
          />
        </CardContent>
      </Card>
    </div>
  );
}

function ComplianceRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-muted-foreground">{label}</span>
      <span className="font-semibold">{value}</span>
    </div>
  );
}

function FeatureTile({
  icon: Icon,
  title,
  body,
}: {
  icon: typeof Users;
  title: string;
  body: string;
}) {
  return (
    <div className="rounded-xl border border-border/60 p-4 bg-card">
      <Icon className="h-5 w-5 text-primary" />
      <div className="font-medium mt-2">{title}</div>
      <p className="text-xs text-muted-foreground mt-1">{body}</p>
    </div>
  );
}

/* -------------------------------- ADMIN ------------------------------- */

function AdminPanel() {
  return (
    <div className="space-y-6">
      <Card className="border-border/60 overflow-hidden">
        <div className="bg-gradient-to-br from-primary via-primary to-primary/80 text-primary-foreground p-6 sm:p-8">
          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div>
              <div className="flex items-center gap-2 text-sm opacity-90">
                <ShieldCheck className="h-4 w-4" />
                Platform Administrator
              </div>
              <h2 className="text-2xl font-bold mt-1">Admin console</h2>
              <p className="text-sm opacity-90 mt-1 max-w-xl">
                Full operational view of SkillKonnect — users, verifications, bookings,
                commissions and system health.
              </p>
            </div>
            <Badge
              variant="secondary"
              className="bg-white/15 text-primary-foreground border-white/20"
            >
              Super admin
            </Badge>
          </div>
        </div>
      </Card>

      <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard icon={Users} label="Total users" value="0" hint="Across all roles" />
        <StatCard
          icon={ShieldCheck}
          label="Pending verifications"
          value="0"
          tone="warning"
          hint="Trainer KYC queue"
        />
        <StatCard icon={CalendarCheck} label="Bookings (30d)" value="0" />
        <StatCard icon={Wallet} label="Platform GMV" value="₦0" tone="accent" />
      </div>

      <div className="grid lg:grid-cols-3 gap-4">
        <Card className="lg:col-span-2 border-border/60">
          <CardHeader>
            <SectionHeader
              icon={Activity}
              title="Operations queue"
              description="Items requiring admin action."
            />
          </CardHeader>
          <CardContent className="divide-y divide-border/60">
            <QueueRow
              icon={ShieldCheck}
              title="Trainer & school verifications"
              count={0}
              cta="Review"
              tone="primary"
              to="/admin/verifications"
            />
            <QueueRow
              icon={AlertTriangle}
              title="Reported bookings"
              count={0}
              cta="Investigate"
              tone="warning"
            />
            <QueueRow
              icon={Building2}
              title="School onboarding"
              count={0}
              cta="Approve"
              tone="primary"
            />
            <QueueRow
              icon={Wallet}
              title="Payout requests"
              count={0}
              cta="Process"
              tone="accent"
            />
          </CardContent>
        </Card>

        <Card className="border-border/60">
          <CardHeader>
            <SectionHeader
              icon={Activity}
              title="System health"
              description="Live platform signals."
            />
          </CardHeader>
          <CardContent className="space-y-4 text-sm">
            <HealthRow label="API uptime (24h)" value="100%" tone="success" />
            <HealthRow label="Auth success rate" value="100%" tone="success" />
            <HealthRow label="Failed payments" value="0" tone="success" />
            <HealthRow label="Open incidents" value="0" tone="success" />
          </CardContent>
        </Card>
      </div>

      <Card className="border-border/60">
        <CardHeader>
          <SectionHeader
            icon={Settings2}
            title="Platform controls"
            description="Manage roles, content and configuration."
          />
        </CardHeader>
        <CardContent className="grid sm:grid-cols-2 lg:grid-cols-4 gap-3 text-sm">
          <FeatureTile icon={Users} title="Users & roles" body="Search, suspend, change roles." />
          <FeatureTile icon={Briefcase} title="Trades catalog" body="Manage trade categories & tags." />
          <FeatureTile icon={Wallet} title="Commissions" body="Set platform fees and payout rules." />
          <FeatureTile icon={Megaphone} title="Announcements" body="Send notices to user segments." />
        </CardContent>
      </Card>
    </div>
  );
}

function QueueRow({
  icon: Icon,
  title,
  count,
  cta,
  tone,
  to,
}: {
  icon: typeof Users;
  title: string;
  count: number;
  cta: string;
  tone: "primary" | "warning" | "accent";
  to?: string;
}) {
  const toneClass: Record<string, string> = {
    primary: "bg-primary/10 text-primary",
    warning: "bg-destructive/10 text-destructive",
    accent: "bg-accent/20 text-accent-foreground",
  };
  return (
    <div className="flex items-center justify-between py-3">
      <div className="flex items-center gap-3">
        <div className={`h-9 w-9 rounded-lg flex items-center justify-center ${toneClass[tone]}`}>
          <Icon className="h-4 w-4" />
        </div>
        <div>
          <div className="font-medium text-sm">{title}</div>
          <div className="text-xs text-muted-foreground">
            {count === 0 ? "Nothing waiting" : `${count} pending`}
          </div>
        </div>
      </div>
      {to ? (
        <Button size="sm" variant="outline" asChild>
          <Link to={to}>{cta}</Link>
        </Button>
      ) : (
        <Button size="sm" variant="outline" disabled={count === 0}>
          {cta}
        </Button>
      )}
    </div>
  );
}

function HealthRow({
  label,
  value,
  tone,
}: {
  label: string;
  value: string;
  tone: "success" | "warning";
}) {
  const dot = tone === "success" ? "bg-success" : "bg-destructive";
  return (
    <div className="flex items-center justify-between">
      <span className="text-muted-foreground">{label}</span>
      <span className="inline-flex items-center gap-2 font-semibold">
        <span className={`h-2 w-2 rounded-full ${dot}`} />
        {value}
      </span>
    </div>
  );
}
