import { Head } from '@inertiajs/react';
import {
    Activity,
    Building2,
    FileText,
    Key,
    Shield,
    TrendingUp,
    Users,
} from 'lucide-react';

import { type BreadcrumbItem } from '@/types';
import AppLayout from '@/layouts/app-layout';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { SharedData } from '@/types';
import { usePage } from '@inertiajs/react';
import { Link } from '@inertiajs/react';

interface DashboardProps {
    stats: {
        users: number;
        active_users: number;
        clients: number;
        active_clients: number;
        documents: number;
        roles: number;
        api_tokens: number;
    };
    recentUsers: Array<{
        id: number;
        name: string;
        email: string;
        is_active: boolean;
        created_at: string;
        roles?: Array<{ name: string }>;
    }>;
    recentClients: Array<{
        id: number;
        name: string;
        code: string;
        is_active: boolean;
        created_at: string;
    }>;
    recentDocuments: Array<{
        id: number;
        name: string;
        type: string;
        size: number;
        created_at: string;
        uploader?: { name: string } | null;
    }>;
    rolesDistribution: Array<{
        name: string;
        users_count: number;
    }>;
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Dashboard',
        href: '/',
    },
];

function formatBytes(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}

function formatDate(date: string): string {
    return new Date(date).toLocaleDateString('fr-FR', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
    });
}

export default function Dashboard({ stats, recentUsers, recentClients, recentDocuments, rolesDistribution }: DashboardProps) {
    const { auth } = usePage<SharedData>().props;
    const isAdmin = auth.user?.roles?.some((r: { name: string }) => ['Super Admin', 'Admin'].includes(r.name));

    const statCards = [
        { label: 'Utilisateurs', value: stats.users, sub: `${stats.active_users} actifs`, icon: Users, color: 'text-blue-600', bg: 'bg-blue-50 dark:bg-blue-950' },
        { label: 'Clients', value: stats.clients, sub: `${stats.active_clients} actifs`, icon: Building2, color: 'text-green-600', bg: 'bg-green-50 dark:bg-green-950' },
        { label: 'Documents', value: stats.documents, sub: 'tous types', icon: FileText, color: 'text-orange-600', bg: 'bg-orange-50 dark:bg-orange-950' },
        { label: 'Rôles', value: stats.roles, sub: 'configurés', icon: Shield, color: 'text-purple-600', bg: 'bg-purple-50 dark:bg-purple-950' },
        { label: 'Tokens API', value: stats.api_tokens, sub: 'Sanctum', icon: Key, color: 'text-cyan-600', bg: 'bg-cyan-50 dark:bg-cyan-950' },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Dashboard" />

            <div className="flex h-full flex-1 flex-col gap-6 p-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight">
                            Bonjour, {auth.user?.name} 👋
                        </h1>
                        <p className="text-muted-foreground text-sm mt-1">
                            Vue d'ensemble de la plateforme SOO API
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <Badge variant="outline" className="gap-1">
                            <Activity className="size-3" />
                            API v1
                        </Badge>
                        {isAdmin && (
                            <Badge variant="default" className="gap-1">
                                <Shield className="size-3" />
                                {auth.user?.roles?.[0]?.name}
                            </Badge>
                        )}
                    </div>
                </div>

                {/* Stats cards */}
                <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-5">
                    {statCards.map((card) => (
                        <Card key={card.label}>
                            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                <CardTitle className="text-sm font-medium text-muted-foreground">
                                    {card.label}
                                </CardTitle>
                                <div className={`rounded-md p-2 ${card.bg}`}>
                                    <card.icon className={`size-4 ${card.color}`} />
                                </div>
                            </CardHeader>
                            <CardContent>
                                <div className="text-2xl font-bold">{card.value}</div>
                                <p className="text-xs text-muted-foreground mt-1">{card.sub}</p>
                            </CardContent>
                        </Card>
                    ))}
                </div>

                {/* Main grid */}
                <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
                    {/* Recent users */}
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between">
                            <div>
                                <CardTitle className="text-lg">Utilisateurs récents</CardTitle>
                                <CardDescription>Derniers comptes créés</CardDescription>
                            </div>
                            <Button variant="ghost" size="sm" asChild>
                                <Link href="/user-management/users">Voir tout</Link>
                            </Button>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Nom</TableHead>
                                        <TableHead>Rôle</TableHead>
                                        <TableHead>Statut</TableHead>
                                        <TableHead>Créé</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {recentUsers.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={4} className="text-center text-muted-foreground py-6">
                                                Aucun utilisateur
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        recentUsers.map((user) => (
                                            <TableRow key={user.id}>
                                                <TableCell className="font-medium">
                                                    {user.name}
                                                    <div className="text-xs text-muted-foreground">{user.email}</div>
                                                </TableCell>
                                                <TableCell>
                                                    {user.roles?.map((r) => (
                                                        <Badge key={r.name} variant="secondary" className="text-xs">
                                                            {r.name}
                                                        </Badge>
                                                    ))}
                                                </TableCell>
                                                <TableCell>
                                                    <Badge variant={user.is_active ? 'default' : 'destructive'} className="text-xs">
                                                        {user.is_active ? 'Actif' : 'Inactif'}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="text-sm text-muted-foreground">
                                                    {formatDate(user.created_at)}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>

                    {/* Recent clients */}
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between">
                            <div>
                                <CardTitle className="text-lg">Clients récents</CardTitle>
                                <CardDescription>Derniers comptes clients</CardDescription>
                            </div>
                            <Button variant="ghost" size="sm" asChild>
                                <Link href="/user-management/clients">Voir tout</Link>
                            </Button>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Nom</TableHead>
                                        <TableHead>Code</TableHead>
                                        <TableHead>Statut</TableHead>
                                        <TableHead>Créé</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {recentClients.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={4} className="text-center text-muted-foreground py-6">
                                                Aucun client
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        recentClients.map((client) => (
                                            <TableRow key={client.id}>
                                                <TableCell className="font-medium">{client.name}</TableCell>
                                                <TableCell>
                                                    <code className="text-xs bg-muted px-1.5 py-0.5 rounded">
                                                        {client.code}
                                                    </code>
                                                </TableCell>
                                                <TableCell>
                                                    <Badge variant={client.is_active ? 'default' : 'destructive'} className="text-xs">
                                                        {client.is_active ? 'Actif' : 'Inactif'}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="text-sm text-muted-foreground">
                                                    {formatDate(client.created_at)}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>

                    {/* Roles distribution */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="text-lg">Répartition des rôles</CardTitle>
                            <CardDescription>Utilisateurs par rôle</CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {rolesDistribution.length === 0 ? (
                                <p className="text-center text-muted-foreground py-6">Aucun rôle configuré</p>
                            ) : (
                                rolesDistribution.map((role) => {
                                    const maxCount = Math.max(...rolesDistribution.map((r) => r.users_count), 1);
                                    const percentage = (role.users_count / maxCount) * 100;
                                    return (
                                        <div key={role.name} className="space-y-1">
                                            <div className="flex items-center justify-between text-sm">
                                                <span className="font-medium">{role.name}</span>
                                                <span className="text-muted-foreground">{role.users_count} utilisateur(s)</span>
                                            </div>
                                            <div className="h-2 rounded-full bg-muted overflow-hidden">
                                                <div
                                                    className="h-full rounded-full bg-primary transition-all"
                                                    style={{ width: `${percentage}%` }}
                                                />
                                            </div>
                                        </div>
                                    );
                                })
                            )}
                        </CardContent>
                    </Card>

                    {/* Recent documents */}
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between">
                            <div>
                                <CardTitle className="text-lg">Documents récents</CardTitle>
                                <CardDescription>Derniers fichiers uploadés</CardDescription>
                            </div>
                            <Button variant="ghost" size="sm" asChild>
                                <Link href="/documents">Voir tout</Link>
                            </Button>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Nom</TableHead>
                                        <TableHead>Type</TableHead>
                                        <TableHead>Taille</TableHead>
                                        <TableHead>Date</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {recentDocuments.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={4} className="text-center text-muted-foreground py-6">
                                                Aucun document
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        recentDocuments.map((doc) => (
                                            <TableRow key={doc.id}>
                                                <TableCell className="font-medium">
                                                    {doc.name}
                                                    {doc.uploader && (
                                                        <div className="text-xs text-muted-foreground">
                                                            par {doc.uploader.name}
                                                        </div>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    <Badge variant="outline" className="text-xs capitalize">
                                                        {doc.type}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="text-sm text-muted-foreground">
                                                    {formatBytes(doc.size)}
                                                </TableCell>
                                                <TableCell className="text-sm text-muted-foreground">
                                                    {formatDate(doc.created_at)}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>
                </div>

                {/* API quick access */}
                <Card>
                    <CardHeader>
                        <CardTitle className="text-lg flex items-center gap-2">
                            <TrendingUp className="size-5" />
                            Accès rapide API
                        </CardTitle>
                        <CardDescription>Endpoints principaux de SOO API v1</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">
                            {[
                                { method: 'POST', path: '/api/v1/auth/login', desc: 'Connexion JWT' },
                                { method: 'GET', path: '/api/v1/auth/me', desc: 'Profil courant' },
                                { method: 'GET', path: '/api/v1/users', desc: 'Liste utilisateurs' },
                                { method: 'GET', path: '/api/v1/clients', desc: 'Liste clients' },
                                { method: 'GET', path: '/api/v1/documents', desc: 'Liste documents' },
                                { method: 'POST', path: '/api/v1/auth/tokens', desc: 'Créer token API' },
                            ].map((endpoint) => (
                                <div
                                    key={endpoint.path}
                                    className="flex items-center gap-3 rounded-lg border p-3 hover:bg-muted/50 transition-colors"
                                >
                                    <Badge
                                        variant={endpoint.method === 'GET' ? 'secondary' : 'default'}
                                        className="font-mono text-xs"
                                    >
                                        {endpoint.method}
                                    </Badge>
                                    <div className="flex-1 min-w-0">
                                        <code className="text-xs block truncate">{endpoint.path}</code>
                                        <p className="text-xs text-muted-foreground">{endpoint.desc}</p>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
