import { ReactNode } from 'react';
import { Head, router } from '@inertiajs/react';
import { useQuery } from '@tanstack/react-query';
import AdminLayout from '@/layouts/AdminLayout';
import { useAuth } from '@/hooks/useAuth';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Shield, Users, Award, AlertTriangle, Clock, ArrowRight, BookOpen } from 'lucide-react';
import { differenceInDays, format } from 'date-fns';

const ComplianceHubPage = () => {
  const { roles, companyId } = useAuth();

  const isSysRole = roles?.some((r: string) => ['sys_admin', 'sys_manager', 'admin', 'manager'].includes(r));

  // Get all companies for sys admins, or just the one for company managers
  const { data: companies } = useQuery({
    queryKey: ['compliance-hub-companies', companyId, isSysRole],
    queryFn: async () => {
      if (isSysRole) {
        const res = await fetch('/api/admin/training-companies?status=approved');
        if (!res.ok) return [];
        return res.json();
      }
      if (companyId) {
        const res = await fetch(`/api/admin/training-companies/${companyId}`);
        if (!res.ok) return [];
        const data = await res.json();
        return data ? [data] : [];
      }
      return [];
    },
  });

  const selectedCompanyId = (companies as any[] | undefined)?.[0]?.id;

  const { data: delegates } = useQuery({
    queryKey: ['compliance-hub-delegates', selectedCompanyId],
    queryFn: async () => {
      if (!selectedCompanyId) return [];
      const res = await fetch(`/api/admin/delegates?company_id=${encodeURIComponent(selectedCompanyId)}&status=active`);
      if (!res.ok) return [];
      return res.json();
    },
    enabled: !!selectedCompanyId,
  });

  const { data: certificates } = useQuery({
    queryKey: ['compliance-hub-certs', selectedCompanyId],
    queryFn: async () => {
      if (!selectedCompanyId) return [];
      const res = await fetch(`/api/admin/certificates?company_id=${encodeURIComponent(selectedCompanyId)}`);
      if (!res.ok) return [];
      return res.json();
    },
    enabled: !!selectedCompanyId,
  });

  // Calculate stats
  const totalDelegates = (delegates as any[] | undefined)?.length || 0;
  const totalCerts = (certificates as any[] | undefined)?.length || 0;

  const now = new Date();
  const expiredCerts = (certificates as any[] | undefined)?.filter((c) => c.expires_at && differenceInDays(new Date(c.expires_at), now) < 0) || [];
  const expiringSoon = (certificates as any[] | undefined)?.filter((c) => {
    if (!c.expires_at) return false;
    const days = differenceInDays(new Date(c.expires_at), now);
    return days >= 0 && days <= 90;
  }) || [];
  const activeCerts = (certificates as any[] | undefined)?.filter((c) => {
    if (!c.expires_at) return c.status === 'active';
    return differenceInDays(new Date(c.expires_at), now) > 90 && c.status === 'active';
  }) || [];

  const externalCerts = (certificates as any[] | undefined)?.filter((c: any) => c.is_external) || [];
  const platformCerts = (certificates as any[] | undefined)?.filter((c: any) => !c.is_external) || [];

  const complianceScore = totalCerts > 0 ? Math.round((activeCerts.length / totalCerts) * 100) : 0;

  // Build action items: expired/expiring certs that have a matching course for rebooking
  const actionItems = [...expiredCerts, ...expiringSoon]
    .map((cert) => {
      const course = (cert as any).course;
      const daysLeft = cert.expires_at ? differenceInDays(new Date(cert.expires_at), now) : null;
      return { ...cert, courseName: course?.title, courseSlug: course?.slug, daysLeft };
    })
    .sort((a, b) => (a.daysLeft ?? 999) - (b.daysLeft ?? 999));

  return (
    <>
      <Head title="Compliance Hub" />
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Shield className="h-6 w-6 text-primary" />
            <div>
              <h1 className="text-2xl font-bold text-foreground">Compliance Hub</h1>
              <p className="text-sm text-muted-foreground">
                {(companies as any[] | undefined)?.[0]?.name || 'Team'} — Training, certification & compliance overview
              </p>
            </div>
          </div>
        </div>

        {/* KPI Cards */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <Users className="h-8 w-8 text-primary" />
                <div>
                  <p className="text-2xl font-bold text-foreground">{totalDelegates}</p>
                  <p className="text-xs text-muted-foreground">Team Members</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <Award className="h-8 w-8 text-primary" />
                <div>
                  <p className="text-2xl font-bold text-foreground">{totalCerts}</p>
                  <p className="text-xs text-muted-foreground">
                    Certifications
                    {externalCerts.length > 0 && (
                      <span className="text-muted-foreground"> ({platformCerts.length} verified, {externalCerts.length} self-reported)</span>
                    )}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <AlertTriangle className="h-8 w-8 text-destructive" />
                <div>
                  <p className="text-2xl font-bold text-foreground">{expiredCerts.length + expiringSoon.length}</p>
                  <p className="text-xs text-muted-foreground">
                    {expiredCerts.length} expired · {expiringSoon.length} expiring
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <p className="text-xs text-muted-foreground">Compliance Score</p>
                  <p className="text-lg font-bold text-foreground">{complianceScore}%</p>
                </div>
                <Progress value={complianceScore} className="h-2" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Action Required */}
        {actionItems.length > 0 && (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base">
                <Clock className="h-5 w-5 text-amber-500" />
                Action Required — Expiring & Expired Certifications
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Delegate</TableHead>
                    <TableHead>Qualification</TableHead>
                    <TableHead>Source</TableHead>
                    <TableHead>Expiry</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="w-[140px]">Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {actionItems.slice(0, 10).map((item: any) => (
                    <TableRow key={item.id}>
                      <TableCell className="text-sm font-medium">{item.delegate_email}</TableCell>
                      <TableCell className="text-sm">
                        {item.courseName || (item as any).qualification_name || '—'}
                      </TableCell>
                      <TableCell>
                        {(item as any).is_external ? (
                          <Badge variant="outline" className="text-xs">Self-reported</Badge>
                        ) : (
                          <Badge variant="default" className="text-xs">Platform</Badge>
                        )}
                      </TableCell>
                      <TableCell className="text-sm">
                        {item.expires_at ? format(new Date(item.expires_at), 'dd MMM yyyy') : '—'}
                      </TableCell>
                      <TableCell>
                        {item.daysLeft !== null && item.daysLeft < 0 ? (
                          <Badge variant="destructive">Expired</Badge>
                        ) : (
                          <Badge className="bg-amber-500 text-white">{item.daysLeft}d left</Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        {item.courseSlug ? (
                          <Button
                            size="sm"
                            variant="hero"
                            className="text-xs"
                            onClick={() => router.visit(`/course/${item.courseSlug}`)}
                          >
                            <BookOpen className="h-3 w-3 mr-1" /> Rebook
                          </Button>
                        ) : (
                          <span className="text-xs text-muted-foreground">No course linked</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              {actionItems.length > 10 && (
                <p className="text-xs text-muted-foreground text-center mt-2">
                  + {actionItems.length - 10} more items
                </p>
              )}
            </CardContent>
          </Card>
        )}

        {/* Quick Links */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {selectedCompanyId && (
            <Card className="cursor-pointer hover:border-primary/50 transition-colors" onClick={() => router.visit(`/admin/companies/${selectedCompanyId}`)}>
              <CardContent className="pt-6 flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Users className="h-5 w-5 text-primary" />
                  <div>
                    <p className="font-medium text-foreground">Manage Team</p>
                    <p className="text-xs text-muted-foreground">Add members, CSV import, assign roles</p>
                  </div>
                </div>
                <ArrowRight className="h-4 w-4 text-muted-foreground" />
              </CardContent>
            </Card>
          )}
          <Card className="cursor-pointer hover:border-primary/50 transition-colors" onClick={() => router.visit('/admin/skills-gap')}>
            <CardContent className="pt-6 flex items-center justify-between">
              <div className="flex items-center gap-3">
                <AlertTriangle className="h-5 w-5 text-amber-500" />
                <div>
                  <p className="font-medium text-foreground">Skills Gap Analysis</p>
                  <p className="text-xs text-muted-foreground">RAG matrix of training requirements</p>
                </div>
              </div>
              <ArrowRight className="h-4 w-4 text-muted-foreground" />
            </CardContent>
          </Card>
          <Card className="cursor-pointer hover:border-primary/50 transition-colors" onClick={() => router.visit('/admin/certificates')}>
            <CardContent className="pt-6 flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Award className="h-5 w-5 text-primary" />
                <div>
                  <p className="font-medium text-foreground">All Certificates</p>
                  <p className="text-xs text-muted-foreground">View, upload, and export certifications</p>
                </div>
              </div>
              <ArrowRight className="h-4 w-4 text-muted-foreground" />
            </CardContent>
          </Card>
        </div>
      </div>
    </>
  );
};

ComplianceHubPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default ComplianceHubPage;
