import { router } from '@inertiajs/react';
import { useQuery } from '@tanstack/react-query';
import { useAuth } from '@/hooks/useAuth';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Users, Award, AlertTriangle, ShoppingCart, CheckCircle2, CreditCard } from 'lucide-react';
import { differenceInDays, format } from 'date-fns';

type Company = { id: string; name: string; credit_available_cents?: number; credit_limit_cents?: number };

const fmtGBP = (cents?: number) => `£${((cents ?? 0) / 100).toLocaleString('en-GB', { minimumFractionDigits: 2 })}`;
type Delegate = { id: string; first_name: string; last_name: string; email: string | null; status: string };
type Certificate = { id: string; course_id: string; delegate_email: string; expires_at: string | null; status: string; course?: { title: string } | null };
type Order = { id: string; start_date: string; num_delegates: number; status: string; course?: { title: string } | null };
type JobRole = { id: string };
type JobRoleRequirement = { id: string; job_role_id: string; course_id: string; is_mandatory: boolean };
type DelegateJobRole = { delegate_id: string; job_role_id: string };

const apiGet = async <T,>(path: string, fallback: T): Promise<T> => {
  try {
    const res = await fetch(path);
    if (!res.ok) return fallback;
    return res.json();
  } catch {
    return fallback;
  }
};

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

  const { data: company } = useQuery({
    queryKey: ['cm-dash-company', companyId],
    enabled: !!companyId,
    queryFn: () => apiGet<Company | null>(`/api/admin/companies/${companyId}`, null),
  });

  const { data: delegates } = useQuery({
    queryKey: ['cm-dash-delegates', companyId],
    enabled: !!companyId,
    queryFn: () => apiGet<Delegate[]>(`/api/admin/companies/${companyId}/delegates`, []),
  });

  const { data: certificates } = useQuery({
    queryKey: ['cm-dash-certs', companyId],
    enabled: !!companyId,
    queryFn: () => apiGet<Certificate[]>(`/api/admin/companies/${companyId}/certificates`, []),
  });

  const { data: recentOrders } = useQuery({
    queryKey: ['cm-dash-orders', companyId],
    enabled: !!companyId,
    queryFn: () => apiGet<Order[]>(`/api/admin/companies/${companyId}/recent-orders`, []),
  });

  const { data: jobRoles } = useQuery({
    queryKey: ['cm-dash-jobroles', companyId],
    enabled: !!companyId,
    queryFn: () => apiGet<JobRole[]>(`/api/admin/companies/${companyId}/job-roles`, []),
  });

  const { data: jobRoleRequirements } = useQuery({
    queryKey: ['cm-dash-jobrole-reqs', companyId],
    enabled: !!jobRoles && jobRoles.length > 0,
    queryFn: () => apiGet<JobRoleRequirement[]>(`/api/admin/companies/${companyId}/job-role-requirements`, []),
  });

  const { data: delegateJobRoles } = useQuery({
    queryKey: ['cm-dash-delegate-jobroles', companyId],
    enabled: !!delegates && delegates.length > 0,
    queryFn: () => apiGet<DelegateJobRole[]>(`/api/admin/companies/${companyId}/delegate-job-roles`, []),
  });

  const activeDelegates = delegates?.filter((d) => d.status === 'active').length || 0;
  const totalDelegates = delegates?.length || 0;

  const now = new Date();
  const expiring30 = certificates?.filter((c) => {
    if (!c.expires_at) return false;
    const days = differenceInDays(new Date(c.expires_at), now);
    return days >= 0 && days <= 30;
  }).length || 0;

  const expiring60 = certificates?.filter((c) => {
    if (!c.expires_at) return false;
    const days = differenceInDays(new Date(c.expires_at), now);
    return days > 30 && days <= 60;
  }).length || 0;

  const expired = certificates?.filter((c) => {
    if (!c.expires_at) return false;
    return differenceInDays(new Date(c.expires_at), now) < 0;
  }).length || 0;

  const complianceScore = (() => {
    if (!delegates?.length || !delegateJobRoles?.length || !jobRoleRequirements?.length) return null;

    let totalRequired = 0;
    let totalMet = 0;

    for (const djr of delegateJobRoles || []) {
      const delegate = delegates?.find((d) => d.id === djr.delegate_id);
      if (!delegate?.email) continue;

      const reqs =
        jobRoleRequirements?.filter((r) => r.job_role_id === djr.job_role_id && r.is_mandatory) ||
        [];

      for (const req of reqs) {
        totalRequired++;
        const hasCert = certificates?.some(
          (c) =>
            c.delegate_email === delegate.email &&
            c.course_id === req.course_id &&
            c.status === 'active' &&
            (!c.expires_at || differenceInDays(new Date(c.expires_at), now) >= 0),
        );
        if (hasCert) totalMet++;
      }
    }

    return totalRequired > 0 ? Math.round((totalMet / totalRequired) * 100) : null;
  })();

  const trainingGaps = (() => {
    if (!delegates?.length || !delegateJobRoles?.length || !jobRoleRequirements?.length) return 0;

    let gaps = 0;
    for (const djr of delegateJobRoles || []) {
      const delegate = delegates?.find((d) => d.id === djr.delegate_id);
      if (!delegate?.email) continue;

      const reqs =
        jobRoleRequirements?.filter((r) => r.job_role_id === djr.job_role_id && r.is_mandatory) ||
        [];

      for (const req of reqs) {
        const hasCert = certificates?.some(
          (c) =>
            c.delegate_email === delegate.email &&
            c.course_id === req.course_id &&
            c.status === 'active' &&
            (!c.expires_at || differenceInDays(new Date(c.expires_at), now) >= 0),
        );
        if (!hasCert) gaps++;
      }
    }
    return gaps;
  })();

  if (!companyId) {
    return (
      <div className="text-center py-12 text-muted-foreground">
        No company associated with your account.
      </div>
    );
  }

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-foreground">{company?.name || 'Company'} Dashboard</h1>
        <p className="text-sm text-muted-foreground mt-1">
          Overview of your delegates, training, and compliance
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
        <Card
          className="cursor-pointer hover:border-primary/50 transition-colors"
          onClick={() => router.visit(`/admin/companies/${companyId}`)}
        >
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Delegates</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activeDelegates}</div>
            <p className="text-xs text-muted-foreground">{totalDelegates} total</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Credit Available</CardTitle>
            <CreditCard className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{fmtGBP(company?.credit_available_cents)}</div>
            <p className="text-xs text-muted-foreground">of {fmtGBP(company?.credit_limit_cents)} limit</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Certificates</CardTitle>
            <Award className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{certificates?.length || 0}</div>
            <div className="flex gap-2 mt-1">
              {expired > 0 && <Badge variant="destructive" className="text-[10px]">{expired} expired</Badge>}
              {expiring30 > 0 && <Badge className="bg-amber-500 text-white text-[10px]">{expiring30} ≤30d</Badge>}
              {expiring60 > 0 && <Badge variant="outline" className="text-[10px]">{expiring60} ≤60d</Badge>}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Training Gaps</CardTitle>
            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{trainingGaps}</div>
            <p className="text-xs text-muted-foreground">missing mandatory certs</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Compliance</CardTitle>
            <CheckCircle2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {complianceScore !== null ? `${complianceScore}%` : '—'}
            </div>
            <p className="text-xs text-muted-foreground">
              {complianceScore !== null ? 'of mandatory certs held' : 'Set up job roles to track'}
            </p>
          </CardContent>
        </Card>
      </div>

      {(expired > 0 || expiring30 > 0) && (
        <Card className="mb-6 border-amber-500/50 bg-amber-50 dark:bg-amber-950/20">
          <CardContent className="py-4 flex items-center gap-3">
            <AlertTriangle className="h-5 w-5 text-amber-600 dark:text-amber-400 shrink-0" />
            <div className="flex-1">
              <p className="font-medium text-foreground">
                {expired + expiring30} certificate{expired + expiring30 !== 1 ? 's' : ''} need attention
              </p>
              <p className="text-sm text-muted-foreground">
                {expired > 0 && `${expired} expired`}
                {expired > 0 && expiring30 > 0 && ', '}
                {expiring30 > 0 && `${expiring30} expiring within 30 days`}
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-base">Recent Bookings</CardTitle>
          <ShoppingCart className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          {recentOrders?.length === 0 ? (
            <p className="text-sm text-muted-foreground py-4 text-center">No bookings yet.</p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Course</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead>Delegates</TableHead>
                  <TableHead>Status</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {recentOrders?.map((o) => (
                  <TableRow key={o.id}>
                    <TableCell className="font-medium">{o.course?.title || '—'}</TableCell>
                    <TableCell>{o.start_date ? format(new Date(o.start_date), 'dd MMM yyyy') : 'Online'}</TableCell>
                    <TableCell>{o.num_delegates}</TableCell>
                    <TableCell>
                      <Badge variant={o.status === 'paid' || o.status === 'confirmed' ? 'default' : 'secondary'}>
                        {o.status}
                      </Badge>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export default CompanyManagerDashboard;
