import React, { useMemo } from 'react';
import { 
  ArrowUp, 
  ArrowDown, 
  DollarSign,
  PieChart,
  Activity,
  Calendar,
  Filter,
  TrendingUp,
  Target,
  CheckCircle2,
  Clock,
  BarChart3,
  TrendingDown
} from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import ExcelTable from '../../components/ExcelTable';
import TransactionsByCategoryModal from '../../components/TransactionsByCategoryModal';

import { extratoService } from '@/services/extratoService';
import { cn } from '@/lib/utils';
import {
  PieChart as RePieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  Legend,
  AreaChart,
  Area,
  BarChart,
  Bar,
  Tooltip
} from 'recharts';
import { FinanceiroChartTooltip } from '../../components/FinanceiroChartTooltip';
import { formatCurrency, parseDateInfo, parseCurrency } from '@/utils/dateUtils';

/**
 * Premium KPI Card with Glow and Glassmorphism
 */
function KPICard({ title, value, subtext, icon, colorClass, highlight, trend, loading }) {
    const Icon = icon;
    return (
        <Card className="bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl relative overflow-hidden group hover:border-slate-300 dark:hover:border-slate-700/50 transition-all duration-500">
            {/* Animated Glow Effect */}
            <div className={`absolute -right-8 -bottom-8 w-[clamp(6rem,10vw,8rem)] h-[clamp(6rem,10vw,8rem)] rounded-full opacity-0 group-hover:opacity-10 transition-opacity duration-700 blur-2xl ${highlight ? 'bg-emerald-500' : 'bg-blue-500'}`} />
            
            <CardContent className="p-[clamp(0.75rem,1.2vw,1.25rem)] flex items-start justify-between relative z-10">
                <div className="flex-1 min-w-0">
                    <p className="text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold text-slate-500 uppercase tracking-[0.2em] mb-[clamp(0.25rem,0.4vw,0.375rem)]">{title}</p>
                    {loading ? (
                        <div className="h-[clamp(1.25rem,2vw,1.875rem)] w-32 bg-slate-200 dark:bg-slate-700 animate-pulse rounded mt-1" />
                    ) : (
                        <h3 className={`text-[clamp(1.25rem,2vw,1.875rem)] font-semibold tracking-tight ${highlight ? 'text-emerald-600 dark:text-emerald-400' : 'text-slate-900 dark:text-white'} leading-tight`}>{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={`text-[clamp(0.625rem,0.7vw,0.75rem)] font-semibold px-[clamp(0.375rem,0.4vw,0.5rem)] py-0.5 rounded shrink-0 ${trend === 'up' ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400' : 'bg-red-500/10 text-red-600 dark:text-red-400'}`}>
                                {trend === 'up' ? '+' : '-'}
                                {trend === 'up' ? 'Acima' : 'Abaixo'}
                            </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={`w-[clamp(2.5rem,3vw,3rem)] h-[clamp(2.5rem,3vw,3rem)] rounded-xl flex items-center justify-center ${colorClass} bg-opacity-10 border border-current border-opacity-20 group-hover:scale-110 transition-transform duration-500 shadow-lg shrink-0`}>
                    <Icon className={`w-[clamp(1.25rem,1.5vw,1.5rem)] h-[clamp(1.25rem,1.5vw,1.5rem)] ${colorClass.replace('bg-', 'text-')}`} />
                </div>
            </CardContent>
        </Card>
    );
}

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

export function CruzamentoView({ data = [], kpis = {}, caixas = [], entradasPlanejadas = [], categorias = [] }) {
    const [filtroMes, setFiltroMes] = React.useState(String(new Date().getMonth() + 1));
    const [filtroAno, setFiltroAno] = React.useState(new Date().getFullYear().toString());
    const [filtroCaixa, setFiltroCaixa] = React.useState('todos');
    const [filtroTipo, setFiltroTipo] = React.useState('mes'); // 'mes' | 'ano' | 'todos'

    // Novos estados para os totais do backend
    const [totaisPlanejados, setTotaisPlanejados] = React.useState({
        total_planejado: 0,
        total_boletos_a_receber: 0,
        total_planejado_geral: 0,
        total_realizado: 0,
        diferenca: 0
    });
    const [isLoadingTotais, setIsLoadingTotais] = React.useState(false);

    const [somaCategorias, setSomaCategorias] = React.useState([]);
    const [isLoadingSoma, setIsLoadingSoma] = React.useState(false);
    
    // Mapeamento removido pois agora usamos os nomes da API de somaCategorias

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

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

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

    const dadosFiltrados = React.useMemo(() => {
        // Agora usamos os dados brutos de transações agrupadas de somaCategorias para filtros globais se necessário,
        // mas para o CruzamentoView, o dadosFiltrados costuma vir da prop 'data'.
        // Se quisermos que o dadosFiltrados reflita o que o backend agrupou:
        const allTrans = somaCategorias.flatMap(c => c.transacoes || []);
        const sourceData = (filtroTipo === 'mes' && allTrans.length > 0) ? allTrans : (Array.isArray(data) ? data : []);
        
        console.log('[CruzamentoView] Pipeline de dados:', {
            filtroTipo,
            sourceCount: sourceData.length,
            propCount: data?.length,
            somaTransCount: allTrans.length
        });

        return sourceData.filter(item => {
            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;
                if (filtroTipo === 'mes') return y === fAno && m === fMes;
                return true;
            };

            // Apply period filter
            if (!matchPeriod(item?.dataEntrada || item?.data || '')) return false;
            
            // Garantir que estamos vendo apenas Receitas (C)
            const op = String(item.tipoOperacao || '').toUpperCase();
            if (op && op !== 'C') return false;

            if (filtroCaixa !== 'todos' && item?.caixinha != null && String(item.caixinha) !== String(filtroCaixa)) return false;
            return true;
        });
    }, [data, somaCategorias, filtroMes, filtroAno, filtroCaixa, filtroTipo]);

    const planejadasFiltradas = React.useMemo(() => {
        if (!Array.isArray(entradasPlanejadas)) return [];
        return entradasPlanejadas.filter(item => {
            // Helper robusto para extrair Ano e Mês de qualquer formato de data da API
            const matchPeriod = (dataStr) => {
                const { year, month } = parseDateInfo(dataStr);
                if (filtroTipo === 'ano') return year === Number(filtroAno);
                if (filtroTipo === 'mes') return year === Number(filtroAno) && month === Number(filtroMes);
                return true;
            };
            // Apply period filter
            if (!matchPeriod(item?.dataEstimativa || item?.dataCriacao || '')) return false;
            // Clientes/Caixinhas filtro simplificado para planejado se não houver mapeamento direto
            return true;
        });
    }, [entradasPlanejadas, 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: 'C' // Receitas
                });
                
                // Normaliza o resultado conforme o backend (esperado array de objetos)
                // Normaliza o resultado conforme o backend para receitas
                const data = result?.por_categoria ?? result?.dados ?? result?.Base_Dados_API ?? (Array.isArray(result) ? result : []);
                console.log('[CruzamentoView] somaCategorias carregadas:', data.length, 'itens');
                if (data.length > 0) {
                    console.log('[CruzamentoView] Exemplo soma:', data[0]);
                }
                setSomaCategorias(Array.isArray(data) ? data : []);
            } catch (err) {
                console.error('[CruzamentoView] Erro ao buscar soma por categoria:', err);
                setSomaCategorias([]);
            } finally {
                setIsLoadingSoma(false);
            }
        };

        if (filtroTipo === 'mes' && filtroMes && filtroAno) {
            fetchSoma();
        } else {
            // Se não for mensal, limpamos ou mantemos (ajustar conforme necessidade)
            setSomaCategorias([]);
        }
    }, [filtroMes, filtroAno, filtroTipo]);

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

    // 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.fetchEntradasPlanejadasTotal({
                    mes: filtroMes,
                    ano: filtroAno
                });
                
                if (result) {
                    setTotaisPlanejados(result);
                }
            } catch (err) {
                console.error('[CruzamentoView] Erro ao buscar totais planejados:', err);
            } finally {
                setIsLoadingTotais(false);
            }
        };

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

    // Modal state

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

    const transactionsForSelectedCategory = React.useMemo(() => {
        if (!selectedCategory) return [];
        
        // Agora buscamos diretamente no objeto que o backend retornou já agrupado
        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('[CruzamentoView] Modal: itens para', selectedCategory.name, ':', transactions.length);
        return transactions;
    }, [selectedCategory, somaCategorias]);


    // 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;
                }
                // Nota: o sistema atual não parece ter seletor de 'dia' global aqui, 
                // mas a rota suporta. Se houver dia no futuro, adicione aqui.

                const result = await extratoService.fetchPlanejadoGrafico(params);
                const data = result?.grafico ?? result ?? [];
                setChartDataBackend(Array.isArray(data) ? data : []);
            } catch (err) {
                console.error('[CruzamentoView] Erro ao buscar dados do gráfico:', err);
                setChartDataBackend([]);
            } finally {
                setIsLoadingChart(false);
            }
        };

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

    // KPIs recalculados com dados filtrados (ou vindos do backend se for mensal)
    const kpisFiltrados = React.useMemo(() => {
        if (filtroTipo === 'mes' && totaisPlanejados) {
            return {
                total_realizado: totaisPlanejados.total_realizado || 0,
                total_boletos_a_receber: totaisPlanejados.total_boletos_a_receber || 0,
                total_planejado_geral: totaisPlanejados.total_planejado_geral || 0
            };
        }

        const total_realizado = dadosFiltrados
            .filter(t => !t?.status || t?.status === 'Recebido' || t?.status === 'Liquidado')
            .reduce((acc, t) => acc + (t?.valor || 0), 0);
        
        const total_boletos_a_receber = planejadasFiltradas.reduce((acc, t) => acc + (Number(t?.total || 0)), 0);
        
        return {
            total_realizado,
            total_boletos_a_receber,
            total_planejado_geral: total_realizado + total_boletos_a_receber
        };
    }, [dadosFiltrados, planejadasFiltradas, filtroTipo, totaisPlanejados]);

    const categoryData = useMemo(() => {
        if (!Array.isArray(somaCategorias)) return [];
        return somaCategorias.map(item => ({
            name: item.categoria || 'Sem Categoria',
            value: parseCurrency(item.total || item.total_entradas || 0)
        })).filter(item => item.value > 0);
    }, [somaCategorias]);

    const timelineData = useMemo(() => {
        const mesesLabel = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
        
        const filteredExecutadas = dadosFiltrados.filter(item => 
            !item?.status || item?.status === 'Recebido' || item?.status === 'Liquidado'
        );
        const filteredPlanejadas = planejadasFiltradas;
        
        if (filtroTipo === 'ano') {
            const map = {};
            mesesLabel.forEach((_, i) => { map[String(i + 1).padStart(2, '0')] = { executado: 0, planejado: 0 }; });
            
            filteredPlanejadas.forEach(item => {
                const { year, month } = parseDateInfo(item.dataEstimativa || item.dataCriacao);
                if (year === Number(filtroAno)) {
                    const key = String(month).padStart(2, '0');
                    if (map[key]) map[key].planejado += Number(item.total || 0);
                }
            });

            filteredExecutadas.forEach(item => {
                const { year, month } = parseDateInfo(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];
                const label = `${key}/${filtroAno}`;
                return { name: label, ...values, value: values.executado };
            });
        }
        
        const map = {};
        filteredPlanejadas.forEach(item => {
            const { month, year, day } = parseDateInfo(item.dataEstimativa || item.dataCriacao);
            if (month && String(year) === String(filtroAno) && (filtroTipo !== 'mes' || String(month) === String(filtroMes))) {
                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.total || 0);
            }
        });

        filteredExecutadas.forEach(item => {
            const { month, year, day } = parseDateInfo(item.dataEntrada);
            if (month && String(year) === String(filtroAno) && (filtroTipo !== 'mes' || String(month) === String(filtroMes))) {
                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 }));
    }, [dadosFiltrados, planejadasFiltradas, filtroTipo, filtroAno, filtroMes]);

    // Dados comparativos: planejado vs executado
    const comparativoData = 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 
                };
            });
        }

        const mesesLabel = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
        const map = {};

        if (filtroTipo === 'ano') {
            mesesLabel.forEach((_, i) => {
                const key = String(i + 1).padStart(2, '0');
                map[key] = { name: mesesLabel[i], executado: 0, planejado: 0 };
            });

            dadosFiltrados.forEach(item => {
                const raw = item?.dataEntrada || '';
                const mes = raw.length >= 7 ? raw.substring(5, 7) : null;
                if (mes && map[mes]) map[mes].executado += Number(item?.valor || 0);
            });

            planejadasFiltradas.forEach(item => {
                const raw = item?.dataEstimativa || item?.dataCriacao || '';
                const mes = raw.length >= 7 ? raw.substring(5, 7) : null;
                if (mes && map[mes]) map[mes].planejado += Number(item?.total || 0);
            });

            return Object.values(map).map(item => {
                const variacao = item.executado - item.planejado;
                const percentual = item.planejado > 0 ? ((item.executado / item.planejado) * 100).toFixed(1) : 0;
                return { ...item, variacao, percentual };
            });
        }

        // Visão mensal/diária
        dadosFiltrados.forEach(item => {
            const { day, month } = parseDateInfo(item?.dataEntrada);
            const label = day ? `${String(day).padStart(2, '0')}-${String(month).padStart(2, '0')}` : `${String(month).padStart(2, '0')}`;
            if (!map[label]) map[label] = { name: label, executado: 0, planejado: 0 };
            map[label].executado += Number(item?.valor || 0);
        });

        planejadasFiltradas.forEach(item => {
            const { day, month } = parseDateInfo(item?.dataEstimativa || item?.dataCriacao);
            const label = day ? `${String(day).padStart(2, '0')}-${String(month).padStart(2, '0')}` : `${String(month).padStart(2, '0')}`;
            if (!map[label]) map[label] = { name: label, executado: 0, planejado: 0 };
            map[label].planejado += Number(item?.total || 0);
        });

        return Object.entries(map)
            .sort((a,b) => a[0].localeCompare(b[0]))
            .map(([name, values]) => {
                const variacao = values.executado - values.planejado;
                const percentual = values.planejado > 0 ? ((values.executado / values.planejado) * 100).toFixed(1) : 0;
                return { ...values, name, variacao, percentual };
            });
    }, [dadosFiltrados, planejadasFiltradas, filtroTipo, chartDataBackend, filtroMes]);

    // Análise de Variância baseada exclusivamente na rota de soma por categoria
    const variacaoCategoria = useMemo(() => {
        if (!Array.isArray(somaCategorias)) return [];
        
        return somaCategorias.map(item => ({
            id: item.idcategoria ?? item.idCategoria ?? item.id,
            categoria: item.categoria || 'Sem Categoria',
            categoriaNome: item.categoria || '(Sem Categoria)',
            name: item.categoria || '(Sem Categoria)',
            entradas: parseCurrency(item.total || item.total_entradas || 0),
            saidas: parseCurrency(item.total_saidas || 0),
            diferenca: parseCurrency(item.diferenca || 0),
            percentual: 0 // Ajustar se necessário
        })).sort((a, b) => b.entradas - a.entradas);
    }, [somaCategorias]);

    // KPIs de variância: Usando os dados reais
    const kpisVariacao = useMemo(() => {
        if (filtroTipo === 'mes' && totaisPlanejados) {
            return {
                total_realizado: totaisPlanejados.total_realizado || 0,
                total_planejado: totaisPlanejados.total_planejado || 0,
                total_boletos_a_receber: totaisPlanejados.total_boletos_a_receber || 0,
                diferenca: totaisPlanejados.diferenca || 0,
                percentual_variacao: (totaisPlanejados.total_planejado || 0) > 0 
                    ? ((totaisPlanejados.total_realizado / totaisPlanejados.total_planejado) * 100).toFixed(1) 
                    : '0'
            };
        }

        const total_realizado = kpisFiltrados.total_realizado;
        const total_planejado = planejadasFiltradas
            .filter(p => !p.parcelado) // Exemplo de lógica local se necessário
            .reduce((acc, p) => acc + (Number(p.total || 0)), 0);
        
        const total_boletos_a_receber = kpisFiltrados.total_boletos_a_receber;
        const diferenca = total_realizado - (total_planejado + total_boletos_a_receber);
        const percentual_variacao = (total_planejado + total_boletos_a_receber) > 0 
            ? ((total_realizado / (total_planejado + total_boletos_a_receber)) * 100).toFixed(1) 
            : '0';

        return {
            total_realizado,
            total_planejado,
            total_boletos_a_receber,
            diferenca,
            percentual_variacao
        };
    }, [kpisFiltrados, filtroTipo, totaisPlanejados, planejadasFiltradas]);

    const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6', '#ec4899', '#f43f5e'];

    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-20">
                <div className="absolute top-20 right-0 w-96 h-96 bg-blue-500/10 rounded-full blur-3xl" />
                <div className="absolute bottom-40 left-0 w-[500px] h-[500px] bg-emerald-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-emerald-600 dark:text-emerald-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>
                            <SelectItem value="todos">Todos</SelectItem>
                        </SelectContent>
                    </Select>
                    {filtroTipo === 'mes' && (
                        <>
                            <Select value={filtroMes} onValueChange={setFiltroMes}>
                                <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_REC.map((m, i) => (i === 0 ? null : <SelectItem key={i} value={String(i)}>{m}</SelectItem>))}
                                </SelectContent>
                            </Select>
                            <Select value={filtroAno} onValueChange={setFiltroAno}>
                                <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_REC.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                                </SelectContent>
                            </Select>
                        </>
                    )}
                    {filtroTipo === 'ano' && (
                        <Select value={filtroAno} onValueChange={setFiltroAno}>
                            <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_REC.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                            </SelectContent>
                        </Select>
                    )}
                    <Select value={filtroCaixa} onValueChange={setFiltroCaixa}>
                        <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>
                            {(caixas || []).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' && filtroMes ? `${MESES_REC[Number(filtroMes)]} / ${filtroAno}` : filtroTipo === 'ano' ? filtroAno : 'Todos'}
                    </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="text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-emerald-500">+12.4% vs mês anterior</p>
                    </div>
                    <div className="w-[clamp(2rem,2.5vw,2.5rem)] h-[clamp(2rem,2.5vw,2.5rem)] rounded-full border-2 border-emerald-500/20 border-t-emerald-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-emerald-500" />
                    </div>
                </div>
            </div>

            {/* KPIs Principais */}
            <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="Liquidado"
                    value={formatCurrency(kpisFiltrados.total_realizado)}
                    subtext="Total recebido efetivamente"
                    icon={CheckCircle2}
                    colorClass="text-emerald-500"
                    loading={isLoadingTotais}
                />
                 {/* <KPICard 
                    title="Expectativa"
                    value={formatCurrency(kpisFiltrados.total_planejado)}
                    subtext="Total planejado + boletos á receber p/ o período"
                    icon={Clock}
                    colorClass="text-blue-500"
                    loading={isLoadingTotais}
                /> */}
                 <KPICard 
                    title="Volume Geral"
                    value={formatCurrency(kpisFiltrados.total_planejado_geral)}
                    subtext="Soma de realizado + esperado"
                    icon={TrendingUp}
                    colorClass="text-purple-500"
                    loading={isLoadingTotais}
                />
            </div>

            {/* KPIs de Variância */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4 md:gap-6 relative z-10">
                <KPICard 
                    title="Expectativa (Plan)"
                    value={formatCurrency(kpisVariacao.total_planejado)}
                    subtext="Total de entradas planejadas"
                    icon={Target}
                    colorClass="text-blue-500"
                    loading={isLoadingTotais}
                />
                <KPICard 
                    title="Boletos á receber"
                    value={formatCurrency(kpisVariacao.total_boletos_a_receber)}
                    subtext="Boletos á receber no perido"
                    icon={CheckCircle2}
                    colorClass="text-emerald-500"
                    highlight
                    loading={isLoadingTotais}
                />
                <KPICard 
                    title="Variação"
                    value={formatCurrency(kpisVariacao.diferenca)}
                    subtext={kpisVariacao.diferenca >= 0 ? "Acima do planejado" : "Abaixo do planejado"}
                    icon={BarChart3}
                    trend={kpisVariacao.diferenca >= 0 ? 'up' : 'down'}
                    colorClass={kpisVariacao.diferenca >= 0 ? "text-emerald-500" : "text-rose-500"}
                    loading={isLoadingTotais}
                />
                {/* <KPICard 
                    title="Taxa de Entrega"
                    value={`${kpisVariacao.percentualVariacao}%`}
                    subtext="Realizado vs Planejado"
                    icon={Activity}
                    colorClass="text-purple-500"
                    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' }}>
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={comparativoData}>
                            <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: '#f1f5f9', 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>}
                            />
                            <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="#10b981" 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-emerald-500/10 flex items-center justify-center border border-emerald-500/20 shrink-0">
                                <PieChart className="w-[clamp(0.875rem,1vw,1rem)] h-[clamp(0.875rem,1vw,1rem)] text-emerald-500" />
                            </div>
                            <span className="truncate">Composição de Receita</span>
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="h-[280px] sm:h-[320px] md:h-[380px] p-4 sm:p-6 pt-6 sm:pt-10">
                        {categoryData.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%">
                                <RePieChart>
                                <Pie
                                    data={categoryData}
                                    cx="50%"
                                    cy="50%"
                                    innerRadius={85}
                                    outerRadius={115}
                                    paddingAngle={10}
                                    dataKey="value"
                                    nameKey="name"
                                    stroke="none"
                                >
                                    {categoryData.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>}
                                />
                                <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 */}
                <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 Recebimento</span>
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="h-[clamp(18.75rem,40vh,25rem)] p-0 pr-[clamp(0.75rem,1.5vw,1.5rem)] pt-[clamp(1.5rem,2.5vh,2.5rem)]">
                        <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                            <AreaChart data={timelineData}>
                                <defs>
                                    <linearGradient id="colorWave" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%" stopColor="#10b981" stopOpacity={0.4}/>
                                        <stop offset="95%" stopColor="#10b981" 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} />} />
                                <Area 
                                    type="monotone" 
                                    dataKey="value" 
                                    name="Recebido"
                                    stroke="#10b981" 
                                    strokeWidth={4} 
                                    fillOpacity={1} 
                                    fill="url(#colorWave)" 
                                    dot={{ fill: '#10b981', r: 4, strokeWidth: 2, stroke: '#1e293b' }}
                                    activeDot={{ r: 6, stroke: '#fff', strokeWidth: 2, fill: '#10b981' }}
                                />
                            </AreaChart>
                        </ResponsiveContainer>
                    </CardContent>
                </Card>
            </div>

            {/* 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-slate-200 dark:border-slate-800/50 bg-slate-50 dark: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="h-[clamp(25rem,50vh,30rem)]">
                        <ExcelTable 
                            data={variacaoCategoria}
                             columns={[
                                {
                                    field: 'categoriaNome',
                                    header: 'Categoria',
                                    width: '250px',
                                    render: (row) => (
                                        <button 
                                            onClick={() => handleCategoryClick(row.categoria, row.id)}
                                            className="font-semibold text-slate-900 dark:text-white pl-3 hover:text-emerald-500 transition-colors text-left w-full"
                                        >
                                            {row.categoriaNome}
                                        </button>
                                    )
                                },
                                {
                                    field: 'entradas',
                                    header: 'Entradas',
                                    width: '150px',
                                    render: (row) => (
                                        <span className="font-mono text-xs text-emerald-400 text-right block w-full">
                                            {formatCurrency(row.entradas)}
                                        </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: '% Lucro',
                                    width: '150px',
                                    render: (row) => (
                                        <div className="flex justify-end pr-3">
                                            <Badge className={cn(
                                                "text-[9px] font-bold",
                                                parseFloat(row.percentual) >= 50 
                                                    ? "bg-emerald-500/10 text-emerald-500 border-emerald-500/20"
                                                    : parseFloat(row.percentual) >= 20
                                                    ? "bg-amber-500/10 text-amber-500 border-amber-500/20"
                                                    : "bg-red-500/10 text-red-500 border-red-500/20"
                                            )}>
                                                {row.percentual}%
                                            </Badge>
                                        </div>
                                    )
                                }
                            ]}
                            rowKey="categoria"
                            pageSize={20}
                        />
                    </div>
                </CardContent>
            </Card>

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

