import React, { useEffect } from 'react';
import { 
    Users, 
    AlertCircle, 
    CalendarCheck, 
    Clock,
    Building2,
    AlertTriangle,
    TrendingDown
} from 'lucide-react';
import {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell,
    PieChart, Pie, Legend
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { 
    Select, 
    SelectContent, 
    SelectItem, 
    SelectTrigger, 
    SelectValue 
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';

/**
 * Dashboard de estatísticas para Contratos de Experiência.
 * 
 * Estrutura da API (/contrato/colaboradores/estatisticas):
 * {
 *   experiencia: { a_vencer_15_dias_total, a_vencer_15_dias_detalhado, vencidos_total, vencidos_detalhado }
 *   prorrogacao:  { a_vencer_15_dias_total, a_vencer_15_dias_detalhado, vencidos_total, vencidos_detalhado }
 *   resumo: { total_contratos, por_empresa: [{empresa, total}], por_status: [{global_status, total}] }
 * }
 */
export const ExperienceContractDashboard = ({ stats, fetchStatistics, filters, setFilters }) => {

    useEffect(() => {
        fetchStatistics(filters.empresa);
    }, [filters.empresa, fetchStatistics]);

    // Desestrutura a resposta da API
    const experiencia = stats?.experiencia || {};
    const prorrogacao = stats?.prorrogacao || {};
    const resumo = stats?.resumo || {};

    const metricCards = [
        {
            label: 'Total de Contratos',
            value: resumo.total_contratos ?? 0,
            icon: Users,
            color: 'bg-indigo-500/10 text-indigo-500',
            borderColor: 'border-indigo-500/20'
        },
        {
            label: 'Exp. a Vencer (15 dias)',
            value: experiencia.a_vencer_15_dias_total ?? 0,
            icon: Clock,
            color: 'bg-amber-500/10 text-amber-500',
            borderColor: 'border-amber-500/20'
        },
        {
            label: 'Exp. Vencidas',
            value: experiencia.vencidos_total ?? 0,
            icon: AlertCircle,
            color: 'bg-rose-500/10 text-rose-500',
            borderColor: 'border-rose-500/20'
        },
        {
            label: 'Prorrog. a Vencer (15 dias)',
            value: prorrogacao.a_vencer_15_dias_total ?? 0,
            icon: CalendarCheck,
            color: 'bg-orange-500/10 text-orange-500',
            borderColor: 'border-orange-500/20'
        },
        {
            label: 'Prorrogações Vencidas',
            value: prorrogacao.vencidos_total ?? 0,
            icon: TrendingDown,
            color: 'bg-red-500/10 text-red-500',
            borderColor: 'border-red-500/20'
        }
    ];

    const statusColorMap = {
        'Admissão':       'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300',
        'Experiência':    'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300',
        'Prorrogação':    'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300',
        'Vencimento de Experiência': 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
    };

    /** Tooltip reutilizável com classes Tailwind — adapta-se ao dark mode */
    const ChartTooltip = ({ active, payload, label }) => {
        if (!active || !payload?.length) return null;
        return (
            <div className="bg-white dark:bg-zinc-900 border border-slate-200 dark:border-white/10 rounded-xl px-4 py-2.5 shadow-xl text-xs">
                {label && <p className="font-bold text-slate-700 dark:text-slate-200 mb-1">{label}</p>}
                {payload.map((p, i) => (
                    <p key={i} className="text-slate-500 dark:text-slate-400">
                        Contratos: <span className="font-bold text-slate-800 dark:text-white">{p.value}</span>
                    </p>
                ))}
            </div>
        );
    };

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700 overflow-y-auto h-full pb-8">

            {/* Filtro de Empresa */}
            <div className="flex items-center justify-between flex-wrap gap-4">
                <div className="space-y-1">
                    <h2 className="text-xl font-bold tracking-tight text-slate-800 dark:text-white">Panorama Geral</h2>
                    <p className="text-sm text-slate-500">Métricas de contratos de experiência por empresa</p>
                </div>
                <div className="flex items-center gap-3 bg-white dark:bg-white/2 p-2 rounded-2xl border border-slate-200 dark:border-white/5">
                    <Building2 size={16} className="text-slate-400 ml-2" />
                    <Select 
                        value={filters.empresa || 'all'} 
                        onValueChange={(val) => setFilters({ empresa: val === 'all' ? '' : val })}
                    >
                        <SelectTrigger className="w-[280px] border-none bg-transparent shadow-none focus:ring-0">
                            <SelectValue placeholder="Todas as Empresas" />
                        </SelectTrigger>
                        <SelectContent className="rounded-2xl shadow-2xl border-slate-200 dark:border-white/10">
                            <SelectItem value="all">Todas as Empresas</SelectItem>
                            {(resumo.por_empresa || [])
                                .filter(emp => emp?.empresa)  // garante que não há value vazio
                                .map(emp => (
                                    <SelectItem key={emp.empresa} value={emp.empresa}>{emp.empresa}</SelectItem>
                                ))
                            }
                        </SelectContent>
                    </Select>
                </div>
            </div>

            {/* Cards de Métricas */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
                {metricCards.map((card, idx) => {
                    const Icon = card.icon;
                    return (
                        <Card key={idx} className={`bg-white dark:bg-white/2 border border-slate-200 dark:border-white/5 rounded-3xl overflow-hidden shadow-sm hover:shadow-md transition-all group`}>
                            <CardContent className="p-6">
                                <div className={`w-10 h-10 rounded-2xl ${card.color} flex items-center justify-center mb-4 group-hover:scale-110 transition-transform`}>
                                    <Icon size={18} />
                                </div>
                                <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1 leading-tight">{card.label}</p>
                                <h3 className="text-3xl font-bold text-slate-800 dark:text-white tracking-tighter">
                                    {card.value}
                                </h3>
                            </CardContent>
                        </Card>
                    );
                })}
            </div>

            {/* Linha 2: Gráficos */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

                {/* Gráfico de Barras — Distribuição por Status */}
                <Card className="bg-white dark:bg-white/2 border-slate-200 dark:border-white/5 rounded-3xl shadow-sm">
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-400">Distribuição por Status</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {resumo.por_status?.length ? (
                            <ResponsiveContainer width="100%" height={220}>
                                <BarChart
                                    data={resumo.por_status.map(item => ({
                                        name: item.global_status,
                                        total: item.total
                                    }))}
                                    layout="vertical"
                                    margin={{ top: 0, right: 24, left: 0, bottom: 0 }}
                                >
                                    <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="rgba(148,163,184,0.1)" />
                                    <XAxis type="number" allowDecimals={false} tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false} />
                                    <YAxis
                                        type="category"
                                        dataKey="name"
                                        width={160}
                                        tick={{ fontSize: 10, fontWeight: 700, fill: '#64748b', textTransform: 'uppercase' }}
                                        axisLine={false}
                                        tickLine={false}
                                    />
                                    <Tooltip
                                        content={<ChartTooltip />}
                                        cursor={{ fill: 'rgba(99,102,241,0.06)' }}
                                    />

                                    <Bar dataKey="total" radius={[0, 8, 8, 0]} maxBarSize={28}>
                                        {(resumo.por_status || []).map((item) => {
                                            const colors = {
                                                'Admissão': '#6366f1',
                                                'Experiência': '#f59e0b',
                                                'Vencimento de Experiência': '#f97316',
                                                'Prorrogação': '#10b981'
                                            };
                                            return <Cell key={item.global_status} fill={colors[item.global_status] || '#6366f1'} />;
                                        })}
                                    </Bar>
                                </BarChart>
                            </ResponsiveContainer>
                        ) : (
                            <p className="text-sm text-slate-400 text-center py-10">Nenhum dado disponível</p>
                        )}
                    </CardContent>
                </Card>

                {/* Gráfico de Pizza — Contratos por Empresa */}
                <Card className="bg-white dark:bg-white/2 border-slate-200 dark:border-white/5 rounded-3xl shadow-sm">
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-400">Contratos por Empresa</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {resumo.por_empresa?.filter(e => e?.empresa)?.length ? (
                            <ResponsiveContainer width="100%" height={220}>
                                <PieChart>
                                    <Pie
                                        data={resumo.por_empresa.filter(e => e?.empresa).map(e => ({ name: e.empresa, value: e.total }))}
                                        cx="50%"
                                        cy="45%"
                                        outerRadius={80}
                                        innerRadius={44}
                                        paddingAngle={3}
                                        dataKey="value"
                                    >
                                        {resumo.por_empresa.filter(e => e?.empresa).map((entry, idx) => {
                                            const PIE_COLORS = ['#6366f1', '#f59e0b', '#10b981', '#f97316', '#ec4899', '#14b8a6'];
                                            return <Cell key={entry.empresa} fill={PIE_COLORS[idx % PIE_COLORS.length]} />;
                                        })}
                                    </Pie>
                                    <Tooltip content={<ChartTooltip />} />

                                    <Legend
                                        iconType="circle"
                                        iconSize={8}
                                        formatter={(value) => (
                                            <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: '#64748b' }}>
                                                {value.length > 30 ? value.substring(0, 28) + '…' : value}
                                            </span>
                                        )}
                                    />
                                </PieChart>
                            </ResponsiveContainer>
                        ) : (
                            <p className="text-sm text-slate-400 text-center py-10">Nenhum dado disponível</p>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Linha 3: Vencimentos Críticos de Experiência */}
            {(experiencia.vencidos_detalhado?.length > 0 || experiencia.a_vencer_15_dias_detalhado?.length > 0) && (
                <Card className="bg-white dark:bg-white/2 border-slate-200 dark:border-white/5 rounded-3xl shadow-sm">
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-400 flex items-center gap-2">
                            <AlertTriangle size={16} className="text-rose-500" />
                            Alertas de Vencimento — Experiência
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-2">
                            {[
                                ...(experiencia.vencidos_detalhado || []).map(c => ({ ...c, _tipo: 'vencido' })),
                                ...(experiencia.a_vencer_15_dias_detalhado || []).map(c => ({ ...c, _tipo: 'a_vencer' }))
                            ].map(c => (
                                <div key={c.idcontrato_rh} className={`flex items-center justify-between p-4 rounded-2xl border ${c._tipo === 'vencido' ? 'bg-rose-50 border-rose-200 dark:bg-rose-900/10 dark:border-rose-500/20' : 'bg-amber-50 border-amber-200 dark:bg-amber-900/10 dark:border-amber-500/20'}`}>
                                    <div>
                                        <p className="text-xs font-bold text-slate-700 dark:text-white">
                                            {c.nome_colaborador || `ID #${c.idcolaborador}`} — {c.empresa}
                                        </p>
                                        <p className="text-[11px] text-slate-500">Vencimento: {c.vencimento_exp || '—'} | Admissão: {c.data_admissao || '—'}</p>
                                    </div>
                                    <Badge className={`text-[10px] font-bold uppercase tracking-widest ${c._tipo === 'vencido' ? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300' : 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'}`}>
                                        {c._tipo === 'vencido' ? 'Vencido' : 'A Vencer'}
                                    </Badge>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Linha 4: Vencimentos Críticos de Prorrogação */}
            {(prorrogacao.vencidos_detalhado?.length > 0 || prorrogacao.a_vencer_15_dias_detalhado?.length > 0) && (
                <Card className="bg-white dark:bg-white/2 border-slate-200 dark:border-white/5 rounded-3xl shadow-sm">
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-400 flex items-center gap-2">
                            <AlertTriangle size={16} className="text-orange-500" />
                            Alertas de Vencimento — Prorrogação
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-2">
                            {[
                                ...(prorrogacao.vencidos_detalhado || []).map(c => ({ ...c, _tipo: 'vencido' })),
                                ...(prorrogacao.a_vencer_15_dias_detalhado || []).map(c => ({ ...c, _tipo: 'a_vencer' }))
                            ].map(c => (
                                <div key={c.idcontrato_rh} className={`flex items-center justify-between p-4 rounded-2xl border ${c._tipo === 'vencido' ? 'bg-rose-50 border-rose-200 dark:bg-rose-900/10 dark:border-rose-500/20' : 'bg-amber-50 border-amber-200 dark:bg-amber-900/10 dark:border-amber-500/20'}`}>
                                    <div>
                                        <p className="text-xs font-bold text-slate-700 dark:text-white">
                                            {c.nome_colaborador || `ID #${c.idcolaborador}`} — {c.empresa}
                                        </p>
                                        <p className="text-[11px] text-slate-500">Prorrogação: {c.prorrogacao_exp || '—'} | Admissão: {c.data_admissao || '—'}</p>
                                    </div>
                                    <Badge className={`text-[10px] font-bold uppercase tracking-widest ${c._tipo === 'vencido' ? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300' : 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'}`}>
                                        {c._tipo === 'vencido' ? 'Vencido' : 'A Vencer'}
                                    </Badge>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>
            )}
        </div>
    );
};
