import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useEmployees } from '../hooks/useEmployees';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription
} from "@/components/ui/dialog";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
    BarChart,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    ResponsiveContainer,
    Cell,
    PieChart,
    Pie,
    Bar
} from 'recharts';
import {
    TrendingUp,
    Users,
    DollarSign,
    Activity,
    Calendar,
    AlertCircle,
    ArrowUpRight,
    ArrowDownRight,
    Briefcase,
    Building2,
    MapPin,
    RefreshCw,
    ShieldCheck,
    Mail,
    Laptop,
    Bell
} from 'lucide-react';
import ExcelTable from '../components/ExcelTable';

export const RhDashboardView = () => {
    const { 
        statistics, 
        alerts, 
        fetchStatistics, 
        fetchAlerts, 
        loading 
    } = useEmployees();

    const [chartData, setChartData] = useState({
        por_base: [],
        por_cargo: [],
        por_cliente: [],
        por_status: [],
        por_empresa: []
    });
    
    const [windowWidth, setWindowWidth] = useState(window.innerWidth);
    const [chartsReady, setChartsReady] = useState(false);
    const [rawAlerts, setRawAlerts] = useState(null);
    const [selectedAlert, setSelectedAlert] = useState(null);
    const [isAlertModalOpen, setIsAlertModalOpen] = useState(false);

    const loadData = useCallback(async () => {
        try {
            const statsResult = await fetchStatistics();
            const alertsResult = await fetchAlerts();
            setRawAlerts(alertsResult);
            
            if (statsResult?.charts) {
                setChartData({
                    por_base: Array.isArray(statsResult.charts.por_base) ? statsResult.charts.por_base : [],
                    por_cargo: Array.isArray(statsResult.charts.por_cargo) ? statsResult.charts.por_cargo : [],
                    por_cliente: Array.isArray(statsResult.charts.por_cliente) ? statsResult.charts.por_cliente : [],
                    por_status: Array.isArray(statsResult.charts.por_status) ? statsResult.charts.por_status : [],
                    por_empresa: Array.isArray(statsResult.charts.por_empresa) ? statsResult.charts.por_empresa : []
                });
                setTimeout(() => setChartsReady(true), 100);
            }
        } catch (error) {
            console.error("Erro ao carregar dashboard:", error);
        }
    }, [fetchStatistics, fetchAlerts]);

    useEffect(() => {
        loadData();
        const handleResize = () => setWindowWidth(window.innerWidth);
        window.addEventListener('resize', handleResize);
        const timer = setTimeout(() => setChartsReady(true), 200);
        return () => {
            window.removeEventListener('resize', handleResize);
            clearTimeout(timer);
        };
    }, [loadData]);

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

    const statusPieData = useMemo(() => {
        if (!chartData?.por_status || chartData.por_status.length === 0) return [];
        return chartData.por_status.map((item, index) => ({
            name: item.status_contrato || 'N/A',
            value: Number(item.quantidade || 0),
            color: COLORS[index % COLORS.length]
        }));
    }, [chartData.por_status]);

    const cargoBarData = useMemo(() => {
        if (!chartData?.por_cargo || chartData.por_cargo.length === 0) return [];
        return chartData.por_cargo.slice(0, 8).map(item => ({
            name: item.cargo && item.cargo.length > 20 ? item.cargo.substring(0, 20) + '...' : (item.cargo || 'N/A'),
            total: Number(item.quantidade || 0)
        }));
    }, [chartData.por_cargo]);

    const handleAlertClick = (alert) => {
        if (!rawAlerts) return;
        
        let data = [];
        const key = alert.label.toLowerCase().includes('cnh vencida') ? 'cnh_vencida' :
                    alert.label.toLowerCase().includes('cnh a vencer') ? 'cnh_proxima_vencer' :
                    alert.label.toLowerCase().includes('férias') ? 'ferias_proximas' :
                    alert.label.toLowerCase().includes('falta telefone') ? 'sem_telefone' :
                    alert.label.toLowerCase().includes('email') ? 'sem_email_corporativo' : null;
        
        if (key && rawAlerts[key]) {
            data = rawAlerts[key].map(emp => ({
                id: emp.idcolaborador || emp.id,
                colaborador: emp.colaboradores || emp.nome,
                cargo: emp.cargo || 'N/A',
                base: emp.base || 'N/A',
                status: emp.status_contrato || 'Ativo',
                info: key === 'cnh_vencida' || key === 'cnh_proxima_vencer' ? emp.validade_cnh :
                      key === 'ferias_proximas' ? emp.data_limite_ferias : 
                      key === 'sem_telefone' ? 'Sem Telefone' : 'Sem Email'
            }));
            setSelectedAlert({ title: alert.label, data });
            setIsAlertModalOpen(true);
        }
    };

    const alertColumns = [
        { field: 'id', header: 'ID', width: 60 },
        { field: 'colaborador', header: 'Colaborador', width: 220 },
        { field: 'cargo', header: 'Cargo', width: 140 },
        { field: 'base', header: 'Base', width: 120 },
        { field: 'info', header: 'Detalhe', width: 130, render: (row) => (
            <span className="text-[clamp(0.875rem,0.9vw,0.9375rem)] font-mono font-bold text-slate-500 uppercase">
                {row.info?.includes('Sun') || row.info?.includes('Mon') || row.info?.includes('-') 
                    ? new Date(row.info).toLocaleDateString() 
                    : row.info}
            </span>
        )}
    ];

    return (
        <div className="theme-rh flex-1 flex flex-col h-full w-full overflow-hidden bg-slate-50/50 dark:bg-[#0a0a0a] p-4 sm:p-6 md:p-8">
            {/* Header */}
            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6 sm:mb-10">
                <div className="space-y-1">
                    <div className="flex items-center gap-3">
                        <div className="p-2 sm:p-3 bg-emerald-500/10 rounded-3xl">
                            <TrendingUp className="text-emerald-500" size={24} />
                        </div>
                        <h1 className="text-[clamp(1.5rem,3vw,2.25rem)] font-semibold text-slate-800 dark:text-white tracking-tight">
                           RH Intelligence
                        </h1>
                    </div>
                    <p className="text-slate-500 text-[clamp(1rem,1.4vw,1.25rem)] font-normal ml-1">
                        Monitoramento analítico do capital humano em tempo real.
                    </p>
                </div>
                
                <button 
                    onClick={loadData}
                    disabled={loading}
                    className="flex items-center gap-3 px-4 sm:px-6 py-2 sm:py-3 bg-white dark:bg-[#1b1b1b] rounded-xl border border-slate-200 dark:border-white/10 shadow-sm hover:shadow-md transition-all text-slate-600 dark:text-slate-300 text-[clamp(1rem,1.1vw,1.0625rem)] font-medium uppercase tracking-widest"
                >
                    <RefreshCw size={16} className={loading ? 'animate-spin text-emerald-500' : ''} />
                    Sincronizar
                </button>
            </div>

            <div className="flex-1 overflow-y-auto custom-scrollbar space-y-4 sm:space-y-6 lg:space-y-8 pr-2">
                {/* Stats Grid Principal - RESPONSIVO & FLUIDO */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-6 gap-4 sm:gap-6">
                    {(statistics || []).map((stat, idx) => (
                        <div key={idx} className="bg-white dark:bg-[#1b1b1b] p-4 sm:p-6 rounded-2xl border border-slate-200 dark:border-white/5 shadow-sm flex flex-col justify-between group hover:border-emerald-500/30 transition-all duration-300 min-h-[140px] sm:min-h-[160px] overflow-hidden">
                            <div className="flex items-center justify-between mb-2 sm:mb-4">
                                <div className={`p-2 sm:p-3 rounded-2xl sm:rounded-3xl ${stat.color} group-hover:scale-110 transition-transform`}>
                                    {stat.label.includes('CNH') ? <ShieldCheck className="w-4 h-4 sm:w-5 sm:h-5" /> : 
                                     stat.label.includes('Email') ? <Mail className="w-4 h-4 sm:w-5 sm:h-5" /> :
                                     stat.label.includes('Desktop') ? <Laptop className="w-4 h-4 sm:w-5 sm:h-5" /> : <Users className="w-4 h-4 sm:w-5 sm:h-5" />}
                                </div>
                                <span className={`text-[clamp(0.875rem,0.9vw,0.9375rem)] font-medium uppercase px-1.5 py-0.5 rounded-lg ${stat.negative ? 'bg-rose-500/10 text-rose-500' : 'bg-emerald-500/10 text-emerald-500'}`}>
                                    {stat.trend}
                                </span>
                            </div>
                            <div>
                                <h3 className="text-[clamp(1.5rem,2.8vw,2.25rem)] font-semibold text-slate-800 dark:text-white leading-tight break-all" title={stat.value}>{stat.value}</h3>
                                <p className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-400 font-medium uppercase tracking-wider mt-1 overflow-hidden" title={stat.label}>{stat.label}</p>
                            </div>
                        </div>
                    ))}
                </div>

                {/* Charts Layout - RESPONSIVO */}
                <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 sm:gap-6 md:gap-8">
                    {/* Principais Cargos */}
                    <Card className="lg:col-span-8 rounded-2xl border-slate-200 dark:border-white/5 bg-white dark:bg-[#1b1b1b] overflow-hidden">
                        <CardHeader className="pb-0 pt-6 sm:pt-8 md:pt-10 px-6 sm:px-8 md:px-10">
                            <div className="flex items-center justify-between">
                                <CardTitle className="text-[clamp(1.125rem,2vw,1.5rem)] font-semibold flex items-center gap-2 sm:gap-3 text-slate-800 dark:text-slate-200">
                                    <div className="w-1.5 h-6 sm:w-2 sm:h-8 bg-emerald-500 rounded-full" />
                                    Distribuição por Cargo
                                </CardTitle>
                                <span className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-slate-400 uppercase tracking-[0.2em]">Top 8 Cargos</span>
                            </div>
                        </CardHeader>
                        <CardContent className="p-4 sm:p-6 md:p-10">
                            <div className="h-[250px] sm:h-[300px] md:h-[350px] w-full" style={{ position: 'relative' }}>
                                {loading && !cargoBarData.length ? (
                                    <div className="h-full flex flex-col items-center justify-center text-slate-400 gap-3">
                                        <RefreshCw size={32} className="opacity-20 animate-spin" />
                                        <p className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium uppercase tracking-widest">Carregando...</p>
                                    </div>
                                ) : chartsReady && cargoBarData.length > 0 ? (
                                    <ResponsiveContainer width="100%" height="100%">
                                        <BarChart data={cargoBarData} layout="vertical" margin={{ left: 0, right: 10 }}>
                                            <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#33415510" />
                                            <XAxis type="number" hide />
                                            <YAxis 
                                                dataKey="name" 
                                                type="category" 
                                                axisLine={false} 
                                                tickLine={false} 
                                                width={windowWidth < 640 ? 80 : 140}
                                                tick={{ 
                                                    fill: '#94a3b8', 
                                                    fontSize: Math.max(10, Math.min(11, windowWidth * 0.01)), 
                                                    fontWeight: 800,
                                                    angle: 0,
                                                    textAnchor: 'end'
                                                }}
                                            />
                                            <Tooltip 
                                                cursor={{ fill: 'rgba(16, 185, 129, 0.05)' }}
                                                contentStyle={{ backgroundColor: '#1b1b1b', border: 'none', borderRadius: '16px', color: '#fff' }}
                                            />
                                            <Bar dataKey="total" fill="#10b981" radius={[0, 8, 8, 0]} barSize={16}>
                                                {cargoBarData.map((entry, index) => (
                                                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                                ))}
                                            </Bar>
                                        </BarChart>
                                    </ResponsiveContainer>
                                ) : (
                                    <div className="h-full flex flex-col items-center justify-center text-slate-400">
                                        <AlertCircle size={32} className="opacity-20" />
                                        <p className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium uppercase">Sem dados</p>
                                    </div>
                                )}
                            </div>
                        </CardContent>
                    </Card>

                    {/* Status do Contrato */}
                    <Card className="lg:col-span-4 rounded-2xl border-slate-200 dark:border-white/5 bg-white dark:bg-[#1b1b1b] overflow-hidden">
                        <CardHeader className="pb-0 pt-6 sm:pt-8 md:pt-10 px-6 sm:px-8 md:px-10">
                            <CardTitle className="text-[clamp(1.125rem,2vw,1.5rem)] font-semibold flex items-center gap-2 sm:gap-3 text-slate-800 dark:text-slate-200">
                                <div className="w-1.5 h-6 sm:w-2 sm:h-8 bg-blue-500 rounded-full" />
                                Status
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="p-4 sm:p-6 md:p-10">
                            <div className="h-[200px] sm:h-[250px] w-full">
                                {chartsReady && statusPieData.length > 0 ? (
                                    <ResponsiveContainer width="100%" height="100%">
                                        <PieChart>
                                            <Pie data={statusPieData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={5} dataKey="value">
                                                {statusPieData.map((entry, index) => (
                                                    <Cell key={`cell-${index}`} fill={entry.color} stroke="none" />
                                                ))}
                                            </Pie>
                                            <Tooltip />
                                        </PieChart>
                                    </ResponsiveContainer>
                                ) : null}
                            </div>
                            <div className="mt-4 sm:mt-6 space-y-2">
                                {statusPieData.map((item, i) => (
                                    <div key={i} className="flex items-center justify-between">
                                        <div className="flex items-center gap-2">
                                            <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: item.color }} />
                                            <span className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-slate-500 uppercase leading-tight" title={item.name}>{item.name}</span>
                                        </div>
                                        <span className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold">{item.value}</span>
                                    </div>
                                ))}
                            </div>
                        </CardContent>
                    </Card>

                    {/* Alertas Críticos - Grelha Responsiva */}
                    <div className="lg:col-span-12 mt-2 sm:mt-4">
                        <div className="flex items-center justify-between mb-4 sm:mb-6 px-2">
                            <h2 className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase text-slate-400 tracking-[0.2em] sm:tracking-[0.3em] flex items-center gap-2 sm:gap-3">
                                <Bell size={16} className="text-rose-500 sm:w-[18px] sm:h-[18px]" /> Atenção & Alertas
                            </h2>
                        </div>
                        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-5 gap-4 sm:gap-6">
                            {(alerts || []).map((alert, idx) => (
                                <button 
                                    key={idx} 
                                    onClick={() => handleAlertClick(alert)}
                                    className="bg-white dark:bg-[#1b1b1b] p-4 sm:p-5 md:p-6 rounded-2xl border border-slate-200 dark:border-white/5 hover:border-rose-500/30 transition-all text-left group shadow-sm active:scale-95 flex flex-col justify-between min-h-[140px] sm:min-h-[160px] overflow-hidden"
                                >
                                    <div className="flex items-center gap-3 sm:gap-4 mb-3 sm:mb-4">
                                        <div className={`p-2.5 sm:p-3 rounded-2xl sm:rounded-3xl ${alert.color} group-hover:scale-110 transition-transform shadow-inner`}>
                                            <AlertCircle className="w-5 h-5 sm:w-6 sm:h-6" />
                                        </div>
                                         <div className="min-w-0 flex-1">
                                            <h4 className="text-[clamp(1.5rem,2.8vw,2.25rem)] font-semibold text-slate-800 dark:text-white leading-none mb-1">{alert.value}</h4>
                                            <p className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-400 font-medium uppercase tracking-widest leading-tight" title={alert.label}>{alert.label}</p>
                                        </div>
                                    </div>
                                    <div className="flex items-center justify-between pt-3 sm:pt-4 border-t border-slate-50 dark:border-white/5 w-full">
                                        <span className={`text-[clamp(0.875rem,0.9vw,0.9375rem)] font-medium uppercase px-2 py-1 rounded-xl ${alert.negative ? 'bg-rose-500/10 text-rose-500' : 'bg-emerald-500/10 text-emerald-500'}`}>
                                            {alert.trend}
                                        </span>
                                        <div className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-emerald-600 dark:text-emerald-400 group-hover:translate-x-1 transition-transform uppercase whitespace-nowrap">Ver Lista →</div>
                                    </div>
                                </button>
                            ))}
                        </div>
                    </div>
                </div>
            </div>

            {/* Modal de Detalhes do Alerta */}
            <Dialog open={isAlertModalOpen} onOpenChange={setIsAlertModalOpen}>
                <DialogContent className="max-w-4xl bg-white dark:bg-[#1b1b1b] border-slate-200 dark:border-white/10 rounded-2xl overflow-hidden p-0 max-h-[90vh] flex flex-col">
                    <DialogHeader className="p-8 bg-slate-50 dark:bg-white/[0.02] border-b border-slate-100 dark:border-white/5 flex-shrink-0">
                        <div className="flex items-center gap-4">
                            <div className="p-3 bg-rose-500/10 rounded-3xl text-rose-500">
                                <AlertCircle size={24} />
                            </div>
                            <div>
                                <DialogTitle className="text-[clamp(1.125rem,2vw,1.5rem)] font-semibold uppercase tracking-tight text-slate-800 dark:text-white">
                                    {selectedAlert?.title}
                                </DialogTitle>
                                <DialogDescription className="text-slate-400 text-[clamp(1rem,1.1vw,1.0625rem)] font-medium uppercase">
                                    Lista de {selectedAlert?.data.length} colaboradores identificados
                                </DialogDescription>
                            </div>
                        </div>
                    </DialogHeader>
                    <div className="flex-1 overflow-hidden p-4 min-h-0 flex flex-col" style={{ height: 'calc(90vh - 180px)', minHeight: '400px', maxHeight: 'calc(90vh - 180px)' }}>
                        <ExcelTable 
                            data={selectedAlert?.data || []}
                            columns={alertColumns}
                            pageSize={50}
                        />
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
};
