import React, { useMemo } from 'react';
import { 
  Target,
  CheckCircle2,
  AlertCircle,
  TrendingUp,
  TrendingDown,
  BarChart3,
  PieChart,
  Activity,
  Filter,
  Calendar,
  DollarSign,
  ArrowUp,
  ArrowDown
} from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import {
  PieChart as RePieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  AreaChart,
  Area,
  BarChart,
  Bar
} from 'recharts';
import { FinanceiroChartTooltip } from '../../components/FinanceiroChartTooltip';
import { extratoService } from '@/services/extratoService';
import ExcelTable from '../../components/ExcelTable';
import TransactionsByCategoryModal from '../../components/TransactionsByCategoryModal';

import { formatCurrency, parseDateInfo, parseCurrency } from '@/utils/dateUtils';

/**
 * Premium KPI Card com visualização clara
 */
function KPICard({ title, value, subtext, icon, colorClass, highlight, trend, percentual, loading }) {
    const Icon = icon;
    return (
        <Card className="bg-white dark:bg-slate-900/50 border-2 shadow-lg rounded-xl overflow-hidden group hover:scale-[1.02] transition-all">
            <CardContent className="p-[clamp(1rem,1.25vw,1.25rem)]">
                <div className="flex items-start justify-between mb-[clamp(0.5rem,0.6vw,0.625rem)]">
                    <div className="flex-1 min-w-0">
                        <p className="text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-[0.2em] mb-[clamp(0.25rem,0.4vw,0.375rem)]">{title}</p>
                        {loading ? (
                            <div className="h-[clamp(1.5rem,2vw,1.875rem)] w-32 bg-slate-200 dark:bg-slate-700 animate-pulse rounded mt-1" />
                        ) : (
                            <h3 className={cn(
                                "text-[clamp(1.5rem,2vw,1.875rem)] font-semibold tracking-tight mb-[clamp(0.25rem,0.4vw,0.375rem)]",
                                highlight ? 'text-rose-400 dark:text-rose-400' : 'text-slate-900 dark:text-white'
                            )}>{value}</h3>
                        )}
                        <div className="flex items-center gap-[clamp(0.375rem,0.5vw,0.5rem)] mt-[clamp(0.375rem,0.5vw,0.5rem)] flex-wrap">
                            {trend && !loading && (
                                <span className={cn(
                                    "text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold px-[clamp(0.375rem,0.4vw,0.5rem)] py-0.5 rounded shrink-0 flex items-center gap-[clamp(0.25rem,0.3vw,0.375rem)]",
                                    trend === 'up' ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400' : 
                                    trend === 'down' ? 'bg-red-500/10 text-red-600 dark:text-red-400' :
                                    'bg-slate-500/10 text-slate-600 dark:text-slate-400'
                                )}>
                                    {trend === 'up' ? <ArrowUp className="w-[clamp(0.75rem,0.8vw,0.875rem)] h-[clamp(0.75rem,0.8vw,0.875rem)]" /> : trend === 'down' ? <ArrowDown className="w-[clamp(0.75rem,0.8vw,0.875rem)] h-[clamp(0.75rem,0.8vw,0.875rem)]" /> : null}
                                    {percentual && `${percentual > 0 ? '+' : ''}${percentual}%`}
                                </span>
                            )}
                            <p className="text-[clamp(0.625rem,0.8vw,0.75rem)] text-slate-500 dark:text-slate-400 font-medium leading-tight">{subtext}</p>
                        </div>
                    </div>
                    <div className={cn(
                        "w-[clamp(2.5rem,3vw,3rem)] h-[clamp(2.5rem,3vw,3rem)] rounded-xl flex items-center justify-center shrink-0 bg-opacity-10 border border-current border-opacity-20 group-hover:scale-110 transition-transform duration-500 shadow-lg",
                        colorClass
                    )}>
                        <Icon className={cn("w-[clamp(1.25rem,1.5vw,1.5rem)] h-[clamp(1.25rem,1.5vw,1.5rem)]", colorClass.replace('bg-', 'text-'))} />
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}

const MESES = ['', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
const ANOS = Array.from({ length: 11 }, (_, i) => new Date().getFullYear() - 5 + i);

export function CruzamentoDespesasView({ state }) {
    const { despesasPlanejadas = [], despesasExecutadas = [], caixinhas = [] } = state;

    const [filtroTipo, setFiltroTipo] = React.useState('mes'); // 'mes' | 'ano'
    const [filtroMes, setFiltroMes] = React.useState(new Date().getMonth() + 1);
    const [filtroAno, setFiltroAno] = React.useState(new Date().getFullYear());
    const [filtroCaixinha, setFiltroCaixinha] = React.useState('todos');

    const [somaCategorias, setSomaCategorias] = React.useState([]);
    const [isLoadingSoma, setIsLoadingSoma] = React.useState(false);

    // Mapeamento removido pois agora usamos os nomes da API de somaCategorias

    const [chartDataBackend, setChartDataBackend] = React.useState([]);
    const [isLoadingChart, setIsLoadingChart] = React.useState(false);

    const [totaisDespesas, setTotaisDespesas] = React.useState({
        total_planejado: 0,
        total_executado: 0,
        total_geral: 0,
        diferenca: 0,
        taxa_realizacao: 0,
        classificacao: '',
        cor: ''
    });
    const [isLoadingTotais, setIsLoadingTotais] = React.useState(false);

    const [selectedCategory, setSelectedCategory] = React.useState(null);
    const [isModalOpen, setIsModalOpen] = React.useState(false);

    // Efeito para buscar totais planejados do mês vigente
    React.useEffect(() => {
        const fetchTotais = async () => {
            if (filtroTipo !== 'mes') return;
            
            setIsLoadingTotais(true);
            try {
                const result = await extratoService.fetchDespesasResumo({
                    mes: filtroMes,
                    ano: filtroAno
                });
                
                if (result) {
                    setTotaisDespesas(result);
                }
            } catch (err) {
                console.error('[CruzamentoDespesasView] Erro ao buscar totais:', err);
            } finally {
                setIsLoadingTotais(false);
            }
        };

        fetchTotais();
    }, [filtroMes, filtroAno, filtroTipo]);

    // Efeito para buscar dados do gráfico do backend

    React.useEffect(() => {
        const fetchChartData = async () => {
            setIsLoadingChart(true);
            try {
                const params = {
                    ano: filtroAno
                };
                if (filtroTipo === 'mes') {
                    params.mes = filtroMes;
                }
                const result = await extratoService.fetchDespesasGrafico(params);
                const data = result?.grafico ?? result ?? [];
                setChartDataBackend(Array.isArray(data) ? data : []);
            } catch (err) {
                console.error('[CruzamentoDespesasView] Erro ao buscar dados do gráfico:', err);
                setChartDataBackend([]);
            } finally {
                setIsLoadingChart(false);
            }
        };

        fetchChartData();
    }, [filtroMes, filtroAno, filtroTipo]);

    // Efeito para buscar soma por categoria do backend
    React.useEffect(() => {
        const fetchSoma = async () => {
            setIsLoadingSoma(true);
            try {
                const result = await extratoService.getSomaPorCategoria({
                    mes: filtroMes,
                    ano: filtroAno,
                    tipoOperacao: 'D' // Despesas
                });
                
                // Normaliza o resultado conforme o backend (esperado array de objetos)
                // O backend para despesas v2 retorna { ano, mes, por_categoria }
                const data = result?.por_categoria ?? result?.dados ?? result?.Base_Dados_API ?? (Array.isArray(result) ? result : []);
                console.log('[CruzamentoDespesasView] somaCategorias carregadas:', data.length, 'itens');
                if (data.length > 0) {
                    console.log('[CruzamentoDespesasView] Exemplo soma:', data[0]);
                }
                setSomaCategorias(Array.isArray(data) ? data : []);
            } catch (err) {
                console.error('[CruzamentoDespesasView] Erro ao buscar soma por categoria:', err);
                setSomaCategorias([]);
            } finally {
                setIsLoadingSoma(false);
            }
        };

        if (filtroTipo === 'mes' && filtroMes && filtroAno) {
            fetchSoma();
        } else {
            setSomaCategorias([]);
        }
    }, [filtroMes, filtroAno, filtroTipo]);

    // Efeito para buscar transações detalhadas do período removido pois soma_por_categoria já traz os itens.

    // Mapeamento removido pois agora usamos os nomes da API de somaCategorias



    const matchPeriod = (dataStr) => {
        const { year, month } = parseDateInfo(dataStr);
        const y = Number(year);
        const m = Number(month);
        const fAno = Number(filtroAno);
        const fMes = Number(filtroMes);

        if (filtroTipo === 'ano') return y === fAno;
        return y === fAno && m === fMes;
    };

    const filteredPlanejadas = useMemo(() => {
        return despesasPlanejadas.filter(item => {
            if (!matchPeriod(item.data || item.dataEntrada)) return false;
            if (filtroCaixinha !== 'todos' && String(item.caixinha || '') !== String(filtroCaixinha)) return false;
            return true;
        });
    }, [despesasPlanejadas, filtroTipo, filtroMes, filtroAno, filtroCaixinha]);

    const filteredExecutadas = useMemo(() => {
        const allTrans = somaCategorias.flatMap(c => c.transacoes || []);
        const sourceData = (filtroTipo === 'mes' && allTrans.length > 0) ? allTrans : (Array.isArray(despesasExecutadas) ? despesasExecutadas : []);

        console.log('[CruzamentoDespesasView] Pipeline de dados para filteredExecutadas:', {
            filtroTipo,
            sourceCount: sourceData.length,
            propCount: despesasExecutadas?.length,
            somaTransCount: allTrans.length
        });
        
        return sourceData.filter(item => {
            if (!matchPeriod(item.data || item.dataEntrada)) return false;
            
            // Garantir que estamos vendo apenas Despesas (D)
            const op = String(item.tipoOperacao || '').toUpperCase();
            if (op && op !== 'D') return false;

            if (filtroCaixinha !== 'todos' && String(item.caixinha || '') !== String(filtroCaixinha)) return false;
            return true;
        });
    }, [despesasExecutadas, somaCategorias, filtroTipo, filtroMes, filtroAno, filtroCaixinha]);

    // Composição e Variância baseadas exclusivamente na rota de soma por categoria
    const comparativoCategoria = useMemo(() => {
        if (!Array.isArray(somaCategorias)) return [];
        
        return somaCategorias.map(item => {
            const saidas = parseCurrency(item.total || item.total_saidas || 0);
            return {
                id: item.idcategoria ?? item.idCategoria ?? item.id,
                categoria: item.categoria || 'Sem Categoria',
                categoriaNome: item.categoria || '(Sem Categoria)',
                name: item.categoria || '(Sem Categoria)',
                entradas: 0,
                saidas,
                diferenca: 0,
                percentual: 0,
                executado: Math.abs(saidas),
                value: Math.abs(saidas)
            };
        }).sort((a, b) => b.saidas - a.saidas);
    }, [somaCategorias]);


    const handleCategoryClick = (name, id) => {
        console.log('[CruzamentoDespesasView] Clicou na categoria:', { name, id });
        setSelectedCategory({ name, id });
        setIsModalOpen(true);
    };

    const transactionsForSelectedCategory = React.useMemo(() => {
        if (!selectedCategory) return [];
        
        // Busca direta no agrupamento do backend
        const catObj = somaCategorias.find(c => {
            const id = c.idcategoria ?? c.idCategoria ?? c.id;
            const name = c.categoria || '';
            return String(id) === String(selectedCategory.id) || name === selectedCategory.name;
        });

        const transactions = catObj?.transacoes || [];
        console.log('[CruzamentoDespesasView] Modal: itens para', selectedCategory.name, ':', transactions.length);
        return transactions;
    }, [selectedCategory, somaCategorias]);

    const timelineData = useMemo(() => {
        if (chartDataBackend.length > 0) {
            return chartDataBackend.map(item => {
                const variacao = (item.executado || 0) - (item.planejado || 0);
                const percentual = (item.planejado || 0) > 0 ? (((item.executado || 0) / item.planejado) * 100).toFixed(1) : 0;
                
                // Formata o nome do período para exibição
                let name = String(item.periodo);
                if (filtroTipo === 'ano') {
                    const mesesLabel = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
                    const mesIdx = parseInt(item.periodo) - 1;
                    if (mesIdx >= 0 && mesIdx < 12) name = mesesLabel[mesIdx];
                } else if (filtroTipo === 'mes') {
                    name = `${String(item.periodo).padStart(2, '0')}/${String(filtroMes).padStart(2, '0')}`;
                }

                return { 
                    ...item, 
                    name,
                    variacao, 
                    percentual,
                    value: item.executado
                };
            });
        }

        const mesesLabel = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
        
        if (filtroTipo === 'ano') {
            const map = {};
            mesesLabel.forEach((_, i) => {
                const key = String(i + 1).padStart(2, '0');
                map[key] = { planejado: 0, executado: 0 };
            });

            filteredPlanejadas.forEach(item => {
                const { year, month } = parseDateInfo(item.data || item.dataEntrada);
                if (year === Number(filtroAno)) {
                    const key = String(month).padStart(2, '0');
                    if (map[key]) map[key].planejado += Number(item.valor || 0);
                }
            });

            filteredExecutadas.forEach(item => {
                const { year, month } = parseDateInfo(item.data || item.dataEntrada);
                if (year === Number(filtroAno)) {
                    const key = String(month).padStart(2, '0');
                    if (map[key]) map[key].executado += Number(item.valor || 0);
                }
            });

            return mesesLabel.map((name, i) => {
                const key = String(i + 1).padStart(2, '0');
                const values = map[key];
                return { name, ...values, value: values.executado };
            });
        }

        const map = {};
        // Para visão mensal/diária -> Mostrar Dia/Mês
        filteredPlanejadas.forEach(item => {
            const { month, year, day } = parseDateInfo(item.data || item.dataEntrada);
            if (month && year) {
                const dateKey = `${year}-${String(month).padStart(2, '0')}${day ? '-' + String(day).padStart(2, '0') : ''}`;
                const label = day ? `${String(day).padStart(2, '0')}/${String(month).padStart(2, '0')}` : `${String(month).padStart(2, '0')}/${year}`;
                if (!map[dateKey]) map[dateKey] = { name: label, planejado: 0, executado: 0 };
                map[dateKey].planejado += Number(item.valor || 0);
            }
        });

        filteredExecutadas.forEach(item => {
            const { month, year, day } = parseDateInfo(item.data || item.dataEntrada);
            if (month && year) {
                const dateKey = `${year}-${String(month).padStart(2, '0')}${day ? '-' + String(day).padStart(2, '0') : ''}`;
                const label = day ? `${String(day).padStart(2, '0')}/${String(month).padStart(2, '0')}` : `${String(month).padStart(2, '0')}/${year}`;
                if (!map[dateKey]) map[dateKey] = { name: label, planejado: 0, executado: 0 };
                map[dateKey].executado += Number(item.valor || 0);
            }
        });

        return Object.entries(map)
            .sort((a, b) => a[0].localeCompare(b[0]))
            .map(([key, values]) => ({ ...values, value: values.executado }));
    }, [filteredPlanejadas, filteredExecutadas, filtroTipo, filtroAno, chartDataBackend, filtroMes]);

    const categoriaData = useMemo(() => {
        return comparativoCategoria.map((item) => ({
            name: item.categoriaNome,
            value: item.executado
        })).filter((d) => d.value > 0);
    }, [comparativoCategoria]);

    const kpisCruzamento = useMemo(() => {
        if (filtroTipo === 'mes' && totaisDespesas) {
            const totalPlanejado = totaisDespesas.total_planejado || 0;
            const totalExecutado = totaisDespesas.total_executado || 0;
            const variacao = totaisDespesas.diferenca || 0;
            const percentualVariacao = totaisDespesas.taxa_realizacao || 0;
            const totalVolume = totaisDespesas.total_geral || (totalPlanejado + totalExecutado);
            const classificacao = totaisDespesas.classificacao || '';
            
            // Mapeamento de cores do back para Tailwind
            const colorMap = {
                'verde': 'text-emerald-500',
                'azul': 'text-blue-500',
                'amarelo': 'text-amber-500',
                'vermelho': 'text-rose-500'
            };
            const corDinamica = colorMap[totaisDespesas.cor] || 'text-blue-500';

            return { totalPlanejado, totalExecutado, variacao, percentualVariacao, totalVolume, classificacao, corDinamica };
        }

        const totalPlanejado = filteredPlanejadas.reduce((acc, item) => acc + (item.valor || 0), 0);
        const totalExecutado = filteredExecutadas.reduce((acc, item) => acc + (item.valor || 0), 0);
        const variacao = totalExecutado - totalPlanejado;
        const percentualVariacao = totalPlanejado > 0 ? ((totalExecutado / totalPlanejado) * 100).toFixed(1) : 0;
        return { 
            totalPlanejado, 
            totalExecutado, 
            variacao, 
            percentualVariacao, 
            totalVolume: totalPlanejado + totalExecutado,
            classificacao: '',
            corDinamica: 'text-blue-500' 
        };
    }, [filteredPlanejadas, filteredExecutadas, filtroTipo, totaisDespesas]);

    const COLORS = ['#ef4444', '#f97316', '#f59e0b', '#8b5cf6', '#64748b', '#10b981'];

    const totalPlanejado = kpisCruzamento.totalPlanejado || 0;
    const totalExecutado = kpisCruzamento.totalExecutado || 0;
    const variacao = kpisCruzamento.variacao || 0;
    const percentualVariacao = kpisCruzamento.percentualVariacao ?? 0;
    const totalVolume = kpisCruzamento.totalVolume || 0;
    const classificacao = kpisCruzamento.classificacao;
    const corDinamica = kpisCruzamento.corDinamica;
    const temPlanejado = totalPlanejado > 0;

    return (
        <div className="space-y-4 sm:space-y-6 relative pb-6 sm:pb-10">
            {/* Abstract Background Elements */}
            <div className="absolute top-0 left-1/2 -translate-x-1/2 w-full max-w-4xl h-full pointer-events-none overflow-hidden opacity-10 dark:opacity-20">
                <div className="absolute top-20 right-0 w-96 h-96 bg-rose-500/10 rounded-full blur-3xl" />
                <div className="absolute bottom-40 left-0 w-[500px] h-[500px] bg-red-500/5 rounded-full blur-3xl" />
            </div>

            {/* Filter & Summary Bar */}
            <div className="bg-white/80 dark:bg-slate-900/60 backdrop-blur-xl p-[clamp(0.75rem,1.2vw,1.25rem)] rounded-xl sm:rounded-2xl border border-slate-200 dark:border-slate-800/50 flex flex-col sm:flex-row flex-wrap gap-[clamp(0.75rem,1vw,1rem)] items-stretch sm:items-center shadow-xl dark:shadow-2xl relative z-10">
                <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-2 flex-1 min-w-0 flex-wrap">
                    <div className="p-[clamp(0.5rem,0.6vw,0.625rem)] bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-800 shrink-0">
                        <Filter className="w-[clamp(0.875rem,1vw,1rem)] h-[clamp(0.875rem,1vw,1rem)] text-rose-500 dark:text-rose-400" />
                    </div>
                    <Select value={filtroTipo} onValueChange={setFiltroTipo}>
                        <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[110px] bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-700 dark:text-white">
                            <SelectValue placeholder="Período" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="mes">Mês</SelectItem>
                            <SelectItem value="ano">Ano</SelectItem>
                        </SelectContent>
                    </Select>
                    {filtroTipo === 'mes' && (
                        <Select value={String(filtroMes)} onValueChange={(v) => setFiltroMes(Number(v))}>
                            <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[130px] bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-700 dark:text-white">
                                <SelectValue placeholder="Mês" />
                            </SelectTrigger>
                            <SelectContent>
                                {MESES.map((m, i) => (i === 0 ? null : <SelectItem key={i} value={String(i)}>{m}</SelectItem>))}
                            </SelectContent>
                        </Select>
                    )}
                    <Select value={String(filtroAno)} onValueChange={(v) => setFiltroAno(Number(v))}>
                        <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[100px] bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-700 dark:text-white">
                            <SelectValue placeholder="Ano" />
                        </SelectTrigger>
                        <SelectContent>
                            {ANOS.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                        </SelectContent>
                    </Select>
                    <Select value={filtroCaixinha} onValueChange={setFiltroCaixinha}>
                        <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[160px] bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-700 dark:text-white">
                            <SelectValue placeholder="Caixinha" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="todos">Todas</SelectItem>
                            {(caixinhas || []).map((c) => (
                                <SelectItem key={c.idcaixinhas_financeiro ?? c.id} value={String(c.idcaixinhas_financeiro ?? c.id ?? '')}>
                                    {c.caixinha ?? c.name ?? 'N/D'}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                    <Badge variant="outline" className="h-[clamp(2rem,2.2vw,2.25rem)] px-[clamp(0.75rem,1vw,1rem)] rounded-lg sm:rounded-xl bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-slate-500 dark:text-slate-400 text-[clamp(0.75rem,0.8vw,0.8125rem)] whitespace-nowrap self-center font-medium">
                        {filtroTipo === 'mes' ? `${MESES[filtroMes]} / ${filtroAno}` : filtroAno}
                    </Badge>
                </div>

                {/* Segunda Linha: Performance */}
                <div className="flex items-center justify-between sm:justify-end gap-[clamp(0.75rem,1vw,1rem)] sm:ml-auto">
                    <div className="text-right">
                        <p className="text-[clamp(0.5625rem,0.7vw,0.625rem)] font-semibold text-slate-500 uppercase tracking-widest">Performance</p>
                        <p className={cn(
                            "text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold",
                            temPlanejado && percentualVariacao >= 100 ? "text-emerald-500" : "text-rose-500"
                        )}>
                            {temPlanejado ? `${percentualVariacao >= 100 ? '+' : ''}${Number(percentualVariacao).toFixed(1)}% vs planejado` : 'Sem planejado'}
                        </p>
                    </div>
                    <div className="w-[clamp(2rem,2.5vw,2.5rem)] h-[clamp(2rem,2.5vw,2.5rem)] rounded-full border-2 border-rose-500/20 border-t-rose-500 animate-spin-slow flex items-center justify-center shrink-0">
                        <Target className="w-[clamp(0.875rem,1.1vw,1.125rem)] h-[clamp(0.875rem,1.1vw,1.125rem)] text-rose-500" />
                    </div>
                </div>
            </div>

            {/* KPIs - Primeira Linha: APENAS Total Executado alimentado */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 gap-3 sm:gap-4 md:gap-6 relative z-10">
                <KPICard 
                    title="Total Planejado"
                    value={formatCurrency(totalPlanejado)}
                    subtext="Total esperado"
                    icon={Target}
                    colorClass="text-slate-500"
                    loading={isLoadingTotais}
                />
                <KPICard 
                    title="Total Executado"
                    value={formatCurrency(totalExecutado)}
                    subtext="Total realizado"
                    icon={CheckCircle2}
                    colorClass="text-rose-500"
                    highlight
                    loading={isLoadingTotais}
                />

            </div>

            {/* KPIs de Variância */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 gap-3 sm:gap-4 md:gap-6 relative z-10">
                <KPICard 
                    title="Variação"
                    value={formatCurrency(variacao)}
                    subtext={variacao >= 0 ? "Fora do planejado" : "Dentro do planejado"}
                    icon={BarChart3}
                    trend={variacao > 0 ? 'down' : 'up'}
                    colorClass={variacao > 0 ? "text-rose-500" : "text-emerald-500"}
                    loading={isLoadingTotais}
                />
                <KPICard 
                    title="Percentual de diferença"
                    value={`${percentualVariacao}%`}
                    subtext={classificacao || "Percentual do planejado executado"}
                    icon={Activity}
                    colorClass={corDinamica}
                    loading={isLoadingTotais}
                />
            </div>

            {/* Gráfico Comparativo Planejado vs Executado */}
            <Card className="bg-white dark:bg-slate-900/50 backdrop-blur-md border border-slate-200 dark:border-slate-800/50 shadow-xl dark:shadow-2xl overflow-hidden group relative z-10">
                <CardHeader className="p-[clamp(1rem,1.5vw,1.5rem)] border-b border-white/5 bg-white/5">
                    <CardTitle className="text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold text-slate-400 uppercase tracking-[0.2em] flex items-center gap-[clamp(0.5rem,0.6vw,0.75rem)]">
                        <div className="w-[clamp(1.5rem,1.8vw,1.75rem)] h-[clamp(1.5rem,1.8vw,1.75rem)] rounded-lg bg-purple-500/10 flex items-center justify-center border border-purple-500/20 shrink-0">
                            <BarChart3 className="w-[clamp(0.875rem,1vw,1rem)] h-[clamp(0.875rem,1vw,1rem)] text-purple-500" />
                        </div>
                        <span className="truncate">Planejado vs Executado</span>
                    </CardTitle>
                </CardHeader>
                <CardContent className="p-0 pr-[clamp(0.75rem,1.5vw,1.5rem)] pt-[clamp(1.5rem,2.5vh,2.5rem)]" style={{ height: '400px', minHeight: '400px' }}>
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={timelineData}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#334155" opacity={0.2} />
                            <XAxis 
                                dataKey="name" 
                                axisLine={false} 
                                tickLine={false} 
                                tick={{fill: '#64748b', fontSize: 10, fontWeight: '500'}} 
                                dy={10} 
                            />
                            <YAxis 
                                axisLine={false} 
                                tickLine={false} 
                                tick={{fill: '#64748b', fontSize: 10}} 
                                tickFormatter={(val) => `R$ ${val/1000}k`} 
                            />
                            <Tooltip 
                                cursor={{ fill: 'rgba(0,0,0,0.05)', opacity: 0.1 }}
                                content={<FinanceiroChartTooltip formatCurrency={formatCurrency} />}
                            />
                            <Legend 
                                formatter={(value) => <span className="text-[clamp(0.625rem,0.7vw,0.75rem)] uppercase font-semibold text-slate-400">{value}</span>}
                            />
                            <Bar dataKey="planejado" fill="#3b82f6" radius={[4, 4, 0, 0]} name="Planejado" />
                            <Bar dataKey="executado" fill="#ef4444" radius={[4, 4, 0, 0]} name="Executado" />
                        </BarChart>
                    </ResponsiveContainer>
                </CardContent>
            </Card>

            {/* Charts Grid */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-[clamp(1rem,1.5vw,1.5rem)] relative z-10">
                {/* Category Chart */}
                {/* Category Chart */}
                <Card className="bg-white dark:bg-slate-900/50 backdrop-blur-md border border-slate-200 dark:border-slate-800/50 shadow-xl dark:shadow-2xl overflow-hidden group">
                    <CardHeader className="p-[clamp(1rem,1.5vw,1.5rem)] border-b border-white/5 bg-white/5">
                        <CardTitle className="text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold text-slate-400 uppercase tracking-[0.2em] flex items-center gap-[clamp(0.5rem,0.6vw,0.75rem)]">
                            <div className="w-[clamp(1.5rem,1.8vw,1.75rem)] h-[clamp(1.5rem,1.8vw,1.75rem)] rounded-lg bg-rose-500/10 flex items-center justify-center border border-rose-500/20 shrink-0">
                                <PieChart className="w-[clamp(0.875rem,1vw,1rem)] h-[clamp(0.875rem,1vw,1rem)] text-rose-500" />
                            </div>
                            <span className="truncate">Composição de Despesas</span>
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-0" style={{ height: '350px', minHeight: '350px' }}>
                        <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                            <RePieChart>
                                <Pie
                                    data={categoriaData}
                                    cx="50%"
                                    cy="50%"
                                    innerRadius={85}
                                    outerRadius={115}
                                    paddingAngle={10}
                                    dataKey="value"
                                    nameKey="name"
                                    stroke="none"
                                >
                                    {categoriaData.map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                    ))}
                                </Pie>
                                <Tooltip content={<FinanceiroChartTooltip formatCurrency={formatCurrency} />} />
                                <Legend 
                                    verticalAlign="bottom" 
                                    height={40} 
                                    iconType="circle" 
                                    formatter={(value) => <span className="text-[10px] uppercase font-bold text-slate-400">{value}</span>}
                                />
                                </RePieChart>
                            </ResponsiveContainer>
                    </CardContent>
                </Card>

                {/* Timeline Chart */}
                {/* Timeline Chart */}
                <Card className="bg-white dark:bg-slate-900/50 backdrop-blur-md border border-slate-200 dark:border-slate-800/50 shadow-xl dark:shadow-2xl overflow-hidden group">
                    <CardHeader className="p-[clamp(1rem,1.5vw,1.5rem)] border-b border-white/5 bg-white/5">
                        <CardTitle className="text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold text-slate-400 uppercase tracking-[0.2em] flex items-center gap-[clamp(0.5rem,0.6vw,0.75rem)]">
                            <div className="w-[clamp(1.5rem,1.8vw,1.75rem)] h-[clamp(1.5rem,1.8vw,1.75rem)] rounded-lg bg-blue-500/10 flex items-center justify-center border border-blue-500/20 shrink-0">
                                <Activity className="w-[clamp(0.875rem,1vw,1rem)] h-[clamp(0.875rem,1vw,1rem)] text-blue-500" />
                            </div>
                            <span className="truncate">Fluxo de Despesas</span>
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="h-[280px] sm:h-[320px] md:h-[380px] p-4 sm:p-6 pt-6 sm:pt-10">
                        {comparativoCategoria.length === 0 ? (
                            <div className="flex items-center justify-center h-full text-slate-500">
                                <p>Nenhum dado disponível para o período selecionado</p>
                            </div>
                        ) : (
                            <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                                <AreaChart data={timelineData}>
                                <defs>
                                    <linearGradient id="colorWaveDesp" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%" stopColor="#ef4444" stopOpacity={0.4}/>
                                        <stop offset="95%" stopColor="#ef4444" stopOpacity={0}/>
                                    </linearGradient>
                                </defs>
                                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#334155" opacity={0.2} />
                                <XAxis 
                                    dataKey="name" 
                                    axisLine={false} 
                                    tickLine={false} 
                                    tick={{fill: '#64748b', fontSize: 10, fontWeight: '500'}} 
                                    dy={10} 
                                />
                                <YAxis 
                                    axisLine={false} 
                                    tickLine={false} 
                                    tick={{fill: '#64748b', fontSize: 10}} 
                                    tickFormatter={(val) => `R$ ${val/1000}k`} 
                                />
                                <Tooltip content={<FinanceiroChartTooltip formatCurrency={formatCurrency} />} />
                                <Legend 
                                    formatter={(value) => <span className="text-[10px] uppercase font-bold text-slate-400">{value}</span>}
                                />
                                <Area 
                                    type="monotone" 
                                    dataKey="executado" 
                                    stroke="#ef4444" 
                                    strokeWidth={3}
                                    fillOpacity={1} 
                                    fill="url(#colorWaveDesp)" 
                                    name="Executado"
                                />
                            </AreaChart>
                        </ResponsiveContainer>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Tabela de Análise de Variância por Categoria */}
            {/* Tabela de Análise de Variância por Categoria */}
            <Card className="bg-white dark:bg-slate-900/50 backdrop-blur-md border border-slate-200 dark:border-slate-800/50 shadow-xl dark:shadow-2xl overflow-hidden relative z-10">
                <CardHeader className="p-[clamp(1rem,1.5vw,1.5rem)] border-b border-white/5 bg-white/5">
                    <CardTitle className="text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold text-slate-400 uppercase tracking-[0.2em] flex items-center gap-[clamp(0.5rem,0.6vw,0.75rem)]">
                        <div className="w-[clamp(1.5rem,1.8vw,1.75rem)] h-[clamp(1.5rem,1.8vw,1.75rem)] rounded-lg bg-amber-500/10 flex items-center justify-center border border-amber-500/20 shrink-0">
                            <TrendingUp className="w-[clamp(0.875rem,1vw,1rem)] h-[clamp(0.875rem,1vw,1rem)] text-amber-500" />
                        </div>
                        <span className="truncate">Análise de Variância por Categoria</span>
                    </CardTitle>
                </CardHeader>
                <CardContent className="p-0">
                    <div className="overflow-x-auto -mx-1 sm:mx-0">
                        <div className="h-[clamp(25rem,50vh,30rem)]">
                            <ExcelTable
                                data={comparativoCategoria}
                                columns={[
                                    { 
                                        field: 'categoriaNome', 
                                        header: 'Categoria', 
                                        width: '200px',
                                        render: (row) => (
                                            <button 
                                                onClick={() => handleCategoryClick(row.categoria, row.id)}
                                                className="font-semibold text-slate-900 dark:text-white pl-3 hover:text-rose-500 transition-colors text-left w-full"
                                            >
                                                {row.categoriaNome}
                                            </button>
                                        )
                                    },
                                    { 
                                        field: 'saidas', 
                                        header: 'Saídas', 
                                        width: '150px',
                                        render: (row) => (
                                            <span className="font-mono text-xs text-rose-400 text-right block w-full">
                                                {formatCurrency(row.saidas)}
                                            </span>
                                        )
                                    },
                                    { 
                                        field: 'diferenca', 
                                        header: 'Diferença', 
                                        width: '150px',
                                        render: (row) => (
                                            <span className={cn(
                                                "font-mono text-xs font-bold text-right block w-full",
                                                row.diferenca >= 0 ? "text-emerald-400" : "text-red-400"
                                            )}>
                                                {row.diferenca >= 0 ? '+' : ''}{formatCurrency(row.diferenca)}
                                            </span>
                                        )
                                    },
                                    { 
                                        field: 'percentual', 
                                        header: '% Saída', 
                                        width: '120px',
                                        render: (row) => (
                                            <div className="flex justify-end pr-3">
                                                <Badge className={cn(
                                                    "text-[9px] font-semibold",
                                                    parseFloat(row.percentual) >= 50 
                                                        ? "bg-rose-500/10 text-rose-500 border-rose-500/20"
                                                        : "bg-slate-500/10 text-slate-500 border-slate-500/20"
                                                )}>
                                                    {row.percentual}%
                                                </Badge>
                                            </div>
                                        )
                                    }
                                ]}
                                rowKey="categoria"
                                pageSize={10}
                            />
                        </div>
                    </div>
                </CardContent>
            </Card>

            <TransactionsByCategoryModal 
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                categoryName={selectedCategory?.name}
                transactions={transactionsForSelectedCategory}
            />
        </div>
    );
};

