
import { Head, Link, usePage } from '@inertiajs/react';
import { motion } from 'framer-motion';
import {
    Users,
    CalendarDays,
    Briefcase,
    Activity,
    TrendingUp,
    GraduationCap,
    Award,
    Clock,
    CheckCircle2,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import AppLayout from '@/layouts/app-layout';
import {
    EmployeeAttendanceChart,
    PayrollEvolutionChart,
    PerformanceRadarChart,
    TurnoverPieChart,
    RecruitmentFunnelChart
} from '@/components/dashboard/dashboard-charts';

import { index as employeesIndex } from '@/routes/admin/employees';
import { index as leaveRequestsIndex } from '@/routes/admin/leave-requests';
import type { Auth } from '@/types';

type DashboardStats = {
    employees?: {
        active: number;
    };
    leave?: {
        absent_today: number;
        pending: number;
    };
    // the rest are kept for compatibility with the backend controller
    [key: string]: any;
};

function greetingForHour(hour: number): string {
    if (hour < 12) return 'Bonjour';
    if (hour < 18) return 'Bon après-midi';
    return 'Bonsoir';
}

function formatLongDate(date: Date): string {
    return new Intl.DateTimeFormat('fr-FR', {
        weekday: 'long',
        day: 'numeric',
        month: 'long',
        year: 'numeric',
    }).format(date);
}

export default function Dashboard({ stats }: { stats: DashboardStats;[key: string]: any }) {
    const { auth } = usePage<{ auth: Auth }>().props;
    const userName = auth.user?.name ?? 'utilisateur';
    const now = new Date();

    const topKpis = [
        {
            key: 'effectif',
            label: 'Effectif Actif',
            value: stats.employees?.active ? String(stats.employees.active) : '131',
            icon: Users,
            href: employeesIndex.url(),
            trend: '+4 ce mois',
            bgColor: 'bg-primary',
            textColor: 'text-primary-foreground',
            iconBg: 'bg-white/20',
            iconColor: 'text-white'
        },
        {
            key: 'conges',
            label: 'Congés en attente',
            value: stats.leave?.pending ? String(stats.leave.pending) : '3',
            icon: CalendarDays,
            href: leaveRequestsIndex.url({ query: { status: 'submitted' } }),
            bgColor: 'bg-brand-yellow',
            textColor: 'text-brand-yellow-foreground',
            iconBg: 'bg-black/10',
            iconColor: 'text-brand-yellow-foreground'
        },
        {
            key: 'turnover',
            label: 'Taux de Turnover',
            value: '3.4%',
            icon: Activity,
            href: '#',
            trend: '-0.5% vs an dernier',
            bgColor: 'bg-secondary',
            textColor: 'text-secondary-foreground',
            iconBg: 'bg-white/20',
            iconColor: 'text-white'
        },
        {
            key: 'recrutements',
            label: 'Postes Ouverts',
            value: '8',
            icon: Briefcase,
            href: '#',
            bgColor: 'bg-accent',
            textColor: 'text-accent-foreground',
            iconBg: 'bg-black/10',
            iconColor: 'text-accent-foreground'
        }
    ];

    const trainingData = [
        { name: 'Sécurité au travail', progress: 85, target: 100 },
        { name: 'Management Agile', progress: 45, target: 50 },
        { name: 'Nouvelles normes ISO', progress: 12, target: 120 },
    ];


    const containerVariants = {
        hidden: { opacity: 0 },
        show: {
            opacity: 1,
            transition: { staggerChildren: 0.1 }
        }
    };

    const itemVariants = {
        hidden: { opacity: 0, y: 15 },
        show: { 
            opacity: 1, 
            y: 0,
            transition: { type: 'spring' as const, stiffness: 350, damping: 30 }
        }
    };

    return (
        <>
            <Head title="Tableau de bord RH" />

            <motion.div variants={containerVariants} initial="hidden" animate="show" className="flex h-full flex-1 flex-col gap-8 p-4 md:p-6 pb-20">
                <header className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="space-y-1">
                        <h1 className="text-2xl font-semibold tracking-tight">{greetingForHour(now.getHours())}, {userName}</h1>
                        <p className="text-sm text-muted-foreground capitalize">{formatLongDate(now)}</p>
                    </div>
                </header>

                {/* 1. KPIs */}
                <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    {topKpis.map((card, i) => {
                        const Icon = card.icon;
                        return (
                            <motion.div key={card.key} variants={itemVariants}>
                                <Link
                                    href={card.href}
                                    className={cn(
                                        'group flex flex-col justify-between h-full rounded-2xl p-5 shadow-sm transition-all hover:shadow-md hover:-translate-y-1',
                                        card.bgColor,
                                        card.textColor
                                    )}
                                >
                                    <div className="flex items-start justify-between gap-3">
                                        <div className="space-y-1.5">
                                            <p className="text-sm font-medium opacity-90">{card.label}</p>
                                            <p className="text-3xl font-bold tracking-tight">{card.value}</p>
                                        </div>
                                        <span className={cn(
                                            'flex size-10 items-center justify-center rounded-xl',
                                            card.iconBg,
                                            card.iconColor
                                        )}>
                                            <Icon className="size-5" />
                                        </span>
                                    </div>
                                    {card.trend && (
                                        <div className="mt-4 flex items-center gap-1.5 text-xs opacity-90">
                                            <TrendingUp className="size-3" />
                                            <span>{card.trend}</span>
                                        </div>
                                    )}
                                </Link>
                            </motion.div>
                        );
                    })}
                </div>

                {/* 2. Main Charts */}
                <div className="grid gap-6 lg:grid-cols-2">
                    <motion.div variants={itemVariants} className="flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5 shadow-sm">
                        <div className="flex items-center justify-between">
                            <h3 className="text-base font-semibold">Présences & Absences</h3>
                            <span className="rounded-full bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground">Derniers 6 mois</span>
                        </div>
                        <EmployeeAttendanceChart />
                    </motion.div>

                    <motion.div variants={itemVariants} className="flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5 shadow-sm">
                        <div className="flex items-center justify-between">
                            <h3 className="text-base font-semibold">Masse Salariale</h3>
                            <span className="rounded-full bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground">En FCFA</span>
                        </div>
                        <PayrollEvolutionChart />
                    </motion.div>
                </div>

                {/* 3. Secondary Metrics */}
                <div className="grid gap-6 lg:grid-cols-3">
                    {/* Turnover */}
                    <motion.div variants={itemVariants} className="flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5 shadow-sm">
                        <h3 className="text-base font-semibold">Turnover (YTD)</h3>
                        <div className="flex-1 flex items-center justify-center">
                            <TurnoverPieChart />
                        </div>
                        <div className="grid grid-cols-2 gap-2 text-sm text-center mt-2">
                            <div className="rounded-lg p-2" style={{ color: 'var(--chart-4)', backgroundColor: 'color-mix(in srgb, var(--chart-4) 15%, transparent)' }}>
                                <span className="block font-bold">4</span>
                                <span className="text-xs">Départs</span>
                            </div>
                            <div className="rounded-lg p-2" style={{ color: 'var(--chart-3)', backgroundColor: 'color-mix(in srgb, var(--chart-3) 20%, transparent)' }}>
                                <span className="block font-bold">12</span>
                                <span className="text-xs">Arrivées</span>
                            </div>
                        </div>
                    </motion.div>

                    {/* Formations */}
                    <motion.div variants={itemVariants} className="flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5 shadow-sm">
                        <div className="flex items-center justify-between">
                            <h3 className="text-base font-semibold">Formations</h3>
                            <GraduationCap className="size-4 text-muted-foreground" />
                        </div>
                        <div className="space-y-5 mt-2">
                            {trainingData.map(training => (
                                <div key={training.name} className="space-y-2">
                                    <div className="flex items-center justify-between text-sm">
                                        <span className="font-medium">{training.name}</span>
                                        <span className="text-muted-foreground">{training.progress}/{training.target} inscrits</span>
                                    </div>
                                    <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
                                        <div
                                            className="h-full bg-primary rounded-full"
                                            style={{ width: `${(training.progress / training.target) * 100}%` }}
                                        />
                                    </div>
                                </div>
                            ))}
                        </div>
                    </motion.div>

                    {/* Recruitment Funnel */}
                    <motion.div variants={itemVariants} className="flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5 shadow-sm">
                        <h3 className="text-base font-semibold">Pipeline Recrutement</h3>
                        <RecruitmentFunnelChart />
                    </motion.div>
                </div>

                {/* 4. Performance & Reviews */}
                <div className="grid gap-6 lg:grid-cols-2">
                    <motion.div variants={itemVariants} className="flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5 shadow-sm">
                        <div className="flex items-center gap-2">
                            <Award className="size-5 text-primary" />
                            <h3 className="text-base font-semibold">Bilan des Compétences Globales</h3>
                        </div>
                        <div className="flex items-center justify-center">
                            <PerformanceRadarChart />
                        </div>
                    </motion.div>

                    <motion.div variants={itemVariants} className="flex flex-col gap-4 rounded-2xl border border-primary/10 bg-card p-5 shadow-sm justify-center">
                        <div className="text-center space-y-2">
                            <CheckCircle2 className="size-12 mx-auto mb-4 opacity-80" style={{ color: 'var(--chart-2)' }} />
                            <h3 className="text-lg font-semibold">Campagne d'évaluation 2026</h3>
                            <p className="text-sm text-muted-foreground px-8">
                                85% des collaborateurs ont finalisé leur entretien annuel.
                                Clôture prévue dans 15 jours.
                            </p>
                        </div>
                        <div className="mt-6 flex justify-center">
                            <Link href="#" className="inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90">
                                Voir les évaluations
                            </Link>
                        </div>
                    </motion.div>
                </div>

            </motion.div>
        </>
    );
}

Dashboard.layout = (page: React.ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Tableau de bord', href: '/dashboard' },
        ]}
    >
        {page}
    </AppLayout>
);
