import { ShieldCheck, Users } from 'lucide-react';

import { Suspense, lazy } from 'react';

import { Head, Link } from '@inertiajs/react';

import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import { ChartErrorBoundary } from '@/Components/admin/ChartErrorBoundary';
import PageHeader from '@/Components/layout/PageHeader';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { Skeleton } from '@/Components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import AdminLayout from '@/Layouts/AdminLayout';
import { formatRelativeTime } from '@/lib/format';
import type { AdminTwoFactorDashboardProps } from '@/types/admin';

// Chart loading fallback
const ChartLoader = () => (
  <div className="h-[250px] rounded-lg border bg-card p-4 space-y-3">
    <Skeleton className="h-5 w-40" />
    <Skeleton className="h-[200px] w-full" />
  </div>
);

// Lazy load adoption bar chart
const LazyAdoptionChart = lazy(async () => {
  const { BarChart, Bar, CartesianGrid, Cell, ChartContainer, ChartTooltip, XAxis, YAxis } =
    await import('@/Components/ui/chart');
  return {
    default: ({ data }: { data: { label: string; count: number }[] }) => (
      <ChartContainer height={250}>
        <BarChart data={data}>
          <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
          <XAxis dataKey="label" className="text-xs" />
          <YAxis allowDecimals={false} className="text-xs" />
          <ChartTooltip />
          <Bar dataKey="count" name="Users" radius={[4, 4, 0, 0]}>
            {data.map((entry, index) => (
              <Cell
                key={`cell-${index}`}
                fill={
                  entry.label === 'Enabled' ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))'
                }
              />
            ))}
          </Bar>
        </BarChart>
      </ChartContainer>
    ),
  };
});

export default function TwoFactorDashboard({ stats, users_with_2fa }: AdminTwoFactorDashboardProps) {
  const chartData = [
    { label: 'Enabled', count: stats.two_factor_enabled },
    { label: 'Disabled', count: stats.without_two_factor },
  ];

  return (
    <AdminLayout>
      <Head title="Admin - Two-Factor" />
      <PageHeader title="Two-Factor Authentication" description="2FA adoption metrics" />

      <div className="container py-6 space-y-6">
        {/* Stats */}
        <AdminStatsGrid
          columns="grid-cols-1 md:grid-cols-3"
          stats={
            [
              {
                title: '2FA Enabled',
                value: stats.two_factor_enabled,
                icon: ShieldCheck,
                description: `of ${stats.total_users} total users`,
              },
              {
                title: 'Adoption Rate',
                value: stats.adoption_rate,
                icon: Users,
                format: (n) => `${n}%`,
                description: 'Users with 2FA enabled',
              },
              {
                title: 'Without 2FA',
                value: stats.without_two_factor,
                valueClassName: 'text-muted-foreground',
                description: 'Users without protection',
              },
            ] satisfies StatCard[]
          }
        />

        {/* Adoption Chart */}
        <Card>
          <CardHeader>
            <CardTitle>2FA Adoption</CardTitle>
            <CardDescription>Users with vs without two-factor authentication</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartErrorBoundary>
              <Suspense fallback={<ChartLoader />}>
                <LazyAdoptionChart data={chartData} />
              </Suspense>
            </ChartErrorBoundary>
          </CardContent>
        </Card>

        {/* Users with 2FA */}
        <Card>
          <CardHeader>
            <CardTitle>Recently Enabled</CardTitle>
            <CardDescription>Users who most recently enabled two-factor authentication</CardDescription>
          </CardHeader>
          <CardContent className="p-0">
            {users_with_2fa.length === 0 ? (
              <EmptyState
                icon={ShieldCheck}
                title="No 2FA users yet"
                description="Users who enable 2FA will appear here."
                size="sm"
                animated={false}
              />
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>User</TableHead>
                      <TableHead>Enabled</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {users_with_2fa.map((u) => (
                      <TableRow key={u.user_id}>
                        <TableCell>
                          <Link href={`/admin/users/${u.user_id}`} className="font-medium hover:underline">
                            {u.user_name}
                          </Link>
                          <div className="text-xs text-muted-foreground">{u.user_email}</div>
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {formatRelativeTime(u.enabled_at)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </AdminLayout>
  );
}
