import React, { useMemo } from 'react';
// import { parse, format } from 'date-fns'; // Removido para evitar erro de build
import { 
  ArrowRightLeft,
  Building2,
  FolderTree,
  Users,
  Receipt,
  ChevronRight,
  ChevronLeft,
  Filter,
  Calendar,
  Search,
  TrendingUp,
  TrendingDown,
  PieChart,
  BarChart3,
  Activity,
  Download,
  Loader2,
  Table as TableIcon,
  ListTree,
  ChevronDown,
  FileText
} from 'lucide-react';
import { TransactionDetailModal } from '../../components/TransactionDetailModal';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import ExcelTable from '../../components/ExcelTable';
import { formatDate, formatCurrency, formatDateForChart } from '../../utils/dateUtils';
import {
  PieChart as RePieChart,
  Pie,
  Cell,
  BarChart,
  Bar,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  AreaChart,
  Area
} from 'recharts';

/** Sanitiza rótulo: corrige typos, espaços e remove trechos duplicados nas legendas */
function sanitizeLabel(name) {
    if (name == null || typeof name !== 'string') return '—';
    let s = name.replace(/\s+/g, ' ').trim();
    if (!s) return '—';
    if (s === 'Padronizadosss') return 'Padronizados';
    // Remove duplicação: ex. "INSTITUTO BRASILEIRO DE DINSTITUTO BRASILEIRO DE ADMINISTRAÇAO..."
    // -> "INSTITUTO BRASILEIRO DE ADMINISTRAÇAO..."
    const repeatedPhrase = /(.{15,}?)\s*\w?\s*\1(.*)/;
    let prev = '';
    while (prev !== s && repeatedPhrase.test(s)) {
        prev = s;
        s = s.replace(repeatedPhrase, (_, phrase, rest) => (phrase + rest).replace(/\s+/g, ' ').trim());
    }
    return s || '—';
}

function AccordionItem({ title, icon: Icon, value, count, children, isOpen, onClick, color }) {
    return (
        <div className="border border-slate-200 dark:border-slate-800 rounded-xl mb-3 overflow-hidden bg-white dark:bg-slate-900/50">
            <div 
                className={cn(
                    "p-4 flex items-center justify-between cursor-pointer transition-colors select-none",
                    isOpen ? "bg-slate-50 dark:bg-slate-800/50" : "hover:bg-slate-50 dark:hover:bg-slate-900"
                )}
                onClick={onClick}
            >
                <div className="flex items-center gap-3">
                    <div 
                        className="w-10 h-10 rounded-lg flex items-center justify-center border"
                        style={color ? { backgroundColor: `${color}20`, borderColor: `${color}40` } : {}}
                    >
                        <Icon className="w-5 h-5" style={color ? { color } : {}} />
                    </div>
                    <div>
                        <h4 className="font-bold text-slate-900 dark:text-white text-sm">{title}</h4>
                        <p className="text-[clamp(0.7rem,1vw,0.8rem)] text-slate-500 uppercase font-bold tracking-wider">{count} Transações</p>
                    </div>
                </div>
                <div className="flex items-center gap-4">
                    <span className="font-bold text-slate-900 dark:text-white">{formatCurrency(value)}</span>
                    <ChevronDown className={cn("w-5 h-5 text-slate-400 transition-transform duration-300", isOpen && "rotate-180")} />
                </div>
            </div>
            {isOpen && (
                <div className="p-4 border-t border-slate-200 dark:border-slate-800 animate-in slide-in-from-top-2 duration-300">
                    {children}
                </div>
            )}
        </div>
    );
}

/** Trunca legenda longa para exibição no eixo (mantém nome completo no tooltip) */
function truncateLegend(name, maxLen = 42) {
    const clean = sanitizeLabel(name);
    if (clean.length <= maxLen) return clean;
    return clean.substring(0, maxLen - 3).trim() + '...';
}

/** Tooltip customizado para gráficos de conciliação: layout limpo, label + valor */
function ConciliacaoChartTooltip({ active, payload, label, formatCurrency }) {
    if (!active || !payload?.length) return null;
    const item = payload[0];
    const name = item.name ?? label ?? item.payload?.name ?? '—';
    const value = item.value ?? item.payload?.valor ?? item.payload?.value ?? 0;
    const displayName = typeof name === 'string' ? sanitizeLabel(name) : String(name);
    return (
        <div className="rounded-xl border border-slate-200 dark:border-slate-800 bg-white/95 dark:bg-slate-900/95 backdrop-blur-md px-4 py-3 shadow-xl min-w-[160px]">
            <p className="text-[clamp(0.7rem,1vw,0.8rem)] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">{displayName}</p>
            <p className="text-base font-bold text-slate-900 dark:text-emerald-400 tabular-nums">{formatCurrency(value)}</p>
        </div>
    );
}

export function TransacoesConciliadasView({ state, actions }) {
    const { 
        caixas, 
        categorias, 
        regras, 
        filtroCaixa,
        filtroAno,
        filtroMes,
        nivelNavegacao,
        caminhoNavegacao,
        caixaSelecionado,
        categoriaSelecionada,
        subgroupSelecionado,
        backendNavData,
        isNavLoading
    } = state;

    // Função utilitária para truncar nomes longos
    const truncateLabel = (text, limit = 20) => {
        if (!text) return '';
        if (text.length <= limit) return text;
        return text.substring(0, limit) + '...';
    };

    // Estado local para exportação
    const [isExporting, setIsExporting] = React.useState(false);

    // Estado do modal de detalhes
    const [selectedTransaction, setSelectedTransaction] = React.useState(null);
    const [detailsOpen, setDetailsOpen] = React.useState(false);

    const handleTransactionClick = (row) => {
        setSelectedTransaction(row);
        setDetailsOpen(true);
    };


    const handleExportPDF = async () => {
        setIsExporting(true);
        try {
            await actions.exportarPDF();
        } finally {
            setIsExporting(false);
        }
    };

    // Estado local para controlar se filtra por mês ou por ano
    const [tipoFiltroTemporal, setTipoFiltroTemporal] = React.useState('mes'); // 'mes' ou 'ano'

    // Quando o tipo de filtro muda, ajustar os filtros
    React.useEffect(() => {
        if (tipoFiltroTemporal === 'ano') {
            // Quando filtrar por ano, limpar o filtro de mês para mostrar todos os meses do ano
            if (filtroMes !== null) {
                actions.setFiltroMes(null);
            }
        } else if (tipoFiltroTemporal === 'mes') {
            // Quando voltar a filtrar por mês, restaurar o mês atual se não houver
            if (!filtroMes) {
                actions.setFiltroMes(new Date().getMonth() + 1);
            }
        }
    }, [tipoFiltroTemporal]); // eslint-disable-line react-hooks/exhaustive-deps


    // Estado para busca local
    const [searchTerm, setSearchTerm] = React.useState('');

    // Obter dados para o nível atual (agora vindo do backend via hook)
    const dadosBackend = useMemo(() => {
        return backendNavData || [];
    }, [backendNavData]);

    // Filtrar dados localmente via search
    const dadosNivelAtual = useMemo(() => {
        if (!searchTerm) return dadosBackend;
        const lowerTerm = searchTerm.toLowerCase();
        return dadosBackend.filter(item => {
            return (
                (item.nome && item.nome.toLowerCase().includes(lowerTerm)) ||
                (item.descricao && item.descricao.toLowerCase().includes(lowerTerm)) ||
                (item.beneficiario && item.beneficiario.toLowerCase().includes(lowerTerm)) ||
                (item.valor && String(item.valor).includes(lowerTerm))
            );
        });
    }, [dadosBackend, searchTerm]);

    // Dados para gráficos por nível
    const dadosGrafico = useMemo(() => {
        if (!dadosNivelAtual || dadosNivelAtual.length === 0) return [];

        if (nivelNavegacao === 0) {
            // Pizza: Distribuição por Caixa
            return dadosNivelAtual.map(caixa => ({
                name: caixa.nome,
                value: Math.abs(caixa.totalValor || 0)
            }));
        } else if (nivelNavegacao === 1 || nivelNavegacao === 2) {
            // Barras: Distribuição por Categoria (Nível 1) ou Subgrupo (Nível 2)
            return dadosNivelAtual.map(item => ({
                name: item.nome || 'Sem Identificação',
                value: Math.abs(item.totalValor || 0),
                transacoes: item.totalTransacoes || 0,
                cor: item.cor || (nivelNavegacao === 2 ? '#94a3b8' : '#3b82f6')
            }));
        } else if (nivelNavegacao === 3) {
            // Timeline: Transações individuais
            // Agrupar por data para o gráfico
            const timelineMap = {};
            dadosNivelAtual.forEach(t => {
                const dateStr = t.data || t.dataEntrada || '';
                const label = formatDateForChart(dateStr);
                
                timelineMap[label] = (timelineMap[label] || 0) + Math.abs(t.valor || 0);
            });

            // Ordenar por data (assumindo formato DD/MM ou YYYY-MM-DD)
            return Object.entries(timelineMap)
                .map(([name, valor]) => ({ name, valor }))
                .sort((a, b) => {
                    const [diaA, mesA] = a.name.split('/').map(Number);
                    const [diaB, mesB] = b.name.split('/').map(Number);
                    if (mesA !== mesB) return mesA - mesB;
                    return diaA - diaB;
                });
        }
        return [];
    }, [nivelNavegacao, dadosNivelAtual]);

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

    const renderGrafico = () => {
        if (!dadosGrafico || dadosGrafico.length === 0) {
            console.log('[TransacoesConciliadasView] Sem dados para gráfico');
            return null;
        }
        console.log('[TransacoesConciliadasView] Renderizando gráfico com', dadosGrafico.length, 'itens');

        if (nivelNavegacao === 0) {
            // Gráfico de Pizza para Caixas
            return (
                <Card className="bg-white dark:bg-[#1e293b]/40 border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden mb-6">
                    <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50">
                        <CardTitle className="text-sm font-bold text-slate-900 dark:text-white flex items-center gap-2">
                            <PieChart className="w-4 h-4 text-blue-500" />
                            Distribuição por Caixa
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-4 sm:p-6">
                        <div className="w-full min-w-[300px] h-[400px] min-h-[300px] max-w-2xl mx-auto">
                            <ResponsiveContainer width="100%" height="100%">
                                <RePieChart>
                                    <Pie
                                        data={dadosGrafico}
                                        cx="50%"
                                        cy="50%"
                                        innerRadius={60}
                                        outerRadius={100}
                                        paddingAngle={5}
                                        dataKey="value"
                                        stroke="none"
                                    >
                                        {dadosGrafico.map((entry, index) => (
                                            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                        ))}
                                    </Pie>
                                    <Tooltip 
                                        content={(props) => <ConciliacaoChartTooltip {...props} formatCurrency={formatCurrency} />}
                                        cursor={{ fill: 'rgba(0,0,0,0.05)', opacity: 0.1 }}
                                    />
                                    <Legend 
                                        verticalAlign="bottom" 
                                        height={36} 
                                        iconType="circle" 
                                        formatter={(value) => <span className="text-[clamp(0.7rem,1vw,0.8rem)] uppercase font-bold text-slate-400">{sanitizeLabel(value)}</span>}
                                    />
                                </RePieChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            );
        } else if (nivelNavegacao === 1 || nivelNavegacao === 2) {
            // Gráfico de Barras para Categorias (Vertical) ou Subgrupos (Horizontal)
            const isSubgroup = nivelNavegacao === 2;
            
            return (
                <Card className="bg-white dark:bg-[#1e293b]/40 border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden mb-6">
                    <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50">
                        <CardTitle className="text-sm font-bold text-slate-900 dark:text-white flex items-center gap-2">
                            <BarChart3 className="w-4 h-4 text-blue-500" />
                            Distribuição por {isSubgroup ? 'Subgrupo' : 'Categoria'}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-4 sm:p-6">
                        <div className="w-full min-w-[300px] h-[400px] min-h-[300px] max-w-2xl mx-auto">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart 
                                    data={dadosGrafico} 
                                    layout={isSubgroup ? 'vertical' : 'horizontal'}
                                    margin={{ left: isSubgroup ? 40 : 10, right: 30, top: 20, bottom: isSubgroup ? 10 : 60 }}
                                >
                                    <CartesianGrid strokeDasharray="3 3" vertical={!isSubgroup} horizontal={isSubgroup} className="stroke-slate-200 dark:stroke-slate-700" opacity={0.5} />
                                    {isSubgroup ? (
                                        <>
                                            <XAxis 
                                                type="number"
                                                hide
                                            />
                                            <YAxis 
                                                dataKey="name" 
                                                type="category"
                                                axisLine={false} 
                                                tickLine={false} 
                                                className="fill-slate-600 dark:fill-slate-400"
                                                tick={{fontSize: 10, fontWeight: 'bold'}} 
                                                width={120}
                                                tickFormatter={(val) => truncateLabel(val, 20)}
                                            />
                                        </>
                                    ) : (
                                        <>
                                            <XAxis 
                                                dataKey="name" 
                                                axisLine={false} 
                                                tickLine={false} 
                                                className="fill-slate-600 dark:fill-slate-400"
                                                tick={{fontSize: 11, fontWeight: 'bold'}} 
                                                angle={-45}
                                                textAnchor="end"
                                                height={80}
                                                tickFormatter={(val) => truncateLabel(val, 15)}
                                            />
                                            <YAxis 
                                                axisLine={false} 
                                                tickLine={false} 
                                                className="fill-slate-600 dark:fill-slate-400"
                                                tick={{fontSize: 10}} 
                                                tickFormatter={(val) => `R$ ${val/1000}k`} 
                                            />
                                        </>
                                    )}
                                    <Tooltip 
                                        content={(props) => <ConciliacaoChartTooltip {...props} formatCurrency={formatCurrency} />}
                                        cursor={{ fill: 'rgba(0,0,0,0.05)', opacity: 0.1 }}
                                    />
                                    <Bar 
                                        dataKey="value" 
                                        radius={isSubgroup ? [0, 4, 4, 0] : [4, 4, 0, 0]}
                                        barSize={isSubgroup ? 20 : undefined}
                                    >
                                        {dadosGrafico.map((entry, index) => (
                                            <Cell key={`cell-${index}`} fill={entry.cor || COLORS[index % COLORS.length]} />
                                        ))}
                                    </Bar>
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            );
        } else if (nivelNavegacao === 3) {
            // Gráfico de Linha/Timeline para Transações
            return (
                <Card className="bg-white dark:bg-[#1e293b]/40 border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden mb-6">
                    <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50">
                        <CardTitle className="text-sm font-bold text-slate-900 dark:text-white flex items-center gap-2">
                            <Activity className="w-4 h-4 text-emerald-500" />
                            Evolução Temporal das Transações
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="p-4 sm:p-6">
                        <div className="w-full min-w-[300px] h-[400px] min-h-[300px] max-w-2xl mx-auto">
                            <ResponsiveContainer width="100%" height="100%">
                                <AreaChart data={dadosGrafico}>
                                    <defs>
                                        <linearGradient id="colorValor" 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: 11, fontWeight: 'bold'}} 
                                        dy={10} 
                                    />
                                    <YAxis 
                                        axisLine={false} 
                                        tickLine={false} 
                                        tick={{fill: '#64748b', fontSize: 10}} 
                                        tickFormatter={(val) => `R$ ${val/1000}k`} 
                                    />
                                    <Tooltip 
                                        content={(props) => <ConciliacaoChartTooltip {...props} formatCurrency={formatCurrency} />}
                                        cursor={{ fill: 'rgba(0,0,0,0.05)', opacity: 0.1 }}
                                    />
                                    <Area 
                                        type="monotone" 
                                        dataKey="valor" 
                                        stroke="#10b981" 
                                        strokeWidth={3}
                                        fillOpacity={1} 
                                        fill="url(#colorValor)" 
                                    />
                                </AreaChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            );
        }
        return null;
    };

    const renderNivel = () => {
        // Altura da tabela ajustada quando há gráfico
        const tabelaHeight = dadosGrafico.length > 0 ? 'h-[400px]' : 'h-[600px]';
        
        if (isNavLoading) {
            return (
                <div className="flex flex-col items-center justify-center p-12 text-slate-400">
                    <Loader2 className="w-8 h-8 animate-spin mb-4 text-blue-500" />
                    <p>Carregando dados...</p>
                </div>
            );
        }

        if (nivelNavegacao === 0) {
            // Lista de Caixas
            return (
                <div className={tabelaHeight}>
                    <ExcelTable
                        data={dadosNivelAtual}
                        columns={[
                            {
                                field: 'nome',
                                header: 'Caixa',
                                width: '250px',
                                render: (row) => (
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-lg bg-blue-500/10 flex items-center justify-center border border-blue-500/20">
                                            <Building2 className="w-5 h-5 text-blue-500" />
                                        </div>
                                        <div>
                                            <p className="font-bold text-slate-900 dark:text-white">{row.nome}</p>
                                            <p className="text-xs text-slate-500 dark:text-slate-400">{row.banco} - {row.agencia}/{row.conta}</p>
                                        </div>
                                    </div>
                                )
                            },
                            {
                                field: 'descricao',
                                header: 'Descrição',
                                width: '300px'
                            },
                            {
                                field: 'totalTransacoes',
                                header: 'Transações',
                                width: '120px',
                                render: (row) => (
                                    <Badge className="bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300">
                                        {row.totalTransacoes || 0}
                                    </Badge>
                                )
                            },
                            {
                                field: 'totalValor',
                                header: 'Valor Total',
                                width: '150px',
                                render: (row) => (
                                    <span className="font-bold text-slate-900 dark:text-white">
                                        {formatCurrency(row.totalValor || 0)}
                                    </span>
                                )
                            }
                        ]}
                        onRowClick={(row) => actions.navegarPara('caixa', row)}
                        rowKey="id"
                        pageSize={25}
                    />
                </div>
            );
        } else if (nivelNavegacao === 1) {
            // Lista de Categorias do Caixa selecionado
            const tabelaHeight = dadosGrafico.length > 0 ? 'h-[400px]' : 'h-[600px]';
            return (
                <div className={tabelaHeight}>
                    <ExcelTable
                        data={dadosNivelAtual}
                        columns={[
                            {
                                field: 'nome',
                                header: 'Categoria',
                                width: '250px',
                                render: (row) => (
                                    <div className="flex items-center gap-3">
                                        <div 
                                            className="w-10 h-10 rounded-lg flex items-center justify-center border"
                                            style={{ backgroundColor: `${row.cor}20`, borderColor: `${row.cor}40` }}
                                        >
                                            <FolderTree className="w-5 h-5" style={{ color: row.cor }} />
                                        </div>
                                        <div>
                                            <p className="font-bold text-slate-900 dark:text-white">{row.nome}</p>
                                            <p className="text-xs text-slate-500 dark:text-slate-400">{row.descricao}</p>
                                        </div>
                                    </div>
                                )
                            },
                            {
                                field: 'totalTransacoes',
                                header: 'Transações',
                                width: '120px',
                                render: (row) => (
                                    <Badge className="bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300">
                                        {row.totalTransacoes || 0}
                                    </Badge>
                                )
                            },
                            {
                                field: 'totalValor',
                                header: 'Valor Total',
                                width: '150px',
                                render: (row) => (
                                    <span className="font-bold text-slate-900 dark:text-white">
                                        {formatCurrency(row.totalValor || 0)}
                                    </span>
                                )
                            }
                        ]}
                        onRowClick={(row) => actions.navegarPara('categoria', row)}
                        rowKey="id"
                        pageSize={25}
                    />
                </div>
            );
        } else if (nivelNavegacao === 2) {
            // Visão de Subgrupos (Agrupamentos dentro da Categoria)
            const tabelaHeight = dadosGrafico.length > 0 ? 'h-[400px]' : 'h-[600px]';
            return (
                <div className={tabelaHeight}>
                    <ExcelTable
                        data={dadosNivelAtual}
                        columns={[
                            {
                                field: 'nome',
                                header: 'Subgrupo / Beneficiário',
                                width: '400px',
                                render: (row) => (
                                    <div className="flex items-center gap-2">
                                        <Users className="w-4 h-4 text-slate-400" />
                                        <span className="font-bold text-slate-900 dark:text-white" title={row.nome}>
                                            {truncateLabel(row.nome || 'Sem Categoria', 40)}
                                        </span>
                                    </div>
                                )
                            },
                            {
                                field: 'totalTransacoes',
                                header: 'Lançamentos',
                                width: '150px',
                                render: (row) => (
                                    <Badge variant="outline" className="text-xs font-bold bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 border-none">
                                        {row.totalTransacoes} transações
                                    </Badge>
                                )
                            },
                            {
                                field: 'totalValor',
                                header: 'Valor Total',
                                width: '200px',
                                className: 'text-right',
                                render: (row) => (
                                    <span className={cn(
                                        "font-bold font-mono",
                                        (row.totalValor || 0) >= 0 ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                    )}>
                                        {formatCurrency(row.totalValor || 0)}
                                    </span>
                                )
                            }
                        ]}
                        onRowClick={(row) => actions.navegarPara('subgrupo', row)}
                        rowKey="id"
                        pageSize={20}
                    />
                </div>
            );
        } else if (nivelNavegacao === 3) {
            // Lista de Transações Individuais
            const tabelaHeight = dadosGrafico.length > 0 ? 'h-[400px]' : 'h-[600px]';
            return (
                <div className={tabelaHeight}>
                    <ExcelTable
                            data={dadosNivelAtual}
                            columns={[
                                {
                                    field: 'data',
                                    header: 'Data',
                                    width: '120px',
                                    render: (row) => row.data || row.dataEntrada || ''
                                },
                                {
                                    field: 'descricao',
                                    header: 'Descrição',
                                    width: '350px',
                                    render: (row) => (
                                        <div className="flex items-center gap-2">
                                            <Receipt className="w-4 h-4 text-slate-400" />
                                            <span className="font-medium text-slate-900 dark:text-white">{row.descricao || 'Sem Descrição'}</span>
                                        </div>
                                    )
                                },
                                {
                                    field: 'beneficiario',
                                    header: 'Beneficiário',
                                    width: '200px',
                                    render: (row) => row.beneficiario || row.beneficiario_pagador || '-'
                                },
                                {
                                    field: 'valor',
                                    header: 'Valor',
                                    width: '150px',
                                    render: (row) => {
                                        const valor = row.valor || 0;
                                        return (
                                            <span className={cn(
                                                "font-bold",
                                                valor < 0 || row.tipo === 'DEBITO' 
                                                    ? "text-red-500" 
                                                    : "text-green-500"
                                            )}>
                                                {formatCurrency(Math.abs(valor))}
                                            </span>
                                        );
                                    }
                                },
                                {
                                    field: 'tipo',
                                    header: 'Tipo',
                                    width: '100px',
                                    render: (row) => {
                                        const tipo = row.tipo || (row.tipoOperacao === 'D' ? 'DEBITO' : 'CREDITO');
                                        const badgeClass = tipo === 'DEBITO' 
                                            ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' 
                                            : 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400';
                                        return (
                                            <Badge className={badgeClass}>
                                                {tipo}
                                            </Badge>
                                        );
                                    }
                                }
                            ]}
                        onRowClick={handleTransactionClick}
                        rowKey="id"
                        pageSize={25}
                    />
                </div>
            );
        }
        return null;
    };

    // Debug: Log dos dados recebidos
    React.useEffect(() => {
        console.log('[TransacoesConciliadasView] State atualizado:', {
            caixas: caixas.length,
            categorias: categorias.length,
            regras: regras.length,
            dadosNivelAtual: dadosNivelAtual.length,
            dadosGrafico: dadosGrafico.length
        });
    }, [caixas, categorias, regras, dadosNivelAtual, dadosGrafico]);

    return (
        <div className="animate-in fade-in duration-700 space-y-6">
            {/* Breadcrumb e Filtros */}
            <Card className="bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden">
                <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50">
                    <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                        {/* Seletor de Visão e Breadcrumb */}
                        <div className="flex items-center gap-4 flex-wrap">
                            <div className="flex items-center gap-2 text-blue-600 font-bold uppercase tracking-wider text-xs">
                                <FileText className="w-4 h-4" />
                                <span>Transações Conciliadas</span>
                            </div>

                             {nivelNavegacao > 0 && (
                                <div className="flex items-center gap-4">
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={actions.voltarNavegacao}
                                        className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white h-7 px-2"
                                    >
                                        <ChevronLeft className="w-4 h-4 mr-1" />
                                        Voltar
                                    </Button>
                                    
                                    <div className="flex items-center gap-2">
                                        {caminhoNavegacao.map((item, idx) => (
                                            <React.Fragment key={idx}>
                                                <div className="flex flex-col">
                                                    <span className="text-[9px] uppercase font-black text-slate-400 tracking-tighter leading-none">{item.tipo}</span>
                                                    <span className="text-sm font-bold text-slate-700 dark:text-slate-200">{item.item.nome || item.item.beneficiario}</span>
                                                </div>
                                                {idx < caminhoNavegacao.length - 1 && <ChevronRight className="w-4 h-4 text-slate-300" />}
                                            </React.Fragment>
                                        ))}
                                        {nivelNavegacao === 3 && (
                                            <>
                                                <ChevronRight className="w-4 h-4 text-slate-300" />
                                                <div className="flex flex-col">
                                                    <span className="text-[9px] uppercase font-black text-slate-400 tracking-tighter leading-none">Visão</span>
                                                    <span className="text-sm font-bold text-blue-600">Lançamentos</span>
                                                </div>
                                            </>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Filtros */}
                        <div className="flex items-center gap-2 flex-wrap">
                            {/* Busca Texto */}
                            <div className="relative">
                                <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                                <Input 
                                    placeholder="Buscar..." 
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="h-9 w-[200px] pl-9 bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-sm"
                                />
                            </div>

                            <Select value={filtroCaixa?.toString() || 'todos'} onValueChange={(val) => actions.setFiltroCaixa(val === 'todos' ? null : parseInt(val))}>
                                <SelectTrigger className="h-9 w-[180px] bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-sm">
                                    <SelectValue placeholder="Filtrar por Caixa" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem key="all" value="all">Todas as Contas</SelectItem>
                                    {caixas.map((caixa, index) => (
                                        <SelectItem key={String(caixa.id ?? index)} value={String(caixa.id ?? '')}>
                                            {caixa.nome}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            
                            {/* Seletor de Tipo de Filtro Temporal */}
                            <Select value={tipoFiltroTemporal} onValueChange={setTipoFiltroTemporal}>
                                <SelectTrigger className="h-9 w-[140px] bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-sm">
                                    <div className="flex items-center gap-2">
                                        <Calendar className="w-4 h-4" />
                                        <SelectValue placeholder="Tipo de Filtro" />
                                    </div>
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="mes">Filtrar por Mês</SelectItem>
                                    <SelectItem value="ano">Filtrar por Ano</SelectItem>
                                </SelectContent>
                            </Select>
                            
                            {/* Filtro de Mês - Mostrado apenas quando tipoFiltroTemporal === 'mes' */}
                            {tipoFiltroTemporal === 'mes' && (
                                <>
                                    <Select 
                                        value={filtroMes?.toString() || (new Date().getMonth() + 1).toString()} 
                                        onValueChange={(val) => actions.setFiltroMes(parseInt(val))}
                                    >
                                        <SelectTrigger className="h-9 w-[140px] bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-sm">
                                            <SelectValue placeholder="Mês" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {[
                                                { value: 1, label: 'Janeiro' },
                                                { value: 2, label: 'Fevereiro' },
                                                { value: 3, label: 'Março' },
                                                { value: 4, label: 'Abril' },
                                                { value: 5, label: 'Maio' },
                                                { value: 6, label: 'Junho' },
                                                { value: 7, label: 'Julho' },
                                                { value: 8, label: 'Agosto' },
                                                { value: 9, label: 'Setembro' },
                                                { value: 10, label: 'Outubro' },
                                                { value: 11, label: 'Novembro' },
                                                { value: 12, label: 'Dezembro' }
                                            ].map(mes => (
                                                <SelectItem key={mes.value} value={mes.value.toString()}>{mes.label}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </>
                            )}
                            
                            {/* Seletor de Ano - Sempre visível se tipo for ano ou mes */}
                            {(tipoFiltroTemporal === 'mes' || tipoFiltroTemporal === 'ano') && (
                                <Select value={(filtroAno ?? new Date().getFullYear()).toString()} onValueChange={(val) => actions.setFiltroAno(parseInt(val))}>
                                    <SelectTrigger className="h-9 w-[120px] bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-sm">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {[2024, 2025, 2026, 2027, 2028, 2029, 2030].map(ano => (
                                            <SelectItem key={ano} value={ano.toString()}>{ano}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            )}
                            
                            {/* Botão Exportar PDF */}
                            <Button 
                                variant="outline" 
                                size="sm" 
                                onClick={handleExportPDF}
                                disabled={isExporting}
                                className="h-9 border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 font-bold hover:bg-slate-100 dark:hover:bg-slate-800"
                            >
                                {isExporting ? (
                                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                ) : (
                                    <Download className="w-4 h-4 mr-2" />
                                )}
                                Exportar PDF
                            </Button>
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-4 sm:p-6">
                    {/* Gráfico Visual */}
                    {renderGrafico()}
                    
                    {/* Tabela de Dados ou Accordion Consolidado */}
                    <div className={dadosGrafico.length > 0 ? 'mt-6' : ''}>
                        {renderNivel()}
                    </div>
                </CardContent>
            </Card>

            {/* Modal de Detalhamento da Transação */}
            <TransactionDetailModal 
                transaction={selectedTransaction}
                open={detailsOpen}
                onOpenChange={setDetailsOpen}
                onNavigateToConciliacao={(t) => setDetailsOpen(false)}
                onEditCategoria={(t) => setDetailsOpen(false)}
            />
        </div>
    );
};
