import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { RefreshCw, CheckCircle2, AlertTriangle, XCircle, Shield } from "lucide-react";
import { differenceInDays } from "date-fns";
import { router } from "@inertiajs/react";

type RAGStatus = "green" | "amber" | "red" | "none";

const ragConfig: Record<RAGStatus, { label: string; bg: string; color: string; icon: typeof CheckCircle2 }> = {
  green: { label: "Valid", bg: "bg-green-100 dark:bg-green-900/30", color: "text-green-700 dark:text-green-400", icon: CheckCircle2 },
  amber: { label: "Expiring", bg: "bg-amber-100 dark:bg-amber-900/30", color: "text-amber-700 dark:text-amber-400", icon: AlertTriangle },
  red: { label: "Expired", bg: "bg-red-100 dark:bg-red-900/30", color: "text-red-700 dark:text-red-400", icon: XCircle },
  none: { label: "Missing", bg: "bg-muted", color: "text-muted-foreground", icon: XCircle },
};

const ComplianceMatrix = () => {
  const { companyId } = useAuth();

  const { data: delegates } = useQuery({
    queryKey: ["compliance-delegates", companyId],
    queryFn: async () => {
      const res = await fetch(`/api/delegates?company_id=${encodeURIComponent(companyId!)}&status=active&order=first_name`);
      if (!res.ok) throw new Error("Failed to load delegates");
      const data = await res.json();
      return (data?.data ?? data) as any[];
    },
    enabled: !!companyId,
  });

  const { data: certCourses } = useQuery({
    queryKey: ["compliance-courses"],
    queryFn: async () => {
      const res = await fetch(`/api/courses?has_certificate=1&is_active=1&order=title`);
      if (!res.ok) throw new Error("Failed to load courses");
      const data = await res.json();
      return (data?.data ?? data) as any[];
    },
  });

  const { data: certificates } = useQuery({
    queryKey: ["compliance-certs", companyId],
    queryFn: async () => {
      const res = await fetch(`/api/certificates?company_id=${encodeURIComponent(companyId!)}`);
      if (!res.ok) throw new Error("Failed to load certificates");
      const data = await res.json();
      return (data?.data ?? data) as any[];
    },
    enabled: !!companyId,
  });

  const getCertStatus = (delegateEmail: string | null, courseId: string): RAGStatus => {
    if (!delegateEmail || !certificates) return "none";
    const cert = certificates.find((c: any) => c.delegate_email.toLowerCase() === delegateEmail.toLowerCase() && c.course_id === courseId);
    if (!cert) return "none";
    if (!cert.expires_at) return "green";
    const days = differenceInDays(new Date(cert.expires_at), new Date());
    if (days < 0) return "red";
    if (days <= 30) return "amber";
    return "green";
  };

  if (!delegates?.length || !certCourses?.length) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><Shield className="h-5 w-5" /> Compliance Matrix</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground text-center py-6">
            {!delegates?.length ? "No active delegates found." : "No certification courses available."}
          </p>
        </CardContent>
      </Card>
    );
  }

  // Summary counts
  let totalRed = 0, totalAmber = 0;
  delegates.forEach((d: any) => {
    certCourses.forEach((c: any) => {
      const s = getCertStatus(d.email, c.id);
      if (s === "red") totalRed++;
      if (s === "amber") totalAmber++;
    });
  });

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <div>
          <CardTitle className="flex items-center gap-2"><Shield className="h-5 w-5" /> Compliance Matrix</CardTitle>
          <p className="text-sm text-muted-foreground mt-1">
            {delegates.length} delegates × {certCourses.length} certifications
            {totalRed > 0 && <span className="text-red-600 font-medium ml-2">· {totalRed} expired</span>}
            {totalAmber > 0 && <span className="text-amber-600 font-medium ml-2">· {totalAmber} expiring</span>}
          </p>
        </div>
      </CardHeader>
      <CardContent className="p-0 overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="sticky left-0 bg-background z-10 min-w-[160px]">Delegate</TableHead>
              {certCourses.map((c: any) => (
                <TableHead key={c.id} className="text-center min-w-[120px] text-xs">{c.title}</TableHead>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {delegates.map((d: any) => (
              <TableRow key={d.id}>
                <TableCell className="sticky left-0 bg-background z-10 font-medium text-sm">
                  {d.first_name} {d.last_name}
                </TableCell>
                {certCourses.map((c: any) => {
                  const status = getCertStatus(d.email, c.id);
                  const cfg = ragConfig[status];
                  const Icon = cfg.icon;
                  return (
                    <TableCell key={c.id} className="text-center">
                      <div className="flex flex-col items-center gap-1">
                        <span className={`inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full font-medium ${cfg.bg} ${cfg.color}`}>
                          <Icon className="w-3 h-3" /> {cfg.label}
                        </span>
                        {(status === "red" || status === "amber" || status === "none") && c.slug && (
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 text-[10px] px-2"
                            onClick={() => router.visit(`/course/${c.slug}`)}
                          >
                            <RefreshCw className="w-3 h-3 mr-0.5" /> Book
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  );
                })}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
};

export default ComplianceMatrix;
