import React, { useState, useMemo } from 'react';
import { 
  Receipt, 
  Search,
  Download,
  Send,
  Calendar,
  FileText,
  Filter,
  MoreHorizontal,
  CheckCircle2,
  Clock,
  XCircle,
  Plus,
  CalendarCheck,
  Edit,
  Trash2,
  AlertCircle,
  Loader2
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardHeader, CardContent } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { ItemDetailPanel } from '@/components/shared/ItemDetailPanel/ItemDetailPanel';
import { useBoletos } from '../../hooks/useBoletos';
import { boletosService } from '@/services/boletosService';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import ExcelTable from '../../components/ExcelTable';
import { ScrollArea } from '@/components/ui/scroll-area';
import { formatDate, formatCurrency, formatStatus } from '../../utils/dateUtils';
import { BoletoCreationDialog } from '../../components/BoletoCreationDialog';

const TIPOS_BOLETO = [
    'Todos os Tipos',
    'SIMPLES',
    'RECORRENTE',
    'PIX',
    'Boleto Bancário',
    'Boleto Registrado'
];

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

/** Formata YYYY-MM para "Janeiro de 2026" */
const formatPeriodoLabel = (yyyyMm) => {
    if (!yyyyMm || yyyyMm.length < 7) return 'Todos os períodos';
    const [y, m] = yyyyMm.split('-');
    const mesIdx = parseInt(m?.replace(/^0+/, '') || '1', 10);
    return `${MESES_NOME[mesIdx] || m} de ${y}`;
};

export const BoletosView = ({ initialFilter = 'TODOS' }) => {
    const { state, actions } = useBoletos();
    const boletos = state?.boletos || [];
    const stats = state?.stats || {
        atrasado: { valor: 0, total: 0 },
        cancelado: { valor: 0, total: 0 },
        recebido: { valor: 0, total: 0 },
        marcadoRecebido: { valor: 0, total: 0 },
        pix: { valor: 0, total: 0 }
    };
    const isLoading = state?.isLoading || false;
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedTipo, setSelectedTipo] = useState('Todos os Tipos');
    const [selectedStatus, setSelectedStatus] = useState(initialFilter);
    const [isScheduleDialogOpen, setIsScheduleDialogOpen] = useState(false);
    const [selectedBoleto, setSelectedBoleto] = useState(null);
    const [newDate, setNewDate] = useState('');
    const [dateRange, setDateRange] = useState({ inicio: '', fim: '' });
    const filterMonth = state?.filterMonth || '';
    const empresas = state?.empresas || [];
    const isCreating = state?.isCreating || false;
    const [isDetailPanelOpen, setIsDetailPanelOpen] = useState(false);
    
    // Estado para cancelamento
    const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false);
    const [boletoToCancel, setBoletoToCancel] = useState(null);
    const [cancelReason, setCancelReason] = useState('');
    const [processingCancellation, setProcessingCancellation] = useState(false);

    // Estados para criação de boleto
    const [isCreationDialogOpen, setIsCreationDialogOpen] = useState(false);
    const [creationMode, setCreationMode] = useState('AVULSO');

    const handleOpenCreationDialog = (mode) => {
        setCreationMode(mode);
        setIsCreationDialogOpen(true);
    };
    const handleCreateBoleto = async (formData, mode) => {
        console.log('[BoletosView] Enviando boleto:', { formData, mode });
        let success = false;
        if (mode === 'AGENDAMENTO') {
            success = await actions?.agendarBoletosGlobal(formData);
        } else {
            success = await actions?.createBoleto(formData, mode);
        }
        
        if (success) {
            setIsCreationDialogOpen(false);
        }
    };

    // Filtro por mês: mesmo critério dos cards (vencimento no mês selecionado)
    const monthStr = (dateStr) => {
        if (!dateStr) return '';
        const d = String(dateStr).slice(0, 7);
        return d.length === 7 ? d : '';
    };

    const filteredBoletos = useMemo(() => {
        return boletos.filter(b => {
            // Filtro de mês/ano: sempre aplicado quando há período selecionado (vencimento no mês/ano).
            const bMonth = monthStr(b.vencimento || b.dataVencimento);
            const matchMonth = !filterMonth || bMonth === filterMonth;

            const matchSearch = !searchTerm ||
                               b.pagador?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                               b.cliente?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                               (b.numero && String(b.numero).toLowerCase().includes(searchTerm.toLowerCase())) ||
                               b.codigoSolicitacao?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                               b.seuNumero?.toLowerCase().includes(searchTerm.toLowerCase());
            const matchTipo = selectedTipo === 'Todos os Tipos' || 
                             b.tipoCobranca === selectedTipo || 
                             b.tipo === selectedTipo ||
                             (selectedTipo === 'SIMPLES' && b.tipoCobranca === 'SIMPLES') ||
                             (selectedTipo === 'RECORRENTE' && b.tipoCobranca === 'RECORRENTE') ||
                             (selectedTipo === 'PIX' && (b.status === 'PIX' || b.tipoCobranca === 'PIX'));
            
            let matchStatus = selectedStatus === 'TODOS';
            if (selectedStatus === 'VENCIDO') {
                matchStatus = b.status === 'ATRASADO' || b.status === 'VENCIDO';
            } else if (selectedStatus === 'RECEBIDO') {
                matchStatus = b.status === 'RECEBIDO' || b.status === 'PAGO';
            } else if (selectedStatus === 'ATRASADO') {
                matchStatus = b.status === 'ATRASADO' || b.status === 'VENCIDO';
            } else {
                matchStatus = b.status === selectedStatus;
            }
            
            let matchDate = true;
            if (dateRange.inicio && (b.emitido || b.dataEmissao)) {
                const dataEmitido = new Date(b.emitido || b.dataEmissao);
                const dataInicio = new Date(dateRange.inicio);
                if (dataEmitido < dataInicio) matchDate = false;
            }
            if (dateRange.fim && (b.emitido || b.dataEmissao)) {
                const dataEmitido = new Date(b.emitido || b.dataEmissao);
                const dataFim = new Date(dateRange.fim);
                if (dataEmitido > dataFim) matchDate = false;
            }
            
            return matchMonth && matchSearch && matchTipo && matchStatus && matchDate;
        });
    }, [boletos, filterMonth, searchTerm, selectedTipo, selectedStatus, dateRange]);

    // Log: somas da tabela (filteredBoletos) vs stats dos cards — para conferir divergências
    const LOG_PREFIX_BOLETOS = '[Boletos/Somas]';
    const somasTabela = useMemo(() => {
        const porStatus = {};
        let totalGeralValor = 0;
        let totalGeralCount = 0;
        for (const b of filteredBoletos) {
            const s = b.status || 'PENDENTE';
            if (!porStatus[s]) porStatus[s] = { count: 0, valor: 0 };
            const v = Number(b.totalRecebido ?? b.valorNominal ?? b.valor ?? 0);
            porStatus[s].count += 1;
            porStatus[s].valor += v;
            totalGeralValor += v;
            totalGeralCount += 1;
        }
        return { porStatus, totalGeralValor, totalGeralCount };
    }, [filteredBoletos]);

    React.useEffect(() => {
        const { porStatus } = somasTabela;
        const tabelaAtrasado = {
            count: (porStatus['ATRASADO']?.count || 0) + (porStatus['VENCIDO']?.count || 0),
            valor: (porStatus['ATRASADO']?.valor || 0) + (porStatus['VENCIDO']?.valor || 0)
        };
        const tabelaRecebido = {
            count: (porStatus['RECEBIDO']?.count || 0) + (porStatus['PAGO']?.count || 0),
            valor: (porStatus['RECEBIDO']?.valor || 0) + (porStatus['PAGO']?.valor || 0)
        };
        console.log(LOG_PREFIX_BOLETOS, 'Tabela (filteredBoletos):', {
            filterMonth,
            count: filteredBoletos.length,
            somasPorStatus: porStatus,
            totalGeralValor: somasTabela.totalGeralValor,
            totalGeralCount: somasTabela.totalGeralCount
        });
        console.log(LOG_PREFIX_BOLETOS, 'Cards vs Tabela (comparação):', {
            atrasado: { cards: stats.atrasado, tabela: tabelaAtrasado, bate: stats.atrasado.total === tabelaAtrasado.count && Math.abs((stats.atrasado.valor || 0) - tabelaAtrasado.valor) < 0.02 },
            cancelado: { cards: stats.cancelado, tabela: porStatus['CANCELADO'] || { count: 0, valor: 0 }, bate: stats.cancelado.total === (porStatus['CANCELADO']?.count || 0) },
            recebido: { cards: stats.recebido, tabela: tabelaRecebido, bate: stats.recebido.total === tabelaRecebido.count && Math.abs((stats.recebido.valor || 0) - tabelaRecebido.valor) < 0.02 },
            marcadoRecebido: { cards: stats.marcadoRecebido, tabela: porStatus['MARCADO_RECEBIDO'] || { count: 0, valor: 0 }, bate: stats.marcadoRecebido.total === (porStatus['MARCADO_RECEBIDO']?.count || 0) },
            pix: { cards: stats.pix, tabela: porStatus['PIX'] || { count: 0, valor: 0 }, bate: stats.pix.total === (porStatus['PIX']?.count || 0) }
        });
    }, [filterMonth, filteredBoletos.length, stats, somasTabela]);

    const handleDownloadBoleto = async (codigoSolicitacao) => {
        if (!codigoSolicitacao) {
            toast.error('Código de solicitação não encontrado');
            return;
        }
        try {
            const blob = await boletosService.downloadBoletoPDF(codigoSolicitacao);
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `Boleto_${codigoSolicitacao}.pdf`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            toast.success('Boleto baixado com sucesso');
        } catch (err) {
            console.error('Erro ao baixar boleto:', err);
            toast.error('Erro ao baixar boleto');
        }
    };

    const handleSendBoleto = async (codigoSolicitacao, pagadorNome) => {
        if (!codigoSolicitacao) {
            toast.error('Código de solicitação não encontrado');
            return;
        }
        try {
            // Busca empresa pelo nome do pagador
            const empresas = await boletosService.fetchEmpresas();
            const empresa = empresas.find(e => e.nome === pagadorNome || e.nome_exibicao === pagadorNome);
            
            if (!empresa) {
                toast.error('Empresa não encontrada');
                return;
            }

            await boletosService.enviarBoletoEmail({
                codigoSolicitacao: codigoSolicitacao,
                idempresa: empresa.idempresa || empresa.id
            });
            
            toast.success('Email enviado com sucesso');
        } catch (err) {
            console.error('Erro ao enviar email:', err);
            toast.error('Erro ao enviar email');
        }
    };

    const handleOpenScheduleDialog = (boleto) => {
        setSelectedBoleto(boleto);
        setNewDate(boleto.vencimento || boleto.dataVencimento);
        setIsScheduleDialogOpen(true);
    };

    const handleSchedule = async () => {
        if (selectedBoleto && newDate) {
            // Tenta encontrar o id da empresa real (idempresa) pelo nome ou CPF/CNPJ se não estiver no objeto
            let finalIdEmpresa = selectedBoleto.idempresa || selectedBoleto.id_empresa;
            
            // Se o idempresa for igual ao codigoSolicitacao, está errado (foi fallback do 'id')
            if (!finalIdEmpresa || finalIdEmpresa === selectedBoleto.codigoSolicitacao) {
                const pagadorNome = selectedBoleto.nome || selectedBoleto.pagador || selectedBoleto.cliente;
                const pagadorDoc = selectedBoleto.cpfCnpj;
                
                const empresaEncontrada = state.empresas?.find(e => 
                    (pagadorNome && (e.nome === pagadorNome || e.nome_exibicao === pagadorNome)) ||
                    (pagadorDoc && e.cpf_cnpj === pagadorDoc)
                );
                
                if (empresaEncontrada) {
                    finalIdEmpresa = empresaEncontrada.idempresa || empresaEncontrada.id;
                }
            }

            const success = await actions?.scheduleBoleto({
                codigoSolicitacao: selectedBoleto.codigoSolicitacao,
                data_vencimento: `${newDate} 09:00`,
                data_execucao: `${newDate} 09:00`,
                idempresa: finalIdEmpresa
            });
            if (success) {
                setIsScheduleDialogOpen(false);
                setSelectedBoleto(null);
                setNewDate('');
            }
        }
    };

    const handleDownloadFatura = (boletoId) => {
        actions?.downloadFatura(boletoId);
        // Simulação de download fatura
        console.log('Download fatura:', boletoId);
    };

    const getStatusBadge = (status) => {
        const statusConfig = {
            'PAGO': { className: 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20', icon: CheckCircle2, label: 'Pago' },
            'RECEBIDO': { className: 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20', icon: CheckCircle2, label: 'Recebido' },
            'A_RECEBER': { className: 'bg-blue-500/10 text-blue-500 border-blue-500/20', icon: Clock, label: 'A Receber' },
            'PENDENTE': { className: 'bg-blue-500/10 text-blue-500 border-blue-500/20', icon: Clock, label: 'A Receber' },
            'VENCIDO': { className: 'bg-red-500/10 text-red-500 border-red-500/20', icon: XCircle, label: 'Atrasado' },
            'ATRASADO': { className: 'bg-red-500/10 text-red-500 border-red-500/20', icon: XCircle, label: 'Atrasado' },
            'CANCELADO': { className: 'bg-slate-500/10 text-slate-400 border-slate-500/20', icon: XCircle, label: 'Cancelado' },
            'MARCADO_RECEBIDO': { className: 'bg-orange-500/10 text-orange-500 border-orange-500/20', icon: CheckCircle2, label: 'Marcado Recebido' },
            'PIX': { className: 'bg-blue-500/10 text-blue-500 border-blue-500/20', icon: Receipt, label: 'Pix' },
        };
        const config = statusConfig[status] || { className: 'bg-slate-500/10 text-slate-400 border-slate-500/20', icon: Clock, label: status };
        const Icon = config.icon;
        return (
            <Badge className={cn("text-[9px] font-bold tracking-widest uppercase px-2 py-0.5 rounded-sm", config.className)}>
                <Icon className="w-2.5 h-2.5 mr-1" />
                {config.label || status}
            </Badge>
        );
    };

    const handleOpenCancelDialog = (boleto) => {
        setBoletoToCancel(boleto);
        setCancelReason('');
        setIsCancelDialogOpen(true);
    };

    const handleConfirmCancellation = async () => {
        if (!boletoToCancel || !cancelReason.trim()) {
            toast.error('Informe o motivo do cancelamento');
            return;
        }

        setProcessingCancellation(true);
        try {
            await boletosService.cancelarBoleto({
                codigoSolicitacao: boletoToCancel.codigoSolicitacao,
                motivoCancelamento: cancelReason
            });
            toast.success('Solicitação de cancelamento enviada');
            setIsCancelDialogOpen(false);
            setBoletoToCancel(null);
            actions?.loadBoletos(); // Recarrega a lista
        } catch (err) {
            console.error('Erro ao cancelar boleto:', err);
            toast.error('Erro ao cancelar boleto');
        } finally {
            setProcessingCancellation(false);
        }
    };

    return (
        <div className="space-y-4 sm:space-y-6 animate-in fade-in duration-700">
            {/* Cards de Resumo do Mês */}
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-2.5 sm:gap-3 md:gap-4">
                {/* Card A Receber */}
                <Card 
                    className={cn(
                        "bg-white dark:bg-slate-900/50 border-2 shadow-lg rounded-lg sm:rounded-xl overflow-hidden cursor-pointer transition-all hover:scale-[1.02] sm:hover:scale-105 active:scale-[0.98]",
                        selectedStatus === 'A_RECEBER' 
                            ? "border-blue-500 dark:border-blue-500 ring-2 ring-blue-500/20" 
                            : "border-slate-300 dark:border-slate-800 hover:border-blue-500/50"
                    )}
                    onClick={() => setSelectedStatus(selectedStatus === 'A_RECEBER' ? 'TODOS' : 'A_RECEBER')}
                >
                    <CardContent className="p-2.5 sm:p-3 md:p-4">
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                            <Clock className="w-3.5 h-3.5 sm:w-4 sm:h-4 md:w-5 md:h-5 text-blue-600 dark:text-blue-400 shrink-0" />
                            <Badge className="bg-blue-100 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-500/20 text-[9px] sm:text-[10px] md:text-xs px-1.5 py-0.5">
                                {stats.a_receber.total}
                            </Badge>
                        </div>
                        <p className="text-lg sm:text-xl md:text-2xl font-bold text-blue-600 dark:text-blue-400 mb-0.5 sm:mb-1 leading-tight">
                            {formatCurrency(stats.a_receber.valor)}
                        </p>
                        <p className="text-[9px] sm:text-[10px] md:text-xs text-slate-600 dark:text-slate-400 font-medium leading-tight">
                            Boletos em aberto para este mês
                        </p>
                    </CardContent>
                </Card>

                {/* Card Atrasado */}
                <Card 
                    className={cn(
                        "bg-white dark:bg-slate-900/50 border-2 shadow-lg rounded-lg sm:rounded-xl overflow-hidden cursor-pointer transition-all hover:scale-[1.02] sm:hover:scale-105 active:scale-[0.98]",
                        selectedStatus === 'ATRASADO' 
                            ? "border-red-500 dark:border-red-500 ring-2 ring-red-500/20" 
                            : "border-red-200 dark:border-red-900/20 hover:border-red-500/50"
                    )}
                    onClick={() => setSelectedStatus(selectedStatus === 'ATRASADO' ? 'TODOS' : 'ATRASADO')}
                >
                    <CardContent className="p-2.5 sm:p-3 md:p-4">
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                            <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 md:w-5 md:h-5 text-red-600 dark:text-red-400 shrink-0" />
                            <Badge className="bg-red-100 dark:bg-red-500/10 text-red-700 dark:text-red-400 border-red-200 dark:border-red-500/20 text-[9px] sm:text-[10px] md:text-xs px-1.5 py-0.5">
                                {stats.atrasado.total}
                            </Badge>
                        </div>
                        <p className="text-lg sm:text-xl md:text-2xl font-bold text-red-600 dark:text-red-400 mb-0.5 sm:mb-1 leading-tight">
                            {formatCurrency(stats.atrasado.valor)}
                        </p>
                        <p className="text-[9px] sm:text-[10px] md:text-xs text-slate-600 dark:text-slate-400 font-medium leading-tight line-clamp-2">
                            Boletos vencidos (Atrasados)
                        </p>
                    </CardContent>
                </Card>

                {/* Card Cancelado */}
                <Card 
                    className={cn(
                        "bg-white dark:bg-slate-900/50 border-2 shadow-lg rounded-lg sm:rounded-xl overflow-hidden cursor-pointer transition-all hover:scale-[1.02] sm:hover:scale-105 active:scale-[0.98]",
                        selectedStatus === 'CANCELADO' 
                            ? "border-slate-500 dark:border-slate-500 ring-2 ring-slate-500/20" 
                            : "border-slate-200 dark:border-slate-800 hover:border-slate-500/50"
                    )}
                    onClick={() => setSelectedStatus(selectedStatus === 'CANCELADO' ? 'TODOS' : 'CANCELADO')}
                >
                    <CardContent className="p-2.5 sm:p-3 md:p-4">
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                            <XCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 md:w-5 md:h-5 text-slate-500 dark:text-slate-400 shrink-0" />
                            <Badge className="bg-slate-100 dark:bg-slate-500/10 text-slate-700 dark:text-slate-400 border-slate-200 dark:border-slate-500/20 text-[9px] sm:text-[10px] md:text-xs px-1.5 py-0.5">
                                {stats.cancelado.total}
                            </Badge>
                        </div>
                        <p className="text-lg sm:text-xl md:text-2xl font-bold text-slate-600 dark:text-slate-400 mb-0.5 sm:mb-1 leading-tight">
                            {formatCurrency(stats.cancelado.valor)}
                        </p>
                        <p className="text-[9px] sm:text-[10px] md:text-xs text-slate-600 dark:text-slate-400 font-medium leading-tight">
                            Boletos cancelados no período
                        </p>
                    </CardContent>
                </Card>

                {/* Card Recebido */}
                <Card 
                    className={cn(
                        "bg-white dark:bg-slate-900/50 border-2 shadow-lg rounded-lg sm:rounded-xl overflow-hidden cursor-pointer transition-all hover:scale-[1.02] sm:hover:scale-105 active:scale-[0.98]",
                        selectedStatus === 'RECEBIDO' 
                            ? "border-emerald-500 dark:border-emerald-500 ring-2 ring-emerald-500/20" 
                            : "border-emerald-100 dark:border-emerald-900/20 hover:border-emerald-500/50"
                    )}
                    onClick={() => setSelectedStatus(selectedStatus === 'RECEBIDO' ? 'TODOS' : 'RECEBIDO')}
                >
                    <CardContent className="p-2.5 sm:p-3 md:p-4">
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                            <CheckCircle2 className="w-3.5 h-3.5 sm:w-4 sm:h-4 md:w-5 md:h-5 text-emerald-600 dark:text-emerald-400 shrink-0" />
                            <Badge className="bg-emerald-100 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20 text-[9px] sm:text-[10px] md:text-xs px-1.5 py-0.5">
                                {stats.recebido.total}
                            </Badge>
                        </div>
                        <p className="text-lg sm:text-xl md:text-2xl font-bold text-emerald-600 dark:text-emerald-400 mb-0.5 sm:mb-1 leading-tight">
                            {formatCurrency(stats.recebido.valor)}
                        </p>
                        <p className="text-[9px] sm:text-[10px] md:text-xs text-slate-600 dark:text-slate-400 font-medium leading-tight line-clamp-2">
                            Boletos recebidos via Banco
                        </p>
                    </CardContent>
                </Card>

                {/* Card Marcado Recebido */}
                <Card 
                    className={cn(
                        "bg-white dark:bg-slate-900/50 border-2 shadow-lg rounded-lg sm:rounded-xl overflow-hidden cursor-pointer transition-all hover:scale-[1.02] sm:hover:scale-105 active:scale-[0.98]",
                        selectedStatus === 'MARCADO_RECEBIDO' 
                            ? "border-orange-500 dark:border-orange-500 ring-2 ring-orange-500/20" 
                            : "border-orange-100 dark:border-orange-900/20 hover:border-orange-500/50"
                    )}
                    onClick={() => setSelectedStatus(selectedStatus === 'MARCADO_RECEBIDO' ? 'TODOS' : 'MARCADO_RECEBIDO')}
                >
                    <CardContent className="p-2.5 sm:p-3 md:p-4">
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                            <CheckCircle2 className="w-3.5 h-3.5 sm:w-4 sm:h-4 md:w-5 md:h-5 text-orange-600 dark:text-orange-400 shrink-0" />
                            <Badge className="bg-orange-100 dark:bg-orange-500/10 text-orange-700 dark:text-orange-400 border-orange-200 dark:border-orange-500/20 text-[9px] sm:text-[10px] md:text-xs px-1.5 py-0.5">
                                {stats.marcadoRecebido.total}
                            </Badge>
                        </div>
                        <p className="text-lg sm:text-xl md:text-2xl font-bold text-orange-600 dark:text-orange-400 mb-0.5 sm:mb-1 leading-tight">
                            {formatCurrency(stats.marcadoRecebido.valor)}
                        </p>
                        <p className="text-[9px] sm:text-[10px] md:text-xs text-slate-600 dark:text-slate-400 font-medium leading-tight">
                            Boletos marcados manualmente
                        </p>
                    </CardContent>
                </Card>

                {/* Card Pix */}
                <Card 
                    className={cn(
                        "bg-white dark:bg-slate-900/50 border-2 shadow-lg rounded-lg sm:rounded-xl overflow-hidden cursor-pointer transition-all hover:scale-[1.02] sm:hover:scale-105 active:scale-[0.98]",
                        selectedStatus === 'PIX' 
                            ? "border-blue-500 dark:border-blue-500 ring-2 ring-blue-500/20" 
                            : "border-blue-100 dark:border-blue-900/20 hover:border-blue-500/50"
                    )}
                    onClick={() => setSelectedStatus(selectedStatus === 'PIX' ? 'TODOS' : 'PIX')}
                >
                    <CardContent className="p-2.5 sm:p-3 md:p-4">
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                            <Receipt className="w-3.5 h-3.5 sm:w-4 sm:h-4 md:w-5 md:h-5 text-blue-600 dark:text-blue-400 shrink-0" />
                            <Badge className="bg-blue-100 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-500/20 text-[9px] sm:text-[10px] md:text-xs px-1.5 py-0.5">
                                {stats.pix.total}
                            </Badge>
                        </div>
                        <p className="text-lg sm:text-xl md:text-2xl font-bold text-blue-600 dark:text-blue-400 mb-0.5 sm:mb-1 leading-tight">
                            {formatCurrency(stats.pix.valor)}
                        </p>
                        <p className="text-[9px] sm:text-[10px] md:text-xs text-slate-600 dark:text-slate-400 font-medium leading-tight">
                            Recebimentos via PIX (Direto e Boletos)
                        </p>
                    </CardContent>
                </Card>
            </div>

            {/* Header de Filtros e Ações */}
            <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 lg:flex-row items-start lg:items-center justify-between gap-4">
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-xl bg-orange-500/10 dark:bg-orange-500/10 flex items-center justify-center border border-orange-500/20 shrink-0">
                                <Receipt className="w-5 h-5 text-orange-500" />
                            </div>
                            <div>
                                <h3 className="font-bold text-slate-900 dark:text-white flex items-center gap-2 flex-wrap text-base sm:text-lg">
                                    Gestão de Cobranças
                                    <Badge variant="outline" className="text-[10px] border-slate-300 dark:border-slate-700 text-slate-600 dark:text-slate-400 bg-slate-50 dark:bg-slate-900/50 font-bold">
                                        {filteredBoletos.length} ITENS
                                    </Badge>
                                </h3>
                                <p className="text-[10px] text-slate-500 dark:text-slate-400 font-medium uppercase tracking-widest hidden sm:block">
                                    Controle e acompanhamento de recebíveis
                                </p>
                            </div>
                        </div>

                        <div className="flex flex-wrap items-center gap-2 w-full lg:w-auto">
                            <Button 
                                size="sm" 
                                onClick={() => handleOpenCreationDialog('AVULSO')}
                                className="bg-blue-600 hover:bg-blue-700 text-white font-bold h-9 px-4"
                            >
                                <Plus className="w-4 h-4 mr-2" />
                                Avulso
                            </Button>
                            <Button 
                                size="sm" 
                                variant="outline"
                                onClick={() => handleOpenCreationDialog('MENSAL')}
                                className="border-slate-300 dark:border-slate-700 text-slate-700 dark:text-white font-bold h-9 px-4"
                            >
                                <CalendarCheck className="w-4 h-4 mr-2" />
                                Mensal
                            </Button>
                            {/* <Button 
                                size="sm" 
                                className="bg-amber-500 hover:bg-amber-600 text-white font-bold h-9 px-4 lg:hidden xl:flex shadow-lg shadow-amber-500/20 border-0"
                                onClick={() => handleOpenCreationDialog('AGENDAMENTO')}
                            >
                                <CalendarCheck className="w-4 h-4 mr-2" />
                                Agendar
                            </Button> */}
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-4 sm:p-6 bg-slate-50/50 dark:bg-slate-900/20">
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-3 sm:gap-4 items-end">
                        {/* Busca */}
                        <div className="lg:col-span-3 space-y-1.5">
                            <Label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Pesquisar</Label>
                            <div className="relative group">
                                <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 dark:text-slate-500" />
                                <Input 
                                    placeholder="Número, cliente ou documento..." 
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 pl-10 h-10 text-xs text-slate-900 dark:text-white rounded-lg focus:ring-blue-500/20"
                                />
                            </div>
                        </div>

                        {/* Mês-Ano padronizados */}
                        <div className="lg:col-span-2 space-y-1.5">
                            <Label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Mês</Label>
                            <Select 
                                value={filterMonth.split('-')[1]?.replace(/^0+/, '') || String(new Date().getMonth() + 1)} 
                                onValueChange={(v) => {
                                    const year = filterMonth.split('-')[0] || String(new Date().getFullYear());
                                    const month = v.padStart(2, '0');
                                    actions?.setFilterMonth(`${year}-${month}`);
                                }}
                            >
                                <SelectTrigger className="h-10 text-xs bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white rounded-lg">
                                    <SelectValue placeholder="Mês" />
                                </SelectTrigger>
                                <SelectContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                                    {MESES_NOME.map((m, i) => (i === 0 ? null : <SelectItem key={i} value={String(i)}>{m}</SelectItem>))}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="lg:col-span-2 space-y-1.5">
                            <Label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Ano</Label>
                            <Select 
                                value={filterMonth.split('-')[0] || String(new Date().getFullYear())} 
                                onValueChange={(v) => {
                                    const month = filterMonth.split('-')[1] || String(new Date().getMonth() + 1).padStart(2, '0');
                                    actions?.setFilterMonth(`${v}-${month}`);
                                }}
                            >
                                <SelectTrigger className="h-10 text-xs bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white rounded-lg">
                                    <SelectValue placeholder="Ano" />
                                </SelectTrigger>
                                <SelectContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                                    {ANOS_LIST.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
                                </SelectContent>
                            </Select>
                        </div>

                        {/* Status */}
                        <div className="lg:col-span-3 space-y-1.5">
                            <Label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Status</Label>
                            <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                                <SelectTrigger className="h-10 text-xs bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white rounded-lg">
                                    <SelectValue placeholder="Filtrar por Status" />
                                </SelectTrigger>
                                <SelectContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                                    <SelectItem value="TODOS">Todos os Status</SelectItem>
                                    <SelectItem value="A_RECEBER">A Receber / Pendente</SelectItem>
                                    <SelectItem value="ATRASADO">Atrasado</SelectItem>
                                    <SelectItem value="CANCELADO">Cancelado</SelectItem>
                                    <SelectItem value="RECEBIDO">Recebido</SelectItem>
                                    <SelectItem value="MARCADO_RECEBIDO">Marcado Recebido</SelectItem>
                                    <SelectItem value="PIX">Pix</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        {/* Tipo de Cobrança */}
                        <div className="lg:col-span-2 space-y-1.5">
                            <Label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Mais Filtros</Label>
                            <Select value={selectedTipo} onValueChange={setSelectedTipo}>
                                <SelectTrigger className="h-10 text-xs bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white rounded-lg">
                                    <div className="flex items-center gap-2">
                                        <Filter className="w-3.5 h-3.5" />
                                        <SelectValue placeholder="Tipo" />
                                    </div>
                                </SelectTrigger>
                                <SelectContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
                                    {TIPOS_BOLETO.map(tipo => (
                                        <SelectItem key={tipo} value={tipo}>{tipo}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                </CardContent>
            </Card>

            {/* Tabela de Boletos com ExcelTable */}
            <Card className="bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden relative">
                <CardContent className="p-0 relative z-10">
                    {/* Loading State */}
                    {isLoading && (
                        <div className="flex items-center justify-center h-[500px]">
                            <Loader2 className="w-8 h-8 animate-spin text-orange-500" />
                        </div>
                    )}
                    
                    {/* Desktop ExcelTable View */}
                    {!isLoading && (
                        <div className="hidden md:block h-[500px] lg:h-[600px]">
                            <ExcelTable
                                data={filteredBoletos}
                            columns={[
                                { 
                                    field: 'pagador', 
                                    header: 'Pagador', 
                                    width: '250px',
                                    render: (row) => (
                                        <span className="font-bold text-slate-900 dark:text-white">
                                            {row.pagador || row.cliente || 'N/D'}
                                        </span>
                                    )
                                },
                                { 
                                    field: 'emitido', 
                                    header: 'Emitido', 
                                    width: '120px',
                                    render: (row) => formatDate(row.emitido || row.dataEmissao)
                                },
                                { 
                                    field: 'vencimento', 
                                    header: 'Vencimento', 
                                    width: '120px',
                                    render: (row) => (
                                        <span className="font-medium">
                                            {formatDate(row.vencimento || row.dataVencimento)}
                                        </span>
                                    )
                                },
                                { 
                                    field: 'dataSituacao', 
                                    header: 'Data Situação', 
                                    width: '120px',
                                    render: (row) => formatDate(row.dataSituacao)
                                },
                                { 
                                    field: 'tipoCobranca', 
                                    header: 'Tipo de Cobrança', 
                                    width: '150px',
                                    render: (row) => (
                                        <Badge variant="outline" className="bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 text-xs font-bold">
                                            {row.tipoCobranca || row.tipo || 'N/D'}
                                        </Badge>
                                    )
                                },
                                { 
                                    field: 'valorNominal', 
                                    header: 'Valor Nominal', 
                                    width: '150px',
                                    render: (row) => (
                                        <span className="font-bold text-slate-900 dark:text-white text-right block">
                                            {formatCurrency(row.valorNominal || row.valor || 0)}
                                        </span>
                                    )
                                },
                                { 
                                    field: 'totalRecebido', 
                                    header: 'Total Recebido', 
                                    width: '150px',
                                    render: (row) => (
                                        <span className="font-bold text-emerald-600 dark:text-emerald-400 text-right block">
                                            {formatCurrency(row.totalRecebido || 0)}
                                        </span>
                                    )
                                },
                                /* { 
                                    field: 'acoes', 
                                    header: 'Ações', 
                                    width: '160px',
                                    render: (row) => (
                                        <div className="flex items-center gap-1">
                                            {row.codigoSolicitacao && (
                                                <>
                                                    <Button 
                                                        variant="ghost" 
                                                        size="icon" 
                                                        className="h-8 w-8 text-slate-400 hover:text-blue-400 hover:bg-blue-50 dark:hover:bg-slate-800"
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            handleDownloadBoleto(row.codigoSolicitacao);
                                                        }}
                                                        title="Baixar PDF"
                                                    >
                                                        <Download className="w-4 h-4" />
                                                    </Button>
                                                    <Button 
                                                        variant="ghost" 
                                                        size="icon" 
                                                        className="h-8 w-8 text-slate-400 hover:text-emerald-400 hover:bg-emerald-50 dark:hover:bg-slate-800"
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            handleSendBoleto(row.codigoSolicitacao, row.pagador || row.cliente);
                                                        }}
                                                        title="Enviar por Email"
                                                    >
                                                        <Send className="w-4 h-4" />
                                                    </Button>
                                                </>
                                            )}
                                            <Button 
                                                variant="ghost" 
                                                size="icon" 
                                                className="h-8 w-8 text-slate-400 hover:text-amber-400 hover:bg-amber-50 dark:hover:bg-slate-800"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    handleOpenScheduleDialog(row);
                                                }}
                                                title="Editar/Agendar"
                                            >
                                                <Edit className="w-4 h-4" />
                                            </Button>
                                        </div>
                                    )
                                } */
                            ]}
                                rowKey="id"
                                pageSize={10}
                                onRowClick={(row) => {
                                    setSelectedBoleto(row);
                                    setIsDetailPanelOpen(true);
                                }}
                            />
                        </div>
                    )}

                    {/* Mobile Card View */}
                    <div className="md:hidden p-4 space-y-3">
                        {filteredBoletos.length === 0 ? (
                            <div className="text-center py-12 text-slate-500 dark:text-slate-400 text-sm">
                                Nenhum boleto encontrado.
                            </div>
                        ) : filteredBoletos.map((boleto) => (
                            <div
                                key={boleto.id}
                                className="p-4 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/30 hover:border-orange-300 dark:hover:border-orange-700 transition-all"
                            >
                                <div className="flex items-start justify-between gap-3 mb-3">
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 mb-1">
                                            <Receipt className="w-4 h-4 text-orange-500 shrink-0" />
                                            <span className="font-mono text-sm font-bold text-slate-900 dark:text-white">{boleto.numero}</span>
                                        </div>
                                        <p className="text-sm font-medium text-slate-900 dark:text-white mb-1">{boleto.pagador || boleto.cliente}</p>
                                        <p className="text-xs text-slate-500 dark:text-slate-400">{boleto.descricao || 'Sem descrição'}</p>
                                    </div>
                                    {getStatusBadge(boleto.status)}
                                </div>
                                <div className="grid grid-cols-2 gap-3 pt-3 border-t border-slate-200 dark:border-slate-800">
                                    <div>
                                        <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold mb-1">Emitido</p>
                                        <p className="text-xs text-slate-700 dark:text-slate-300">{formatDate(boleto.emitido || boleto.dataEmissao)}</p>
                                    </div>
                                    <div>
                                        <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold mb-1">Vencimento</p>
                                        <p className="text-xs text-slate-700 dark:text-slate-300">{formatDate(boleto.vencimento || boleto.dataVencimento)}</p>
                                    </div>
                                </div>
                                <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between">
                                    <div>
                                        <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold mb-1">Valor Nominal</p>
                                        <p className="text-base font-bold text-orange-600 dark:text-orange-400">{formatCurrency(boleto.valorNominal || boleto.valor || 0)}</p>
                                    </div>
                                    <div className="text-right">
                                        <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase font-bold mb-1">Recebido</p>
                                        <p className="text-sm font-bold text-emerald-600 dark:text-emerald-400">{formatCurrency(boleto.totalRecebido || 0)}</p>
                                    </div>
                                    <div className="flex gap-2">
                                        <Button 
                                            size="sm" 
                                            variant="ghost" 
                                            className="h-8 w-8 p-0 text-slate-400 hover:text-blue-400"
                                            onClick={() => handleDownloadBoleto(boleto.id)}
                                            title="Baixar"
                                        >
                                            <Download className="w-4 h-4" />
                                        </Button>
                                        <Button 
                                            size="sm" 
                                            variant="ghost" 
                                            className="h-8 w-8 p-0 text-slate-400 hover:text-emerald-400"
                                            onClick={() => handleSendBoleto(boleto.id)}
                                            title="Enviar"
                                        >
                                            <Send className="w-4 h-4" />
                                        </Button>
                                        {/* <Button 
                                            size="sm" 
                                            variant="ghost" 
                                            className="h-8 w-8 p-0 text-amber-500 hover:text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-500/10"
                                            onClick={() => handleOpenScheduleDialog(boleto)}
                                            title="Agendar"
                                        >
                                            <Calendar className="w-4 h-4" />
                                        </Button> */}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </CardContent>
            </Card>

            {/* Dialog de Agendamento */}
            <Dialog open={isScheduleDialogOpen} onOpenChange={setIsScheduleDialogOpen}>
                <DialogContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white">
                    <DialogHeader>
                        <DialogTitle className="text-slate-900 dark:text-white font-bold text-lg">
                            Agendar Boleto
                        </DialogTitle>
                        <div className="sr-only">Formulário para agendar o vencimento do boleto selecionado</div>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        {selectedBoleto && (
                            <div className="space-y-2">
                                <div>
                                    <Label className="text-slate-500 dark:text-slate-300 text-xs font-bold uppercase block mb-2">
                                        Boleto: {selectedBoleto.numero || selectedBoleto.id}
                                    </Label>
                                    <Label className="text-slate-500 dark:text-slate-300 text-xs font-bold uppercase block mb-2">
                                        Pagador: {selectedBoleto.pagador || selectedBoleto.cliente}
                                    </Label>
                                </div>
                                <div className="space-y-2">
                                    <Label className="text-slate-500 dark:text-slate-300 text-xs font-bold uppercase">
                                        Nova Data de Vencimento
                                    </Label>
                                    <Input
                                        type="date"
                                        value={newDate}
                                        onChange={(e) => setNewDate(e.target.value)}
                                        className="bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white focus:border-orange-500"
                                    />
                                </div>
                            </div>
                        )}
                    </div>
                    <DialogFooter>
                        <Button 
                            variant="ghost" 
                            onClick={() => setIsScheduleDialogOpen(false)}
                            className="text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white"
                        >
                            Cancelar
                        </Button>
                        <Button 
                            onClick={handleSchedule}
                            className="bg-orange-600 hover:bg-orange-700 text-white"
                        >
                            <Calendar className="w-4 h-4 mr-2" />
                            Agendar
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Dialog de Criação de Boleto (Avulso / Mensal / Agendamento) */}
            <BoletoCreationDialog 
                open={isCreationDialogOpen}
                onOpenChange={setIsCreationDialogOpen}
                creationMode={creationMode}
                empresas={empresas}
                isCreating={isCreating}
                onCreateBoleto={handleCreateBoleto}
            />
            {/* Painel de Detalhes do Boleto */}
            {isDetailPanelOpen && selectedBoleto && (
                <div className="fixed top-16 right-0 bottom-0 left-0 md:left-auto z-[100]">
                    {/* Backdrop */}
                    <div 
                        className="absolute inset-0 bg-black/10 dark:bg-slate-900/20 md:bg-transparent" 
                        onClick={() => setIsDetailPanelOpen(false)} 
                    />
                    
                    <div className="absolute top-0 right-0 bottom-0 w-full md:w-[600px] bg-white dark:bg-[#1e293b] shadow-2xl border-l border-slate-200 dark:border-slate-800 animate-in slide-in-from-right duration-300 flex flex-col">
                        <ItemDetailPanel
                            title={selectedBoleto.nome || selectedBoleto.pagador || selectedBoleto.cliente || 'N/D'}
                            subtitle={`Seu Número: ${selectedBoleto.seuNumero || selectedBoleto.numero || 'N/D'}`}
                            status={formatStatus(selectedBoleto.situacao || selectedBoleto.status)}
                            statusColor={
                                selectedBoleto.status === 'RECEBIDO' || selectedBoleto.status === 'PAGO' 
                                    ? "bg-emerald-500/10 text-emerald-500" 
                                    : selectedBoleto.status === 'ATRASADO' || selectedBoleto.status === 'VENCIDO'
                                        ? "bg-red-500/10 text-red-500"
                                        : "bg-blue-500/10 text-blue-500"
                            }
                            onClose={() => setIsDetailPanelOpen(false)}
                            actions={selectedBoleto.tipo === 'PIX' || selectedBoleto.status === 'PIX' ? [] : [
                                {
                                    label: 'Baixar PDF',
                                    icon: <Download className="w-4 h-4" />,
                                    onClick: () => handleDownloadBoleto(selectedBoleto.codigoSolicitacao),
                                    variant: 'outline'
                                },
                                {
                                    label: 'Enviar Email',
                                    icon: <Send className="w-4 h-4" />,
                                    onClick: () => handleSendBoleto(selectedBoleto.codigoSolicitacao, selectedBoleto.pagador || selectedBoleto.cliente),
                                    variant: 'outline'
                                },
                                {
                                    label: 'Agendar',
                                    icon: <Calendar className="w-4 h-4" />,
                                    onClick: () => handleOpenScheduleDialog(selectedBoleto),
                                    className: "bg-amber-500 hover:bg-amber-600 text-white border-0 shadow-md shadow-amber-500/10"
                                },
                                ...(selectedBoleto.status !== 'CANCELADO' && selectedBoleto.status !== 'PAGO' && selectedBoleto.status !== 'RECEBIDO' ? [{
                                    label: 'Cancelar',
                                    icon: <XCircle className="w-4 h-4 text-red-500" />,
                                    onClick: () => handleOpenCancelDialog(selectedBoleto),
                                    variant: 'outline',
                                    className: 'text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/10 border-red-200 dark:border-red-900/20'
                                }] : [])
                            ]}
                            tabs={[
                                {
                                    id: 'info',
                                    label: 'Informações',
                                    content: (selectedBoleto.tipo === 'PIX' || selectedBoleto.status === 'PIX') ? (
                                        <div className="space-y-4">
                                            <div className="grid grid-cols-2 gap-4">
                                                <div className="p-3 bg-emerald-500/5 rounded-lg border border-emerald-500/10">
                                                    <p className="text-[10px] uppercase font-bold text-emerald-600/70 dark:text-emerald-400/70">Valor Recebido</p>
                                                    <p className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">{formatCurrency(selectedBoleto.valorNominal || selectedBoleto.valor)}</p>
                                                </div>
                                                <div className="p-3 bg-slate-500/5 rounded-lg border border-slate-500/10">
                                                    <p className="text-[10px] uppercase font-bold text-slate-500/70 dark:text-slate-400/70">Data</p>
                                                    <p className="text-xl font-bold text-slate-700 dark:text-slate-300">{formatDate(selectedBoleto.dataEmissao || selectedBoleto.emitido)}</p>
                                                </div>
                                            </div>

                                            <div className="space-y-3">
                                                {selectedBoleto.descricao && (
                                                    <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Descrição</p>
                                                        <div className="text-sm bg-slate-50 dark:bg-slate-900/50 p-2 rounded border border-slate-100 dark:border-slate-800 text-slate-700 dark:text-slate-300">
                                                            {selectedBoleto.descricao}
                                                        </div>
                                                    </div>
                                                )}

                                                <div>
                                                    <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">ID Transação / TXID</p>
                                                    <div className="flex items-center gap-2">
                                                        <code className="text-[11px] flex-1 font-mono bg-slate-100 dark:bg-slate-900/50 p-2 rounded border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 break-all select-all">
                                                            {selectedBoleto.txid || selectedBoleto.numero || selectedBoleto.idTransacao || 'N/D'}
                                                        </code>
                                                    </div>
                                                </div>
                                                
                                                <div className="grid grid-cols-2 gap-3">
                                                     <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">CPF/CNPJ</p>
                                                        <p className="text-sm font-bold text-slate-900 dark:text-white">{selectedBoleto.cpfCnpj || 'N/D'}</p>
                                                    </div>
                                                    <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Situação</p>
                                                        <Badge variant="outline" className="text-emerald-600 border-emerald-200 bg-emerald-50">Confirmado</Badge>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="space-y-6">
                                            <div className="grid grid-cols-3 gap-4">
                                                <div className="p-3 bg-slate-50 dark:bg-slate-900/50 rounded-lg border border-slate-100 dark:border-slate-800">
                                                    <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Valor Nominal</p>
                                                    <p className="text-lg font-bold text-slate-900 dark:text-white">{formatCurrency(selectedBoleto.valorNominal || selectedBoleto.valor)}</p>
                                                </div>
                                                <div className="p-3 bg-emerald-500/5 rounded-lg border border-emerald-500/10">
                                                    <p className="text-[10px] font-bold text-emerald-600/70 dark:text-emerald-400/70 uppercase tracking-widest mb-1">Total Recebido</p>
                                                    <p className="text-lg font-bold text-emerald-600 dark:text-emerald-400">{formatCurrency(selectedBoleto.totalRecebido || 0)}</p>
                                                </div>
                                                <div className="p-3 bg-blue-500/5 rounded-lg border border-blue-500/10">
                                                    <p className="text-[10px] font-bold text-blue-600/70 dark:text-blue-400/70 uppercase tracking-widest mb-1">Vencimento</p>
                                                    <p className="text-lg font-bold text-blue-600 dark:text-blue-400">{formatDate(selectedBoleto.dataVencimento || selectedBoleto.vencimento)}</p>
                                                </div>
                                            </div>

                                            <div className="grid grid-cols-2 gap-6 bg-slate-50 dark:bg-slate-900/20 p-4 rounded-xl border border-slate-100 dark:border-slate-800/50">
                                                <div>
                                                    <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Data Emissão</p>
                                                    <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">{formatDate(selectedBoleto.dataEmissao || selectedBoleto.emitido)}</p>
                                                </div>
                                                <div>
                                                    <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Data Situação</p>
                                                    <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">{formatDate(selectedBoleto.dataSituacao)}</p>
                                                </div>
                                            </div>

                                            <Separator className="bg-slate-200 dark:bg-slate-800" />

                                            <div className="space-y-4">
                                                <div className="grid grid-cols-2 gap-4">
                                                    <div className="bg-slate-50 dark:bg-slate-900/30 p-3 rounded-lg border border-slate-100 dark:border-slate-800">
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Nosso Número</p>
                                                        <p className="text-xs font-mono font-bold text-slate-700 dark:text-slate-300">{selectedBoleto.nossoNumero || 'N/D'}</p>
                                                    </div>
                                                    <div className="bg-slate-50 dark:bg-slate-900/30 p-3 rounded-lg border border-slate-100 dark:border-slate-800">
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Seu Número</p>
                                                        <p className="text-xs font-mono font-bold text-slate-700 dark:text-slate-300">{selectedBoleto.seuNumero || 'N/D'}</p>
                                                    </div>
                                                </div>

                                                <div className="grid grid-cols-2 gap-4">
                                                     <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">CPF/CNPJ</p>
                                                        <p className="text-sm font-bold text-slate-900 dark:text-white">{selectedBoleto.cpfCnpj || 'N/D'}</p>
                                                    </div>
                                                    <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Situação</p>
                                                        <p className="text-sm font-bold text-slate-900 dark:text-white">{formatStatus(selectedBoleto.situacao || selectedBoleto.status)}</p>
                                                    </div>
                                                </div>

                                                <div className="grid grid-cols-2 gap-4">
                                                     <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Tipo de Cobrança</p>
                                                        <p className="text-sm font-semibold text-slate-600 dark:text-slate-400">{selectedBoleto.tipoCobranca || 'N/D'}</p>
                                                    </div>
                                                    <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">ID Sistema</p>
                                                        <p className="text-sm font-semibold text-slate-600 dark:text-slate-400">{selectedBoleto.idboletos || selectedBoleto.id || 'N/D'}</p>
                                                    </div>
                                                </div>

                                                <Separator className="bg-slate-100 dark:bg-slate-800/50" />

                                                <div>
                                                    <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Código de Solicitação</p>
                                                    <p className="text-[11px] font-mono bg-slate-100 dark:bg-slate-900/50 p-2 rounded border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 break-all select-all">
                                                        {selectedBoleto.codigoSolicitacao}
                                                    </p>
                                                </div>

                                                {selectedBoleto.codigoBarras && (
                                                    <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Código de Barras</p>
                                                        <p className="text-[11px] font-mono bg-slate-100 dark:bg-slate-900/50 p-2 rounded border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 break-all select-all">
                                                            {selectedBoleto.codigoBarras}
                                                        </p>
                                                    </div>
                                                )}

                                                {selectedBoleto.linhaDigitavel && (
                                                    <div>
                                                        <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1">Linha Digitável</p>
                                                        <p className="text-[11px] font-mono bg-slate-100 dark:bg-slate-900/50 p-2 rounded border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 break-all select-all">
                                                            {selectedBoleto.linhaDigitavel}
                                                        </p>
                                                    </div>
                                                )}

                                                {(selectedBoleto.pixCopiaECola || selectedBoleto.txid) && (
                                                    <div className="mt-4 p-4 bg-blue-500/5 rounded-xl border border-blue-500/10 space-y-3">
                                                        <p className="text-[10px] font-bold text-blue-600 dark:text-blue-400 uppercase tracking-widest">Informações PIX</p>
                                                        
                                                        {selectedBoleto.txid && (
                                                            <div>
                                                                <p className="text-[9px] font-bold text-slate-500 dark:text-slate-400 uppercase mb-1">TXID</p>
                                                                <p className="text-[10px] font-mono text-slate-600 dark:text-slate-400 break-all">{selectedBoleto.txid}</p>
                                                            </div>
                                                        )}

                                                        {selectedBoleto.pixCopiaECola && (
                                                            <div>
                                                                <p className="text-[9px] font-bold text-slate-500 dark:text-slate-400 uppercase mb-1">Pix Copia e Cola</p>
                                                                <p className="text-[10px] font-mono bg-white dark:bg-slate-900/50 p-2 rounded border border-blue-200 dark:border-blue-900/20 text-slate-600 dark:text-slate-400 break-all line-clamp-3 select-all">
                                                                    {selectedBoleto.pixCopiaECola}
                                                                </p>
                                                            </div>
                                                        )}
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    )
                                }
                            ]}
                        />
                    </div>
                </div>
            )}

            <CancelamentoDialog 
                open={isCancelDialogOpen} 
                onOpenChange={setIsCancelDialogOpen}
                onConfirm={handleConfirmCancellation}
                loading={processingCancellation}
                reason={cancelReason}
                setReason={setCancelReason}
                boleto={boletoToCancel}
            />
        </div>
    );
};

/* Dialog de Cancelamento de Boleto */
function CancelamentoDialog({ open, onOpenChange, onConfirm, loading, reason, setReason, boleto }) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white max-w-md z-[1000]">
                <DialogHeader>
                    <DialogTitle className="text-slate-900 dark:text-white font-bold text-lg flex items-center gap-2">
                        <XCircle className="w-5 h-5 text-red-500" />
                        Cancelar Boleto
                    </DialogTitle>
                    <div className="sr-only">Confirmação de cancelamento de boleto</div>
                </DialogHeader>
                <div className="space-y-4 py-4">
                    <div className="bg-red-50 dark:bg-red-500/5 border border-red-100 dark:border-red-500/10 rounded-lg p-3">
                        <p className="text-xs text-red-500/80">
                            Você está prestes a cancelar o boleto <strong>{boleto?.numero}</strong> de <strong>{boleto?.pagador || boleto?.cliente}</strong> no valor de <strong>{boleto?.valorNominal ? parseFloat(boleto?.valorNominal).toLocaleString('pt-BR', {style: 'currency', currency:'BRL'}) : 'R$ 0,00'}</strong>.
                        </p>
                    </div>
                    <div className="space-y-2">
                        <Label className="text-slate-500 dark:text-slate-300 text-xs font-bold uppercase">
                            Motivo do Cancelamento <span className="text-red-400">*</span>
                        </Label>
                        <textarea
                            value={reason}
                            onChange={(e) => setReason(e.target.value)}
                            className="w-full bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white rounded-md p-2 text-sm min-h-[80px]"
                            placeholder="Descreva o motivo..."
                        />
                    </div>
                </div>
                <DialogFooter>
                    <Button 
                        variant="ghost" 
                        onClick={() => onOpenChange(false)}
                        className="text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white"
                        disabled={loading}
                    >
                        Voltar
                    </Button>
                    <Button 
                        onClick={onConfirm}
                        className="bg-red-600 hover:bg-red-700 text-white"
                        disabled={loading || !reason.trim()}
                    >
                        {loading ? (
                            <>
                                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                Cancelando...
                            </>
                        ) : (
                            <>
                                <XCircle className="w-4 h-4 mr-2" />
                                Confirmar Cancelamento
                            </>
                        )}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
