import React, { useEffect, useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import ExcelTable from '../components/ExcelTable';
import { 
    Calendar, 
    RefreshCw, 
    CalendarDays,
    Clock,
    AlertTriangle,
    CheckCircle2,
    PieChart as PieIcon,
    BarChart3,
    ArrowUpRight,
    Users,
    Search,
    ChevronRight,
    Briefcase,
    Building2,
    Filter
} from 'lucide-react';
import { 
    PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip,
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Legend
} from 'recharts';
import { useGestaoFerias } from '../hooks/useGestaoFerias';
import { RhFeedbackContainer } from '../components/RhFeedbackNotification';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';

const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#f97316'];

const containerVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: { 
        opacity: 1, 
        y: 0,
        transition: { 
            duration: 0.6, 
            staggerChildren: 0.1 
        }
    }
};

const itemVariants = {
    hidden: { opacity: 0, y: 10 },
    visible: { opacity: 1, y: 0 }
};

const KPISection = React.memo(({ stats, vacations }) => {
    return (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {[
                { label: 'Férias Críticas', value: stats?.vencendo || 0, icon: AlertTriangle, color: 'text-rose-500', bg: 'bg-rose-500/10' },
                { label: 'Colaboradores em Gozo', value: stats?.emGozo || 0, icon: Users, color: 'text-blue-500', bg: 'bg-blue-500/10' },
                { label: 'Direitos Ativos', value: vacations.length, icon: CheckCircle2, color: 'text-emerald-500', bg: 'bg-emerald-500/10' },
                { label: 'Dias Acumulados', value: stats?.totalDias || 0, icon: Clock, color: 'text-amber-500', bg: 'bg-amber-500/10' }
            ].map((card, i) => (
                <motion.div 
                    key={i} 
                    variants={itemVariants}
                    whileHover={{ y: -5, scale: 1.02 }}
                    className="bg-white dark:bg-[#1b1b1b] p-6 rounded-[28px] border border-slate-200 dark:border-white/5 flex items-center justify-between shadow-sm border-b-4 border-b-slate-100 dark:border-b-white/5 transition-all"
                >
                    <div className="flex items-center gap-5">
                        <div className={`p-4 rounded-[22px] ${card.bg}`}>
                            <card.icon className={card.color} size={28} />
                        </div>
                        <div className="space-y-1">
                            <span className="text-[10px] uppercase font-bold text-slate-400 tracking-[0.1em]">{card.label}</span>
                            <h4 className="text-3xl font-black text-slate-800 dark:text-white leading-none">{card.value}</h4>
                        </div>
                    </div>
                    <div className="p-2 rounded-xl bg-slate-50 dark:bg-white/5">
                        <ArrowUpRight size={14} className="text-slate-300" />
                    </div>
                </motion.div>
            ))}
        </div>
    );
});

const ChartsSection = React.memo(({ stats }) => {
    return (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* Linear Chart */}
            <motion.div variants={itemVariants} className="bg-white dark:bg-[#1b1b1b] p-8 rounded-[32px] border border-slate-200 dark:border-white/5 shadow-xl shadow-slate-200/20 dark:shadow-none">
                <div className="flex items-center justify-between mb-10">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-blue-500/10 rounded-xl"><BarChart3 size={18} className="text-blue-500" /></div>
                        <h3 className="font-bold text-slate-800 dark:text-white uppercase tracking-widest text-[10px]">Cronograma de Vencimento</h3>
                    </div>
                    <Badge className="bg-blue-500/5 text-blue-500 border-none font-bold text-[9px]">ANUAL</Badge>
                </div>
                <div className="h-[280px] w-full">
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={stats?.chartMonthly || []} margin={{ top: 0, right: 0, left: -20, bottom: 0 }}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#88888815" />
                            <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fontSize: 9, fontWeight: 700, fill: '#94a3b8' }} />
                            <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 9, fontWeight: 700, fill: '#94a3b8' }} />
                            <RechartsTooltip 
                                contentStyle={{ backgroundColor: '#131313', border: 'none', borderRadius: '16px', color: '#fff', fontSize: '10px', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }}
                                cursor={{ fill: '#88888808' }}
                            />
                            <Bar dataKey="Total" fill="#3b82f6" radius={[6, 6, 0, 0]} barSize={24} />
                            <Bar dataKey="Vencendo" fill="#f43f5e" radius={[6, 6, 0, 0]} barSize={24} />
                        </BarChart>
                    </ResponsiveContainer>
                </div>
                <div className="mt-8 flex items-center justify-center gap-6">
                    <div className="flex items-center gap-2"><div className="w-2 h-2 rounded-full bg-blue-500"></div><span className="text-[10px] font-bold text-slate-400">TOTAL</span></div>
                    <div className="flex items-center gap-2"><div className="w-2 h-2 rounded-full bg-rose-500"></div><span className="text-[10px] font-bold text-slate-400">CRÍTICOS</span></div>
                </div>
            </motion.div>

            {/* Donut Chart with Improved Legend */}
            <motion.div variants={itemVariants} className="bg-white dark:bg-[#1b1b1b] p-8 rounded-[32px] border border-slate-200 dark:border-white/5 shadow-xl shadow-slate-200/20 dark:shadow-none">
                <div className="flex items-center justify-between mb-10">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-emerald-500/10 rounded-xl"><PieIcon size={18} className="text-emerald-500" /></div>
                        <h3 className="font-bold text-slate-800 dark:text-white uppercase tracking-widest text-[10px]">Distribuição por Empresa</h3>
                    </div>
                </div>
                <div className="h-[280px] w-full flex flex-col sm:flex-row items-center">
                    <div className="w-full sm:w-1/2 h-full">
                        <ResponsiveContainer width="100%" height="100%">
                            <PieChart>
                                <Pie
                                    data={stats?.chartByCompany || []}
                                    innerRadius={75}
                                    outerRadius={95}
                                    paddingAngle={8}
                                    dataKey="value"
                                    stroke="none"
                                >
                                    {(stats?.chartByCompany || []).map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                    ))}
                                </Pie>
                                <RechartsTooltip />
                            </PieChart>
                        </ResponsiveContainer>
                    </div>
                    <div className="w-full sm:w-1/2 space-y-3 pl-4">
                        {(stats?.chartByCompany || []).slice(0, 6).map((item, i) => (
                            <div key={i} className="flex items-center justify-between group transition-all">
                                <div className="flex items-center gap-3 overflow-hidden">
                                    <div className="min-w-2 h-2 rounded-full shadow-sm" style={{ backgroundColor: COLORS[i % COLORS.length] }}></div>
                                    <span className="text-[11px] font-bold text-slate-500 dark:text-slate-400 truncate group-hover:text-slate-900 dark:group-hover:text-white transition-colors uppercase tracking-tight">
                                        {item.name}
                                    </span>
                                </div>
                                <div className="flex items-center gap-2 pl-2">
                                    <span className="text-[11px] font-black text-slate-800 dark:text-white">{item.value}</span>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </motion.div>
        </div>
    );
});

const MonthlySummaryGrid = React.memo(({ stats, months, onMonthClick }) => {
    return (
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-5">
            {months.map((mes, idx) => {
                const monthData = stats?.monthly ? stats.monthly[idx] : { count: 0, urgent: 0 };
                return (
                    <motion.div 
                        key={idx}
                        whileHover={{ y: -8, scale: 1.05 }}
                        className="relative p-6 rounded-[28px] border border-slate-200 dark:border-white/5 bg-white dark:bg-[#1b1b1b] text-center shadow-sm hover:shadow-2xl hover:shadow-blue-500/10 hover:border-blue-400 dark:hover:border-blue-500/50 transition-all cursor-pointer group overflow-hidden"
                        onClick={() => onMonthClick(idx + 1)}
                    >
                        <div className="absolute top-0 right-0 p-3 opacity-10 group-hover:opacity-100 transition-opacity">
                            <ArrowUpRight size={12} className="text-blue-500" />
                        </div>
                        <p className="text-[10px] font-black text-slate-300 dark:text-slate-600 uppercase tracking-[0.2em] group-hover:text-blue-500 transition-colors">{mes.substring(0, 3)}</p>
                        <p className="text-4xl font-black text-slate-800 dark:text-white mt-2 group-hover:scale-110 transition-transform">{monthData.count}</p>
                        
                        <div className="mt-4 pt-4 border-t border-slate-50 dark:border-white/2 flex flex-col items-center gap-1.5">
                            {monthData.urgent > 0 ? (
                                <Badge className="bg-rose-500/10 text-rose-500 border-none font-bold text-[8px] px-2 py-0.5 rounded-lg animate-pulse">
                                    {monthData.urgent} CRÍTICOS
                                </Badge>
                            ) : (
                                <span className="text-[8px] font-bold text-emerald-500 bg-emerald-500/5 px-2 py-0.5 rounded-lg">REGULAR</span>
                            )}
                        </div>
                    </motion.div>
                );
            })}
        </div>
    );
});

const DetailModal = React.memo(({ open, onOpenChange, mesSelecionado, months, year, vacations }) => {
    const [modalSearch, setModalSearch] = useState('');
    const [modalStatusFilter, setModalStatusFilter] = useState('all');
    const [visibleCount, setVisibleCount] = useState(30);

    useEffect(() => {
        if (open) {
            setVisibleCount(30);
        }
    }, [open, modalSearch, modalStatusFilter, mesSelecionado]);

    const filteredForModal = useMemo(() => {
        if (!mesSelecionado) return [];
        return vacations.filter(v => {
            const limitMonth = v.limitDateObj.getMonth() + 1;
            const matchesMonth = limitMonth === mesSelecionado;
            const matchesSearch = v.name.toLowerCase().includes(modalSearch.toLowerCase());
            const matchesStatus = modalStatusFilter === 'all' || 
                (modalStatusFilter === 'urgent' && (v.limitDateObj - new Date()) < (60 * 24 * 60 * 60 * 1000));
            
            return matchesMonth && matchesSearch && matchesStatus;
        });
    }, [vacations, mesSelecionado, modalSearch, modalStatusFilter]);

    const displayedVacations = useMemo(() => {
        return filteredForModal.slice(0, visibleCount);
    }, [filteredForModal, visibleCount]);

    const handleLoadMore = () => {
        setVisibleCount(prev => prev + 30);
    };

    if (!mesSelecionado) return null;

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-5xl bg-[#fafafa] dark:bg-[#0e0e0e] border-slate-200 dark:border-white/10 p-0 overflow-hidden flex flex-col max-h-[85vh] rounded-[32px] shadow-2xl">
                <DialogHeader className="p-10 bg-white dark:bg-white/2 border-b border-slate-100 dark:border-white/5 flex-shrink-0">
                    <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
                        <div className="flex items-center gap-5">
                            <div className="p-4 bg-blue-500/10 rounded-[22px] text-blue-500 shadow-inner">
                                <CalendarDays size={32} />
                            </div>
                            <div className="space-y-1">
                                <DialogTitle className="text-3xl font-black text-slate-800 dark:text-white tracking-tighter uppercase leading-none">
                                    {months[mesSelecionado - 1]} <span className="text-blue-500">{year}</span>
                                </DialogTitle>
                                <DialogDescription className="text-slate-400 font-bold text-xs uppercase tracking-widest pl-1">
                                    Férias com Vencimento no Período
                                </DialogDescription>
                            </div>
                        </div>
                        
                        <div className="flex items-center gap-3 w-full md:w-auto">
                            <div className="relative flex-1 md:w-64">
                                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                                <Input 
                                    placeholder="Pesquisar..." 
                                    value={modalSearch}
                                    onChange={(e) => setModalSearch(e.target.value)}
                                    className="pl-9 h-11 bg-slate-50 dark:bg-white/5 border-slate-200 dark:border-white/5 rounded-2xl text-[11px] font-bold" 
                                />
                            </div>
                            <div className="flex items-center gap-1.5 p-1 bg-slate-100 dark:bg-white/5 rounded-2xl">
                                <button 
                                    onClick={() => setModalStatusFilter('all')}
                                    className={`px-3 py-2 rounded-xl text-[10px] font-bold uppercase transition-all ${modalStatusFilter === 'all' ? 'bg-white dark:bg-slate-700 shadow-sm text-blue-500 dark:text-white' : 'text-slate-400'}`}
                                >Todos</button>
                                <button 
                                    onClick={() => setModalStatusFilter('urgent')}
                                    className={`px-3 py-2 rounded-xl text-[10px] font-bold uppercase transition-all ${modalStatusFilter === 'urgent' ? 'bg-rose-500 text-white shadow-lg' : 'text-slate-400'}`}
                                >Críticos</button>
                            </div>
                        </div>
                    </div>
                </DialogHeader>
                
                <div className="flex-1 overflow-y-auto p-10 custom-scrollbar">
                    <AnimatePresence mode="popLayout">
                        {filteredForModal.length > 0 ? (
                            <motion.div 
                                key="list"
                                initial={{ opacity: 0 }}
                                animate={{ opacity: 1 }}
                                exit={{ opacity: 0 }}
                                className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
                            >
                                {displayedVacations.map((v, i) => (
                                    <motion.div 
                                        key={v.id}
                                        initial={{ opacity: 0, scale: 0.9 }}
                                        animate={{ opacity: 1, scale: 1 }}
                                        transition={{ delay: (i % 30) * 0.05 }}
                                        whileHover={{ y: -5 }}
                                        className="bg-white dark:bg-[#1b1b1b] p-6 rounded-[28px] border border-slate-200 dark:border-white/5 shadow-sm hover:shadow-xl transition-all group border-b-4 border-b-slate-100 dark:border-b-white/5"
                                    >
                                        <div className="flex items-start justify-between mb-6">
                                            <div className="flex items-center gap-3">
                                                <Avatar className="h-10 w-10 rounded-[14px] border-2 border-slate-50 dark:border-white/5">
                                                    <AvatarImage src={v.avatar} />
                                                    <AvatarFallback className="bg-blue-500/10 text-blue-500 font-black text-xs">
                                                        {v.name.substring(0,2).toUpperCase()}
                                                    </AvatarFallback>
                                                </Avatar>
                                                <div>
                                                    <h5 className="font-black text-slate-800 dark:text-slate-100 text-xs uppercase leading-tight mb-0.5">{v.name}</h5>
                                                    <p className="text-[9px] text-slate-400 font-bold uppercase tracking-widest">{v.companyName}</p>
                                                </div>
                                            </div>
                                            {(v.limitDateObj - new Date()) < (60 * 24 * 60 * 60 * 1000) && (
                                                <div className="p-1.5 bg-rose-500/10 rounded-lg"><AlertTriangle size={14} className="text-rose-500" /></div>
                                            )}
                                        </div>

                                        <div className="space-y-4">
                                            <div className="flex items-center justify-between text-[10px] p-3 bg-slate-50 dark:bg-white/2 rounded-2xl">
                                                <div className="flex items-center gap-2 font-bold text-slate-400 uppercase tracking-tighter">
                                                    <Briefcase size={12} className="text-slate-400" /> Vencimento
                                                </div>
                                                <span className="font-mono font-bold text-slate-700 dark:text-slate-200">{v.limitDate}</span>
                                            </div>
                                            
                                            <div className="grid grid-cols-2 gap-3">
                                                <div className="p-3 bg-blue-50 dark:bg-blue-500/5 rounded-2xl flex flex-col items-center justify-center gap-1.5 transition-colors group-hover:bg-blue-100 dark:group-hover:bg-blue-500/10">
                                                    <span className="text-[9px] font-black text-blue-400 uppercase tracking-tighter">Saldo</span>
                                                    <span className="text-xl font-black text-blue-600 dark:text-blue-400 leading-none">{v.diasAGozar}d</span>
                                                </div>
                                                <div className="p-3 bg-emerald-50 dark:bg-emerald-500/5 rounded-2xl flex flex-col items-center justify-center gap-1.5">
                                                    <span className="text-[9px] font-black text-emerald-400 uppercase tracking-tighter">Direito</span>
                                                    <span className="text-xl font-black text-emerald-600 dark:text-emerald-400 leading-none">{v.diasDireito}d</span>
                                                </div>
                                            </div>

                                            <div className="flex items-center gap-3 pt-2">
                                                <div className="flex-1 h-1.5 bg-slate-100 dark:bg-white/5 rounded-full overflow-hidden">
                                                    <motion.div 
                                                        initial={{ width: 0 }}
                                                        animate={{ width: `${(v.diasGozados / v.diasDireito) * 100}%` }}
                                                        className="h-full bg-blue-500 rounded-full"
                                                    />
                                                </div>
                                                <span className="text-[9px] font-black text-slate-400">{v.diasGozados} / {v.diasDireito}</span>
                                            </div>
                                        </div>
                                        
                                        <button className="w-full mt-6 py-3 rounded-2xl bg-slate-50 dark:bg-white/5 text-[9px] font-black text-slate-400 uppercase tracking-widest hover:bg-blue-600 hover:text-white transition-all transform active:scale-95 group-hover:border-blue-500/20 border border-transparent">
                                            Expandir Detalhes
                                        </button>
                                    </motion.div>
                                ))}
                                {filteredForModal.length > visibleCount && (
                                    <motion.div 
                                        initial={{ opacity: 0 }}
                                        animate={{ opacity: 1 }}
                                        className="col-span-1 md:col-span-2 lg:col-span-3 flex justify-center py-6"
                                    >
                                        <Button
                                            onClick={handleLoadMore}
                                            variant="outline"
                                            className="bg-white dark:bg-[#1b1b1b] hover:bg-slate-50 dark:hover:bg-white/5 text-slate-500 hover:text-blue-500 border border-slate-200 dark:border-white/10 shadow-sm font-bold uppercase tracking-widest text-[10px] px-8 py-6 rounded-2xl transition-all h-auto"
                                        >
                                            Carregar Mais ({filteredForModal.length - visibleCount} restantes)
                                        </Button>
                                    </motion.div>
                                )}
                            </motion.div>
                        ) : (
                            <motion.div 
                                key="empty"
                                initial={{ opacity: 0 }}
                                animate={{ opacity: 1 }}
                                className="flex flex-col items-center justify-center py-20 text-center"
                            >
                                <div className="p-6 bg-slate-100 dark:bg-white/5 rounded-full mb-6">
                                    <Search size={40} className="text-slate-300" />
                                </div>
                                <h5 className="text-xl font-bold text-slate-800 dark:text-white mb-2">Sem resultados encontrados</h5>
                                <p className="text-sm text-slate-400 max-w-xs mx-auto">Tente ajustar seus filtros ou termos de pesquisa para encontrar o que procura.</p>
                            </motion.div>
                        )}
                    </AnimatePresence>
                </div>
            </DialogContent>
        </Dialog>
    );
});

export const GestaoFeriasView = () => {
    const { 
        vacations, 
        loading, 
        filters, 
        stats,
        setFilters, 
        fetchVacations 
    } = useGestaoFerias();

    const [modalMesAberto, setModalMesAberto] = useState(false);
    const [mesSelecionado, setMesSelecionado] = useState(null);

    useEffect(() => {
        fetchVacations();
    }, [filters.month, filters.year, filters.department]);

    const columns = useMemo(() => [
        { 
            field: 'name', 
            header: 'Funcionário', 
            width: 300, 
            render: (row) => (
                <div className="flex items-center gap-3">
                    <Avatar className="h-8 w-8 rounded-lg border border-slate-200 dark:border-white/10">
                        <AvatarImage src={row.avatar} />
                        <AvatarFallback className="bg-blue-500/10 text-blue-500 font-bold text-[10px]">
                            {row.name.substring(0, 2).toUpperCase()}
                        </AvatarFallback>
                    </Avatar>
                    <div className="flex flex-col">
                        <span className="font-bold text-slate-800 dark:text-slate-100 text-[13px]">{row.name}</span>
                        <span className="text-[10px] text-slate-400 font-medium uppercase tracking-tight">{row.companyName}</span>
                    </div>
                </div>
            ) 
        },
        { field: 'admissionDate', header: 'Admissão', width: 110, className: 'font-mono text-xs' },
        { field: 'lastReturnDate', header: 'Último Retorno', width: 110, className: 'font-mono text-xs' },
        { 
            field: 'limitDate', 
            header: 'Data Limite', 
            width: 120, 
            render: (row) => {
                const now = new Date();
                const isClose = (row.limitDateObj - now) < (60 * 24 * 60 * 60 * 1000);
                return (
                    <div className="flex items-center gap-2">
                        <span className={`font-mono text-xs font-bold ${isClose ? 'text-rose-500 bg-rose-500/10 px-2 py-0.5 rounded-md' : 'text-slate-600 dark:text-slate-400'}`}>
                            {row.limitDate}
                        </span>
                    </div>
                );
            }
        },
        { field: 'faltas', header: 'Faltas', width: 70, className: 'text-center font-bold text-xs' },
        { field: 'diasAGozar', header: 'Saldo', width: 90, render: (row) => (
            <Badge variant="outline" className={`rounded-xl border-none font-bold text-[10px] ${row.diasAGozar > 0 ? 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300' : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'}`}>
                {row.diasAGozar} DIAS
            </Badge>
        )}
    ], []);

    const months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];

    const handleMonthClick = (monthIdx) => {
        setMesSelecionado(monthIdx);
        setModalMesAberto(true);
    };

    return (
        <div className="theme-rh flex-1 flex flex-col h-full w-full overflow-hidden bg-[#fafafa] dark:bg-[#0a0a0a] p-4 sm:p-6 lg:p-10 space-y-8">
            
            {/* Header section with Animations */}
            <motion.div 
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                className="flex flex-col xl:flex-row xl:items-center justify-between gap-6"
            >
                <div className="space-y-2">
                    <div className="flex items-center gap-4">
                        <div className="p-3 bg-blue-500/10 rounded-2xl shadow-inner border border-blue-500/5">
                            <Calendar className="text-blue-500" size={28} />
                        </div>
                        <h1 className="text-3xl md:text-5xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
                            Gestão de <span className="text-blue-600">Férias</span>
                        </h1>
                    </div>
                    <p className="text-slate-400 dark:text-slate-500 text-sm md:text-base font-medium italic opacity-80 pl-1">
                        Controle centralizado de períodos aquisitivos e cronograma de gozo
                    </p>
                </div>

                <div className="flex items-center gap-4 bg-white dark:bg-white/5 p-2 rounded-[24px] border border-slate-200 dark:border-white/5 shadow-sm">
                    <div className="flex items-center gap-2 px-3 border-r border-slate-200 dark:border-white/10">
                        <CalendarDays size={16} className="text-slate-400" />
                        <select 
                            value={filters.month}
                            onChange={(e) => setFilters({ month: parseInt(e.target.value) })}
                            className="bg-transparent border-none text-xs font-bold uppercase tracking-wider text-slate-600 dark:text-slate-300 focus:ring-0 cursor-pointer"
                        >
                            {months.map((m, i) => <option key={i} value={i+1}>{m}</option>)}
                        </select>
                    </div>
                    <select 
                        value={filters.year}
                        onChange={(e) => setFilters({ year: parseInt(e.target.value) })}
                        className="bg-transparent border-none text-xs font-bold uppercase tracking-wider text-slate-600 dark:text-slate-300 focus:ring-0 px-3 cursor-pointer"
                    >
                        {[2024, 2025, 2026].map(y => <option key={y} value={y}>{y}</option>)}
                    </select>
                    
                    <Button 
                        onClick={fetchVacations}
                        disabled={loading}
                        variant="ghost"
                        className="h-10 w-10 rounded-xl hover:bg-slate-100 dark:hover:bg-white/5"
                    >
                        <RefreshCw size={16} className={`${loading ? 'animate-spin' : ''} text-blue-500`} />
                    </Button>
                </div>
            </motion.div>

            <motion.div 
                variants={containerVariants}
                initial="hidden"
                animate="visible"
                className="flex-1 overflow-y-auto custom-scrollbar space-y-8 pr-2"
            >
                {/* Dash Cards */}
                <KPISection stats={stats} vacations={vacations} />

                {/* Charts Area */}
                <ChartsSection stats={stats} />

                {/* Monthly Summary Grid - Styled like Calendars */}
                <motion.div variants={itemVariants} className="space-y-6">
                    <div className="flex items-center gap-3 ml-2">
                        <div className="p-2 bg-indigo-500/10 rounded-xl"><CalendarDays size={18} className="text-indigo-500" /></div>
                        <h3 className="font-bold text-slate-800 dark:text-white uppercase tracking-widest text-[11px]">Resumo Mensal de Vencimentos</h3>
                    </div>
                    <MonthlySummaryGrid 
                        stats={stats} 
                        months={months} 
                        onMonthClick={handleMonthClick} 
                    />
                </motion.div>

                {/* Table Detail with Animation */}
                <motion.div variants={itemVariants} className="bg-white dark:bg-[#1b1b1b] rounded-[32px] border border-slate-200 dark:border-white/5 overflow-hidden flex flex-col shadow-2xl shadow-slate-200/20 dark:shadow-none min-h-[600px]">
                    <div className="p-8 border-b border-slate-200 dark:border-white/5 flex items-center justify-between">
                        <div className="flex items-center gap-4">
                            <div className="p-2 bg-indigo-500/5 rounded-xl"><Users className="text-indigo-500" size={18} /></div>
                            <div>
                                <h3 className="font-bold text-slate-800 dark:text-white uppercase tracking-widest text-[10px]">Detalhamento Operacional</h3>
                                <p className="text-[9px] text-slate-400 font-medium uppercase tracking-tighter mt-0.5">Visão tabular p/ exportação e filtros</p>
                            </div>
                        </div>
                        <div className="relative w-72">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                            <Input placeholder="Buscar na tabela..." className="pl-9 h-10 border-slate-200 dark:border-white/5 bg-slate-50 dark:bg-white/5 rounded-xl text-xs font-semibold" />
                        </div>
                    </div>
                    <div className="flex-1 overflow-hidden p-4">
                        <ExcelTable 
                            data={vacations}
                            columns={columns}
                            filterDefs={[]}
                            pageSize={10}
                            loading={loading}
                        />
                    </div>
                </motion.div>
            </motion.div>

            {/* Modal de Detalhes por Mês - Revamped with cards and Animations */}
            <DetailModal 
                open={modalMesAberto}
                onOpenChange={setModalMesAberto}
                mesSelecionado={mesSelecionado}
                months={months}
                year={filters.year}
                vacations={vacations}
            />

            <RhFeedbackContainer />
        </div>
    );
};
