import React, { useState } from 'react';
import { 
   ArrowUpRight, 
   ArrowDownRight,
   DollarSign,
   TrendingUp,
   CreditCard,
   Users,
   Settings,
   MoreHorizontal,
   AlertCircle,
   FileText,
   Loader2,
   Calendar,
   Wallet,
   Info
 } from 'lucide-react';
 import { 
   Dialog, 
   DialogContent, 
   DialogHeader, 
   DialogTitle, 
   DialogDescription,
   DialogFooter
 } from '@/components/ui/dialog';
 import { Card, CardContent } from '@/components/ui/card';
 import { Button } from '@/components/ui/button';
 import { Badge } from '@/components/ui/badge';
 import ExcelTable from '../components/ExcelTable';
 import {
   BarChart,
   XAxis,
   YAxis,
   CartesianGrid,
   Tooltip,
   ResponsiveContainer,
   LineChart,
   Line,
   PieChart,
   Pie,
   Cell,
   Legend,
   AreaChart,
   Area,
   Bar
 } from 'recharts';
 import { cn } from '@/lib/utils';
 import { useDashboard } from '../hooks/useDashboard';
import { TransactionDetailModal } from '../components/TransactionDetailModal';
import { formatDate, formatCurrency } from '../utils/dateUtils';
import { parseDateInfo } from '@/utils/dateUtils';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { FinanceiroChartTooltip } from '../components/FinanceiroChartTooltip';
import { useConciliacaoV2 } from '../hooks/useConciliacaoV2';
import { ExtratoCompletoView } from './conciliacao-v2/ExtratoCompletoView';
import { CategorizacaoDialog } from '../components/CategorizacaoDialog';
 
 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);

 // Premium KPI Card with Glow and Glassmorphism - Dashboard Version
 const XPICard = ({ 
   title, 
   value, 
   subtitle, 
   icon: Icon, 
   bgIcon, 
   onClick,
   loading = false,
   trend = null
  }) => {
   const handleClick = (e) => {
     if (onClick) {
       console.log('XPICard clicked:', title);
       onClick(e);
     }
   };

   return (
    <Card 
      className={cn(
        "bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl relative overflow-hidden group transition-all duration-500 hover:border-slate-300 dark:hover:border-slate-700/50 rounded-2xl",
        onClick && "cursor-pointer active:scale-[0.98]"
      )}
      onClick={handleClick}
    >
      {/* Animated Glow Effect */}
      <div className={cn(
        "absolute -right-12 -bottom-12 w-[clamp(8rem,15vw,12rem)] h-[clamp(8rem,15vw,12rem)] rounded-full opacity-0 group-hover:opacity-10 transition-opacity duration-700 blur-3xl bg-emerald-500"
      )} />
      
      <CardContent className="p-[clamp(0.875rem,1.5vw,1.375rem)] 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-bold text-slate-500 dark:text-slate-400 uppercase tracking-[0.2em] mb-[clamp(0.375rem,0.5vw,0.625rem)]">{title}</p>
          
          {loading ? (
            <div className="h-[clamp(1.25rem,2vw,1.75rem)] w-36 bg-slate-200 dark:bg-slate-700 animate-pulse rounded mt-1" />
          ) : (
            <h3 className="text-[clamp(1.25rem,2vw,1.75rem)] font-bold tracking-tight text-slate-900 dark:text-white leading-none">
              {value}
            </h3>
          )}

          <div className="flex items-center gap-[clamp(0.375rem,0.5vw,0.75rem)] mt-[clamp(0.5rem,1vw,1rem)] flex-wrap">
            {trend && !loading && (
              <div className={cn(
                "flex items-center gap-1.5 text-[clamp(0.7rem,0.8vw,0.85rem)] font-bold px-[clamp(0.5rem,0.6vw,0.75rem)] py-1 rounded-lg shrink-0",
                trend > 0 ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400" : "bg-rose-500/10 text-rose-600 dark:text-rose-400"
              )}>
                {trend > 0 ? <ArrowUpRight size={14} /> : <ArrowDownRight size={14} />}
                {Math.abs(trend)}%
              </div>
            )}
            <p className="text-[clamp(0.7rem,0.8vw,0.8rem)] text-slate-500 dark:text-slate-400 font-bold leading-tight truncate opacity-80">{subtitle}</p>
          </div>
        </div>

        <div className={cn(
          "w-[clamp(2.5rem,3.5vw,3.25rem)] h-[clamp(2.5rem,3.5vw,3.25rem)] rounded-2xl flex items-center justify-center transition-all duration-500 group-hover:scale-110 shadow-2xl shrink-0",
          "bg-opacity-10 border border-current border-opacity-20",
          bgIcon.replace('bg-', 'text-').replace('/10', '')
        )} style={{ backgroundColor: bgIcon.includes('/') ? undefined : 'currentColor' }}>
          {loading ? (
            <Loader2 size={24} className="animate-spin" />
          ) : (
            <Icon size={20} className={bgIcon.replace('bg-', 'text-').split(' ')[1] || bgIcon.replace('bg-', 'text-')} strokeWidth={2.5} />
          )}
        </div>
      </CardContent>
    </Card>
  );
 };

 export const DashboardView = ({ onNavigate }) => {
   const { 
     loading, 
     error, 
     resumo, 
     getFluxoBarData, 
     getBoletosPieData, 
     getJurosData,
     jurosFilter,
     setJurosFilter,
     fluxoPeriodo,
     setFluxoPeriodo,
     getUltimasTransacoes,
     fetchEntradasMes,
     fetchSaidasPeriodo,
     fetchTransacoesNaoConciliadas,
     fetchBoletosAbertos,
     fetchJurosAdicionados,
     reload
   } = useDashboard();

    const { state: conciliacaoState, actions: conciliacaoActions } = useConciliacaoV2('extrato-completo');

   // States for interactive modals
   const [modalState, setModalState] = useState({
     saldo: false,
     despesas: false,
     naoConciliadas: false,
     boletosAbertos: false,
     adicionado: false
   });
   const [modalData, setModalData] = useState({
     saldo: [],
     despesas: [],
     naoConciliadas: [],
     boletosAbertos: [],
     adicionado: {
       lista: [],
       total_adicionado: 0,
       total_registros: 0
     }
   });
    const [modalLoading, setModalLoading] = useState(false);
    const [modalDate, setModalDate] = useState(new Date());
 
     // New states for juros detailing period selectors
     const [jurosDetailPeriodo, setJurosDetailPeriodo] = useState('mes'); // 'mes' | 'ano'
     const [jurosDetailMes, setJurosDetailMes] = useState(String(new Date().getMonth() + 1));
     const [jurosDetailAno, setJurosDetailAno] = useState(String(new Date().getFullYear()));

     // New states for requested adjustments
    const [isExtratoPopupOpen, setIsExtratoPopupOpen] = useState(false);
    const [isCategorizacaoOpen, setIsCategorizacaoOpen] = useState(false);

    const fetchDataForModal = async (type, dateOrParams) => {
      let mes, ano;
      
      if (type === 'adicionado' && typeof dateOrParams === 'object') {
        mes = dateOrParams.mes;
        ano = dateOrParams.ano;
      } else {
        const d = dateOrParams instanceof Date ? dateOrParams : new Date();
        mes = d.getMonth() + 1;
        ano = d.getFullYear();
      }

      let data = [];
 
      try {
        setModalLoading(true);
        switch (type) {
          case 'saldo':
            data = await fetchEntradasMes(mes, ano);
            break;
          case 'despesas':
            data = await fetchSaidasPeriodo(mes, ano);
            break;
          case 'naoConciliadas':
            data = await fetchTransacoesNaoConciliadas(mes, ano);
            break;
          case 'boletosAbertos':
            data = await fetchBoletosAbertos(); // Global
            break;
          case 'adicionado':
            const result = await fetchJurosAdicionados(mes, ano);
            data = {
              lista: result.dados || result.adicionado || [],
              total_adicionado: result.total_adicionado || 0,
              total_registros: result.total_registros || 0
            };
            break;
        }
        setModalData(prev => ({ ...prev, [type]: data }));
      } catch (err) {
        console.error(`Error loading modal data for ${type}:`, err);
      } finally {
        setModalLoading(false);
      }
    };
 
    const openModal = (type) => {
      setModalState(prev => ({ ...prev, [type]: true }));
      const now = new Date();
      if (type === 'adicionado') {
        fetchDataForModal(type, { mes: jurosDetailMes, ano: jurosDetailAno });
      } else {
        setModalDate(now);
        fetchDataForModal(type, now);
      }
    };

   const handleModalDateChange = (type, newDate) => {
      fetchDataForModal(type, newDate);
   };

   // Dados para gráficos
   const fluxoBarData = getFluxoBarData();
   const boletosPieData = getBoletosPieData();
   const ultimasTransacoes = getUltimasTransacoes(20); // Aumentado para mostrar mais scroll

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

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

    const handleNavigateToConciliacao = (transaction) => {
       setSelectedTransaction(transaction);
       setIsCategorizacaoOpen(true);
    };

    const handleEditCategoria = (transaction) => {
       setSelectedTransaction(transaction);
       setIsCategorizacaoOpen(true);
    };

   if (error) {
     return (
       <div className="flex flex-col items-center justify-center min-h-[60vh] text-center space-y-4">
         <div className="w-16 h-16 bg-rose-500/10 rounded-full flex items-center justify-center mb-2">
           <AlertCircle className="w-8 h-8 text-rose-500 dark:text-rose-400" />
         </div>
         <h3 className="text-xl font-bold text-slate-900 dark:text-white">Ops! Algo deu errado</h3>
         <p className="text-sm text-slate-500 dark:text-slate-400 max-w-sm">{error}</p>
         <Button onClick={() => window.location.reload()} variant="outline" className="mt-4 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white hover:bg-slate-100 dark:hover:bg-slate-800">
           Tentar Novamente
         </Button>
       </div>
     );
   }

   return (
     <div className="space-y-8 pb-10">
       {/* Header Section */}
       <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
         <div>
           <h1 className="text-2xl font-bold text-slate-900 dark:text-white tracking-tight">Painel Financeiro</h1>
           <p className="text-sm text-slate-500 dark:text-slate-400 uppercase tracking-widest font-bold mt-1">Visão Geral do Workspace</p>
         </div>
         {/* <div className="flex items-center gap-3">
           <Button 
            variant="outline" 
            className="bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white hover:bg-slate-50 dark:hover:bg-slate-800 h-9 px-4 text-xs font-bold"
            onClick={() => window.print()}
           >
             <FileText className="w-3.5 h-3.5 mr-2" />
             Exportar PDF
           </Button>
           <Button 
            className="bg-emerald-600 hover:bg-emerald-500 text-white h-9 px-4 text-xs font-bold shadow-lg shadow-emerald-500/20"
            onClick={() => onNavigate && onNavigate('contas-receber/novo')}
           >
             <DollarSign className="w-3.5 h-3.5 mr-2" />
             Nova Receita
           </Button>
         </div> */}
       </div>

       {/* KPI Grid */}
       <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
         <XPICard 
           title="SALDO EM CONTA" 
           value={formatCurrency(resumo.saldoTotal)} 
           subtitle="Calculado (Fluxo)"
           icon={Wallet}
           bgIcon="bg-emerald-500/10 text-emerald-500"
           loading={loading}
         />
         <XPICard 
           title="RECEITAS (EXECUTADO)" 
           value={formatCurrency(resumo.entrada)} 
           subtitle="Receitas + Último Saldo"
           icon={ArrowUpRight}
           bgIcon="bg-emerald-500/10 text-emerald-500"
           onClick={() => openModal('saldo')}
           loading={loading}
         />
         <XPICard 
           title="DESPESAS" 
           value={formatCurrency(resumo.saida)} 
           subtitle="Total de saídas"
           icon={ArrowDownRight}
           bgIcon="bg-rose-400/10 text-rose-400"
           onClick={() => openModal('despesas')}
           loading={loading}
         />
         <XPICard 
           title="TRANSAÇÕES NÃO CONCILIADAS" 
           value={resumo.transacoesPendentes} 
           subtitle="Sem conciliação"
           icon={AlertCircle}
           bgIcon="bg-amber-500/10 text-amber-500"
           onClick={() => openModal('naoConciliadas')}
           loading={loading}
         />
         <XPICard 
           title="BOLETOS EM ABERTO" 
           value={formatCurrency(resumo.emPendencia.valor)} 
           subtitle={`${resumo.emPendencia.quantidade} boletos do mês`}
           icon={CreditCard}
           bgIcon="bg-blue-500/10 text-blue-500"
           onClick={() => openModal('boletosAbertos')}
           loading={loading}
         />
         {/* 
           Card Extrato (Entradas) - Removido
           Funcionalidade substituída pelo Card de Saldo que já exibe entradas
         <XPICard 
           title="EXTRATO (ENTRADAS)" 
           value={formatCurrency(resumo.faturamento)} 
           subtitle="Entradas do mês"
           icon={TrendingUp}
           bgIcon="bg-indigo-500/10 text-indigo-500"
           onClick={() => onNavigate && onNavigate('conciliacao/extrato')}
           loading={loading}
         />
         */}
       </div>

       {/* Central Charts Area */}
       <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
         
          {/* Interest Flow Bar Chart */}
          <Card className="lg:col-span-2 bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 shadow-xl overflow-hidden">
            <div className="p-6 pb-2">
              <div className="flex justify-between items-center mb-4">
                <div className="space-y-1">
                  <h3 className="text-lg font-bold text-slate-900 dark:text-white tracking-tight">Fluxo de Juros</h3>
                  <p className="text-[10px] font-bold text-slate-500 dark:text-slate-500 uppercase tracking-widest">Pagamento de juros por período</p>
                </div>
                <div className="flex items-center gap-2">
                    <Select value={jurosFilter} onValueChange={setJurosFilter}>
                      <SelectTrigger className="w-[120px] h-8 text-xs font-bold uppercase tracking-wider bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-700">
                        <SelectValue placeholder="Período" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="mensal" className="text-xs font-bold uppercase">Mensal</SelectItem>
                        <SelectItem value="anual" className="text-xs font-bold uppercase">Anual</SelectItem>
                      </SelectContent>
                    </Select>
                  <div className="p-2 bg-blue-500/10 rounded-lg">
                    <TrendingUp className="w-4 h-4 text-blue-500" />
                  </div>
                  <Button 
                    variant="outline" 
                    className="h-8 px-3 text-[10px] font-bold uppercase tracking-wider border-slate-200 dark:border-slate-700 bg-white dark:bg-[#0f172a] hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-900 dark:text-white"
                    onClick={() => openModal('adicionado')}
                  >
                    Detalhamento
                  </Button>
                </div>
              </div>
            </div>
            
            <div className="h-[320px] px-2">
              {loading ? (
                <div className="flex items-center justify-center h-full">
                  <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
                </div>
              ) : (
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={getJurosData()} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#64748b" opacity={0.1} />
                    <XAxis 
                      dataKey="name" 
                      axisLine={false} 
                      tickLine={false} 
                      tick={{fill: '#64748b', fontSize: 10, fontWeight: 700}} 
                    />
                    <YAxis 
                      axisLine={false} 
                      tickLine={false} 
                      tick={{fill: '#64748b', fontSize: 10}}
                      tickFormatter={(val) => `R$ ${(val/1000).toFixed(0)}k`}
                    />
                    <Tooltip 
                        cursor={{ fill: 'rgba(59, 130, 246, 0.05)' }}
                        content={<FinanceiroChartTooltip formatCurrency={formatCurrency} />}
                    />
                    <Bar 
                      dataKey="valor" 
                      fill="#3b82f6" 
                      radius={[6, 6, 0, 0]}
                      barSize={50}
                    />
                  </BarChart>
                </ResponsiveContainer>
              )}
            </div>
          </Card>

         {/* Distribution Chart */}
         <Card className="bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 shadow-xl overflow-hidden flex flex-col">
           <div className="p-6">
             <h3 className="text-lg font-bold text-slate-900 dark:text-white tracking-tight">Status de Cobrança</h3>
             <p className="text-[10px] font-bold text-slate-500 dark:text-slate-500 uppercase tracking-widest">Distribuição Mensal</p>
           </div>
           
           <div className="flex-1 min-h-[250px] relative">
             {loading ? (
               <div className="flex items-center justify-center h-full">
                 <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
               </div>
             ) : (
               <>
                 <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                   <PieChart>
                     <Pie
                       data={boletosPieData}
                       cx="50%"
                       cy="45%"
                       innerRadius={65}
                       outerRadius={90}
                       paddingAngle={8}
                       dataKey="value"
                     >
                       {boletosPieData.map((entry, index) => (
                         <Cell key={`cell-${index}`} fill={entry.color} stroke="none" />
                       ))}
                       <Tooltip content={<FinanceiroChartTooltip />} />
                     </Pie>
                   </PieChart>
                 </ResponsiveContainer>
                 <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none mt-[-20px]">
                    <span className="text-2xl font-bold text-slate-900 dark:text-white">{boletosPieData.reduce((a, b) => a + b.count, 0)}</span>
                    <span className="text-[9px] font-bold text-slate-500 dark:text-slate-500 uppercase">Total</span>
                 </div>
               </>
             )}
           </div>

           <div className="p-6 bg-slate-50 dark:bg-slate-900/40 flex flex-col gap-3">
             {boletosPieData.map((item, index) => (
               <div key={index} className="flex items-center gap-3 py-1.5 group/item">
                 <div className="w-3.5 h-3.5 rounded-full shrink-0 shadow-sm transition-transform group-hover/item:scale-110" style={{ backgroundColor: item.color }} />
                 <span className="text-[clamp(0.75rem,0.9vw,0.85rem)] font-bold text-slate-500 dark:text-slate-300 uppercase tracking-wider flex-1">{item.name}</span>
                 <span className="text-[clamp(0.85rem,1.1vw,1rem)] font-bold text-slate-900 dark:text-white">{item.count} boleto{item.count !== 1 ? 's' : ''}</span>
               </div>
             ))}
           </div>
         </Card>

       </div>

       {/* Bottom Rows */}
       <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
         
         {/* Historical Flow */}
         <Card className="bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 shadow-xl p-6">
           <div className="flex justify-between items-center mb-6">
             <div className="space-y-1">
               <h3 className="text-lg font-bold text-slate-900 dark:text-white tracking-tight">Histórico de Fluxo</h3>
               <p className="text-[10px] font-bold text-slate-500 dark:text-slate-500 uppercase tracking-widest">Entradas vs Saídas</p>
             </div>
             <div className="flex items-center gap-3">
                <Select value={fluxoPeriodo} onValueChange={setFluxoPeriodo}>
                  <SelectTrigger className="w-[140px] h-8 text-xs font-bold uppercase tracking-wider bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-700">
                    <SelectValue placeholder="Período" />
                  </SelectTrigger>
                  <SelectContent className="z-[10000]">
                    <SelectItem value="0" className="text-xs font-bold uppercase">Mês Vigente</SelectItem>
                    <SelectItem value="1" className="text-xs font-bold uppercase">1 Mês Atrás</SelectItem>
                    <SelectItem value="2" className="text-xs font-bold uppercase">2 Meses Atrás</SelectItem>
                    <SelectItem value="3" className="text-xs font-bold uppercase">3 Meses Atrás</SelectItem>
                  </SelectContent>
                </Select>
                <Calendar className="w-4 h-4 text-slate-500" />
              </div>
           </div>
           
           <div className="h-[280px]">
             {loading ? (
               <div className="flex items-center justify-center h-full">
                 <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
               </div>
             ) : (
               <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                 <BarChart data={fluxoBarData} barGap={8}>
                   <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#64748b" opacity={0.2} />
                   <XAxis 
                     dataKey="name" 
                     axisLine={false} 
                     tickLine={false} 
                     tick={{fill: '#64748b', fontSize: 10, fontWeight: 700}} 
                   />
                    <YAxis 
                      axisLine={false} 
                      tickLine={false} 
                      tick={{fill: '#64748b', fontSize: 10}}
                      tickFormatter={(val) => `${(val/1000).toFixed(0)}k`}
                    />
                    <Tooltip 
                      cursor={{ fill: 'rgba(0,0,0,0.05)', opacity: 0.1 }}
                      content={<FinanceiroChartTooltip formatCurrency={formatCurrency} />}
                    />
                    <Bar dataKey="entradas" fill="#10b981" radius={[4, 4, 0, 0]} barSize={12} name="Entradas" />
                   <Bar dataKey="saidas" fill="#fb7185" radius={[4, 4, 0, 0]} barSize={12} name="Saídas" />
                 </BarChart>
               </ResponsiveContainer>
             )}
           </div>
         </Card>

         {/* Transactions List */}
         <Card className="bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 shadow-xl flex flex-col">
            <div className="p-6 border-b border-slate-200 dark:border-slate-800 flex justify-between items-center">
              <div>
                <h3 className="text-lg font-bold text-slate-900 dark:text-white tracking-tight">Movimentações</h3>
                <p className="text-[clamp(0.7rem,1vw,0.8rem)] font-bold text-slate-500 dark:text-slate-500 uppercase tracking-widest">Lançamentos Recentes</p>
              </div>
               <Button 
                variant="ghost" 
                className="text-[clamp(0.7rem,1vw,0.8rem)] font-bold uppercase text-emerald-600 dark:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10"
                onClick={() => setIsExtratoPopupOpen(true)}
              >
                Ver Extrato Completo
              </Button>
            </div>
            
            <div className="flex-1 overflow-y-auto max-h-[350px] custom-scrollbar">
              {loading ? (
                <div className="flex items-center justify-center py-12">
                   <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
                </div>
              ) : ultimasTransacoes.length > 0 ? (
                <div className="divide-y divide-slate-100 dark:divide-slate-800/50">
                  {ultimasTransacoes.map((t, i) => (
                    <div 
                      key={i} 
                      className="px-6 py-3 flex items-center justify-between hover:bg-slate-50 dark:hover:bg-slate-800/20 transition-colors group cursor-pointer"
                      onClick={() => handleTransactionClick(t)}
                    >
                      <div className="flex items-center gap-4">
                        <div className={cn(
                          "w-10 h-10 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105 shadow-sm",
                          t.tipoOperacao === 'C' ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-500" : "bg-rose-400/10 text-rose-500"
                        )}>
                          {t.tipoOperacao === 'C' ? <ArrowUpRight size={18} /> : <ArrowDownRight size={18} />}
                        </div>
                        <div className="flex flex-col">
                          <span className="text-xs font-bold text-slate-900 dark:text-white leading-tight min-w-[150px] truncate max-w-[240px]">
                            {t.descricao || 'Sem descrição'}
                          </span>
                          <div className="flex items-center gap-2 mt-1">
                            <span className="text-[clamp(0.7rem,1vw,0.8rem)] font-bold text-slate-500 uppercase tracking-wider bg-slate-100 dark:bg-slate-800 px-1.5 py-0.5 rounded">
                               {t.tipoTransacao || 'GERAL'} 
                            </span>
                            <span className="text-[clamp(0.7rem,1.1vw,0.8125rem)] text-slate-400">
                              {t.dataEntrada}
                            </span>
                          </div>
                          {(t.beneficiario_pagador) && (
                            <span className="text-[clamp(0.7rem,1.1vw,0.8125rem)] text-slate-400 dark:text-slate-500 truncate max-w-[200px] mt-0.5">
                              {t.beneficiario_pagador}
                            </span>
                          )}
                        </div>
                      </div>
                      
                      <div className="flex flex-col items-end gap-1">
                        <span className={cn(
                          "text-sm font-bold tracking-tight",
                          t.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-500" : "text-rose-500"
                        )}>
                          {t.tipoOperacao === 'C' ? '+' : '-'}{formatCurrency(t.valor)}
                        </span>
                        <div className="flex items-center gap-1">
                          {t.categoria && t.categoria != 0 ? (
                            <span className="text-[clamp(0.65rem,1vw,0.75rem)] font-bold px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-500 border border-emerald-500/20">
                              CONCILIADO
                            </span>
                          ) : (
                            <span className="text-[clamp(0.65rem,1vw,0.75rem)] font-bold px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-600 dark:text-amber-500 border border-amber-500/20">
                              PENDENTE
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-12 text-slate-500 italic text-sm">
                  Nenhuma movimentação recente
                </div>
              )}
            </div>
         </Card>
      </div>
      
      {/* Transaction Detail Modal */}
      {/* Transaction Detail Modal */}
      <TransactionDetailModal 
        transaction={selectedTransaction}
        open={detailsOpen}
        onOpenChange={setDetailsOpen}
        onEditTransaction={handleNavigateToConciliacao}
        onViewInExtrato={(transaction) => {
          if (transaction.tipoOperacao === 'C') {
             // Open Entradas modal
             const parsed = parseDateInfo(transaction.dataEntrada);
             const date = new Date(parsed.year || new Date().getFullYear(), (parsed.month || new Date().getMonth() + 1) - 1, parsed.day || 1);
             setModalDate(date);
             handleModalDateChange('saldo', date);
             setModalState(prev => ({ ...prev, saldo: true }));
          } else {
             // Open Saídas modal
             const parsed = parseDateInfo(transaction.dataEntrada);
             const date = new Date(parsed.year || new Date().getFullYear(), (parsed.month || new Date().getMonth() + 1) - 1, parsed.day || 1);
             setModalDate(date);
             handleModalDateChange('despesas', date);
             setModalState(prev => ({ ...prev, despesas: true }));
          }
        }}
        categorias={conciliacaoState?.categorias || []}
        caixas={conciliacaoState?.caixas || []}
      />

      {/* Modal - Saldo Disponível (Entradas do Mês) */}
      <Dialog open={modalState.saldo} onOpenChange={(open) => setModalState(prev => ({ ...prev, saldo: open }))}>
        <DialogContent className="max-w-4xl bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 z-[9999] flex flex-col max-h-[90vh]">
          <DialogHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <div className="space-y-1">
              <DialogTitle className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
                <ArrowUpRight className="text-emerald-500" />
                Entradas - {modalDate.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' })}
              </DialogTitle>
              <DialogDescription className="text-slate-500">
                Visualização detalhada de todos os créditos recebidos no período selecionado.
              </DialogDescription>
            </div>
            <div className="flex items-center gap-2">
               <span className="text-xs font-bold text-slate-500 uppercase tracking-widest hidden sm:block">Período:</span>
               <input
                  type="month"
                  className="bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-md px-3 py-1 text-sm font-bold text-slate-700 dark:text-slate-300 focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
                  value={modalDate.toISOString().slice(0, 7)}
                  onChange={(e) => {
                    if (e.target.value) {
                      const [y, m] = e.target.value.split('-').map(Number);
                      const newDate = new Date(y, m - 1);
                      setModalDate(newDate);
                      handleModalDateChange('saldo', newDate);
                    }
                  }}
               />
            </div>
          </DialogHeader>
          <div className="flex-1 h-[clamp(300px,60vh,600px)] overflow-auto custom-scrollbar">
            <ExcelTable 
              data={modalData.saldo}
              loading={modalLoading}
              columns={[
                { 
                  header: '', 
                  field: 'tipoOperacao', 
                  width: 50, 
                  render: (row) => (
                    <div className="w-8 h-8 rounded-lg flex items-center justify-center bg-emerald-500/10 text-emerald-600">
                      <ArrowUpRight size={14} />
                    </div>
                  )
                },
                { header: 'Data', field: 'dataEntrada', width: 120, render: (row) => (
                  <span className="text-slate-500 font-medium">{row.dataEntrada}</span>
                )},
                { header: 'Descrição', field: 'descricao', width: 250, render: (row) => (
                  <span className="font-bold text-slate-900 dark:text-white">{row.descricao || 'Sem descrição'}</span>
                )},
                { header: 'Categoria', field: 'categoriaNome', width: 150, render: (row) => (
                  <Badge variant="outline" className="text-[clamp(0.7rem,1vw,0.8125rem)] font-bold uppercase tracking-widest bg-emerald-500/5 text-emerald-500 border-emerald-500/20">
                    {row.categoriaNome || 'Sem Categoria'}
                  </Badge>
                )},
                { header: 'Valor', field: 'valor', width: 120, render: (row) => (
                  <span className="font-bold text-emerald-600 dark:text-emerald-400">{formatCurrency(row.valor)}</span>
                )}
              ]}
            />
          </div>
          <div className="flex justify-end p-4 bg-slate-50 dark:bg-slate-900/40 rounded-xl shrink-0">
            <div className="text-right">
              <p className="text-[clamp(0.7rem,1vw,0.8125rem)] font-bold text-slate-500 uppercase tracking-widest">Total de Entradas</p>
              <p className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                {formatCurrency(modalData.saldo.reduce((acc, curr) => acc + (Number(curr.valor) || 0), 0))}
              </p>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Modal - Despesas (Saídas do Mês) */}
      <Dialog open={modalState.despesas} onOpenChange={(open) => setModalState(prev => ({ ...prev, despesas: open }))}>
        <DialogContent className="max-w-4xl bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 z-[9999] flex flex-col max-h-[90vh]">
          <DialogHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
             <div className="space-y-1">
                <DialogTitle className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
                  <ArrowDownRight className="text-rose-400" />
                  Saídas - {modalDate.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' })}
                </DialogTitle>
                <DialogDescription className="text-slate-500">
                  Detalhamento de todos os pagamentos e débitos efetuados no período selecionado.
                </DialogDescription>
             </div>
             <div className="flex items-center gap-2">
               <span className="text-xs font-bold text-slate-500 uppercase tracking-widest hidden sm:block">Período:</span>
               <input
                  type="month"
                  className="bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-md px-3 py-1 text-sm font-bold text-slate-700 dark:text-slate-300 focus:outline-none focus:ring-2 focus:ring-rose-400/50"
                  value={modalDate.toISOString().slice(0, 7)}
                  onChange={(e) => {
                    if (e.target.value) {
                      const [y, m] = e.target.value.split('-').map(Number);
                      const newDate = new Date(y, m - 1);
                      setModalDate(newDate);
                      handleModalDateChange('despesas', newDate);
                    }
                  }}
               />
            </div>
          </DialogHeader>
          <div className="flex-1 h-[clamp(300px,60vh,600px)] overflow-auto custom-scrollbar">
            <ExcelTable 
              data={modalData.despesas}
              loading={modalLoading}
              columns={[
                { 
                  header: '', 
                  field: 'tipoOperacao', 
                  width: 50, 
                  render: (row) => (
                    <div className="w-8 h-8 rounded-lg flex items-center justify-center bg-rose-400/10 text-rose-500">
                      <ArrowDownRight size={14} />
                    </div>
                  )
                },
                { header: 'Data', field: 'dataEntrada', width: 120, render: (row) => (
                  <span className="text-slate-500 font-medium">{row.dataEntrada}</span>
                )},
                { header: 'Favorecido', field: 'beneficiario_pagador', width: 200, render: (row) => (
                  <span className="font-bold text-slate-900 dark:text-white">{row.beneficiario_pagador || 'N/A'}</span>
                )},
                { header: 'Categoria', field: 'categoriaNome', width: 150, render: (row) => (
                  <Badge variant="outline" className="text-[clamp(0.7rem,1vw,0.8125rem)] font-bold uppercase tracking-widest bg-rose-400/5 text-rose-500 border-rose-400/20">
                    {row.categoriaNome || 'Sem Categoria'}
                  </Badge>
                )},
                { header: 'Descrição', field: 'descricao', width: 200 },
                { header: 'Valor', field: 'valor', width: 120, render: (row) => (
                  <span className="font-bold text-red-600 dark:text-red-400">{formatCurrency(row.valor)}</span>
                )}
              ]}
            />
          </div>
          <div className="flex justify-end p-4 bg-slate-50 dark:bg-slate-900/40 rounded-xl shrink-0">
            <div className="text-right">
              <p className="text-[clamp(0.7rem,1vw,0.8125rem)] font-bold text-slate-500 uppercase tracking-widest">Total de Saídas</p>
              <p className="text-2xl font-bold text-rose-500">
                {formatCurrency(modalData.despesas.reduce((acc, curr) => acc + (Number(curr.valor) || 0), 0))}
              </p>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Modal - Transações Não Conciliadas */}
      <Dialog open={modalState.naoConciliadas} onOpenChange={(open) => setModalState(prev => ({ ...prev, naoConciliadas: open }))}>
        <DialogContent className="max-w-5xl bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 z-[9999] flex flex-col max-h-[90vh]">
          <DialogHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <div className="space-y-1">
              <DialogTitle className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
                <AlertCircle className="text-amber-500" />
                Transações Pendentes de Conciliação
              </DialogTitle>
              <DialogDescription className="text-slate-500">
                Movimentações do extrato que ainda não foram categorizadas ou vinculadas a um lançamento no mês selecionado.
              </DialogDescription>
            </div>
            <div className="flex items-center gap-2">
               <span className="text-xs font-bold text-slate-500 uppercase tracking-widest hidden sm:block">Período:</span>
               <input
                  type="month"
                  className="bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-md px-3 py-1 text-sm font-bold text-slate-700 dark:text-slate-300 focus:outline-none focus:ring-2 focus:ring-amber-500/50"
                  value={modalDate.toISOString().slice(0, 7)}
                  onChange={(e) => {
                    if (e.target.value) {
                      const [y, m] = e.target.value.split('-').map(Number);
                      const newDate = new Date(y, m - 1);
                      setModalDate(newDate);
                      handleModalDateChange('naoConciliadas', newDate);
                    }
                  }}
               />
            </div>
          </DialogHeader>
          <div className="flex-1 h-[clamp(300px,60vh,600px)] overflow-auto custom-scrollbar">
             <ExcelTable 
              data={modalData.naoConciliadas}
              loading={modalLoading}
              onRowClick={handleTransactionClick}
              columns={[
                { 
                  header: '', 
                  field: 'tipoOperacao', 
                  width: 50, 
                  render: (row) => (
                    <div className={cn(
                      "w-8 h-8 rounded-lg flex items-center justify-center",
                      row.tipoOperacao === 'C' ? "bg-emerald-500/10 text-emerald-600" : "bg-red-500/10 text-red-600"
                    )}>
                      {row.tipoOperacao === 'C' ? <ArrowUpRight size={14} /> : <ArrowDownRight size={14} />}
                    </div>
                  )
                },
                { header: 'Data', field: 'dataEntrada', width: 120, render: (row) => (
                  <span className="text-slate-500 font-medium">{formatDate(row.dataEntrada)}</span>
                )},
                { header: 'Descrição', field: 'descricao', width: 250, render: (row) => (
                  <span className="font-bold text-slate-900 dark:text-white">{row.descricao || 'Sem descrição'}</span>
                )},
                { header: 'Tipo', field: 'tipoTransacao', width: 100, render: (row) => (
                  <span className="text-[clamp(0.7rem,1vw,0.8125rem)] font-bold text-slate-500 uppercase tracking-wider bg-slate-100 dark:bg-slate-800 px-1.5 py-0.5 rounded">
                    {row.tipoTransacao || 'GERAL'}
                  </span>
                )},
                { header: 'Ben./Pag.', field: 'beneficiario_pagador', width: 200 },
                { header: 'Valor', field: 'valor', width: 120, render: (row) => (
                  <span className={cn(
                    "font-bold",
                    row.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400"
                  )}>
                    {row.tipoOperacao === 'C' ? '+' : '-'}{formatCurrency(row.valor)}
                  </span>
                )},
                { header: 'Status', field: 'status', width: 120, render: () => (
                  <Badge className="bg-amber-500/10 text-amber-500 border-amber-500/20 text-[clamp(0.7rem,1vw,0.8125rem)] font-bold">PENDENTE</Badge>
                )}
              ]}
            />
          </div>
          <DialogFooter className="bg-slate-50 dark:bg-slate-900/40 p-4 rounded-b-xl border-t border-slate-200 dark:border-slate-800 shrink-0">
             {/* <Button 
               variant="default" 
               className="bg-emerald-600 hover:bg-emerald-500 text-white font-bold uppercase tracking-widest text-xs"
               onClick={() => onNavigate && onNavigate('conciliacao/pendentes')}
             >
                Ir para Conciliação Completa
             </Button> */}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Modal - Boletos em Aberto */}
      <Dialog open={modalState.boletosAbertos} onOpenChange={(open) => setModalState(prev => ({ ...prev, boletosAbertos: open }))}>
        <DialogContent className="max-w-5xl bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 z-[9999] flex flex-col max-h-[90vh]">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
              <CreditCard className="text-blue-500" />
              Boletos em Aberto / Pendentes
            </DialogTitle>
            <DialogDescription className="text-slate-500">
              Cobranças com vencimento no período que ainda não foram liquidadas.
            </DialogDescription>
          </DialogHeader>
          <div className="flex-1 h-[clamp(300px,60vh,600px)] overflow-auto custom-scrollbar">
            <ExcelTable 
              data={modalData.boletosAbertos}
              loading={modalLoading}
              columns={[
                { header: 'Número', field: 'seuNumero', width: 120, render: (row) => {
                  const c = row.cobranca || row;
                  return `#${c.seuNumero || c.id}`;
                }},
                { header: 'Cliente', field: 'nome', width: 250, render: (row) => {
                  const c = row.cobranca || row;
                  return c.nome || c.pagadorNome || c.clienteNome || 'Desconhecido';
                }},
                { header: 'Emissão', field: 'dataEmissao', width: 120, render: (row) => {
                  const c = row.cobranca || row;
                  return formatDate(c.dataEmissao);
                }},
                { header: 'Vencimento', field: 'dataVencimento', width: 120, render: (row) => {
                  const c = row.cobranca || row;
                  return formatDate(c.dataVencimento);
                }},
                { header: 'Valor', field: 'valorNominal', width: 120, render: (row) => {
                  const c = row.cobranca || row;
                  return <span className="font-bold text-blue-600 dark:text-blue-400">{formatCurrency(c.valorNominal || c.valorTotal)}</span>;
                }},
                { header: 'Situação', field: 'situacao', width: 120, render: (row) => {
                  const c = row.cobranca || row;
                  return (
                    <Badge className={cn(
                      "text-[9px] font-bold uppercase tracking-tighter",
                      c.situacao === 'ATRASADO' ? "bg-red-500/10 text-red-500" : "bg-blue-500/10 text-blue-500"
                    )}>
                      {c.situacao}
                    </Badge>
                  );
                }}
              ]}
            />
          </div>
          <DialogFooter className="bg-slate-50 dark:bg-slate-900/40 p-4 -mx-6 -mb-6 rounded-b-xl border-t border-slate-200 dark:border-slate-800 flex justify-between shrink-0">
             <div className="text-left">
                <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Total em Aberto</p>
                <p className="text-xl font-bold text-blue-600 dark:text-blue-400">
                  {formatCurrency(modalData.boletosAbertos.reduce((acc, curr) => acc + (Number(curr.cobranca?.valorNominal || curr.valorNominal || 0)), 0))}
                </p>
             </div>
             {/* <Button 
               variant="outline" 
               className="border-slate-200 text-slate-700 h-10 px-6 font-bold uppercase text-[10px]"
               onClick={() => onNavigate && onNavigate('receber/boletos-pendentes')}
             >
                Gerenciar Todos os Boletos
             </Button> */}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Modal - Detalhamento de Juros Adicionados */}
      <Dialog open={modalState.adicionado} onOpenChange={(open) => setModalState(prev => ({ ...prev, adicionado: open }))}>
        <DialogContent className="max-w-5xl bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 z-[9999] flex flex-col max-h-[90vh]">
          <DialogHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <div className="space-y-1">
              <DialogTitle className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
                <TrendingUp className="text-blue-500" />
                Juros Adicionados - {jurosDetailPeriodo === 'mes' ? `${MESES_REC[Number(jurosDetailMes)]} / ${jurosDetailAno}` : jurosDetailAno}
              </DialogTitle>
              <DialogDescription className="text-slate-500">
                Detalhamento dos juros e acréscimos identificados no período.
              </DialogDescription>
            </div>
            <div className="flex items-center gap-2">
               <span className="text-xs font-bold text-slate-500 uppercase tracking-widest hidden sm:block">Período:</span>
               
               <Select value={jurosDetailPeriodo} onValueChange={(val) => {
                 setJurosDetailPeriodo(val);
                 fetchDataForModal('adicionado', { mes: val === 'ano' ? null : jurosDetailMes, ano: jurosDetailAno });
               }}>
                  <SelectTrigger className="h-8 w-[100px] bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-xs font-semibold">
                      <SelectValue placeholder="Tipo" />
                  </SelectTrigger>
                  <SelectContent className="z-[10001]">
                      <SelectItem value="mes">Mensal</SelectItem>
                      <SelectItem value="ano">Anual</SelectItem>
                  </SelectContent>
               </Select>

               {jurosDetailPeriodo === 'mes' && (
                 <Select value={jurosDetailMes} onValueChange={(val) => {
                   setJurosDetailMes(val);
                   fetchDataForModal('adicionado', { mes: val, ano: jurosDetailAno });
                 }}>
                    <SelectTrigger className="h-8 w-[120px] bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-xs font-semibold">
                        <SelectValue placeholder="Mês" />
                    </SelectTrigger>
                    <SelectContent className="z-[10001]">
                        {MESES_REC.map((m, i) => (i === 0 ? null : <SelectItem key={i} value={String(i)}>{m}</SelectItem>))}
                    </SelectContent>
                 </Select>
               )}

               <Select value={jurosDetailAno} onValueChange={(val) => {
                 setJurosDetailAno(val);
                 fetchDataForModal('adicionado', { mes: jurosDetailPeriodo === 'ano' ? null : jurosDetailMes, ano: val });
               }}>
                  <SelectTrigger className="h-8 w-[90px] bg-white dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-xs font-semibold">
                      <SelectValue placeholder="Ano" />
                  </SelectTrigger>
                  <SelectContent className="z-[10001]">
                      {ANOS_REC.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                  </SelectContent>
               </Select>
            </div>
          </DialogHeader>
          <div className="flex-1 h-[clamp(300px,60vh,600px)] overflow-auto custom-scrollbar">
            <ExcelTable 
              data={modalData.adicionado.lista}
              loading={modalLoading}
              columns={[
                { header: 'Data', field: 'dataEntrada', width: 120, render: (row) => (
                  <span className="text-slate-500 font-medium">{formatDate(row.dataEntrada)}</span>
                )},
                { header: 'Beneficiário/Pagador', field: 'beneficiario_pagador', width: 250, render: (row) => (
                  <span className="font-bold text-slate-900 dark:text-white">{row.beneficiario_pagador || 'N/A'}</span>
                )},
                { header: 'Descrição', field: 'descricao', width: 300 },
                { header: 'Tipo', field: 'tipoTransacao', width: 120, render: (row) => (
                  <Badge variant="outline" className="text-[10px] font-bold uppercase tracking-widest bg-slate-100 dark:bg-slate-800 text-slate-500">
                    {row.tipoTransacao || 'GERAL'}
                  </Badge>
                )},
                { header: 'Valor (Juros)', field: 'adicionado', width: 120, render: (row) => (
                  <span className="font-bold text-blue-600 dark:text-blue-400">{formatCurrency(row.adicionado)}</span>
                )},
                { header: 'Valor Total', field: 'valor', width: 120, render: (row) => (
                  <span className="text-slate-500">{formatCurrency(row.valor)}</span>
                )}
              ]}
            />
          </div>
          <DialogFooter className="bg-slate-50 dark:bg-slate-900/40 p-4 -mx-6 -mb-6 rounded-b-xl border-t border-slate-200 dark:border-slate-800 flex justify-between shrink-0">
             <div className="text-left">
                <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Total de Juros Adicionados</p>
                <div className="flex items-baseline gap-2">
                  <p className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                    {formatCurrency(modalData.adicionado.total_adicionado)}
                  </p>
                  <span className="text-xs text-slate-400 font-medium">({modalData.adicionado.total_registros} registros)</span>
                </div>
             </div>
             {/* <Button 
               variant="outline" 
               className="border-slate-200 text-slate-700 h-10 px-6 font-bold uppercase text-[10px]"
               onClick={() => setModalState(prev => ({ ...prev, adicionado: false }))}
             >
                Fechar
             </Button> */}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Modal - Extrato Completo em Popup */}
      <Dialog open={isExtratoPopupOpen} onOpenChange={setIsExtratoPopupOpen}>
        <DialogContent className="max-w-[95vw] w-[1400px] bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 z-[9999] flex flex-col max-h-[90vh] p-0 overflow-hidden">
          <DialogHeader className="sr-only">
            <DialogTitle>Extrato Completo</DialogTitle>
            <DialogDescription>Visualização detalhada do extrato bancário com filtros de período e categorias.</DialogDescription>
          </DialogHeader>
          <div className="p-6 overflow-y-auto custom-scrollbar">
            <ExtratoCompletoView 
              state={conciliacaoState} 
              actions={{
                ...conciliacaoActions,
                // Override onclick behavior if needed or just use standard actions
              }} 
            />
          </div>
        </DialogContent>
      </Dialog>

      {/* Dialog de Categorização Direta */}
      <CategorizacaoDialog 
        transacao={selectedTransaction}
        isOpen={isCategorizacaoOpen}
        onOpenChange={setIsCategorizacaoOpen}
        categorias={conciliacaoState?.categorias}
        caixas={conciliacaoState?.caixas}
        actions={{
          ...conciliacaoActions,
          categorizarTransacao: async (id, data) => {
            const success = await conciliacaoActions.categorizarTransacao(id, data);
            if (success) {
              // Reload dashboard data to reflect changes
              fetchDataForModal('naoConciliadas', modalDate);
              if (typeof reload === 'function') reload();
            }
            return success;
          }
        }}
      />
    </div>
   );
 };
