import React, { useState, useRef, useMemo } from 'react';
import { Upload, FileSpreadsheet, AlertCircle, Save, CheckCircle2, ArrowRight, HelpCircle, Download, ArrowLeft, X, FileText } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import CnabExcelTable from '../components/CnabExcelTable';
import { useGerarRemessa } from '../hooks/useGerarRemessa';
import { useCnabStore } from '../hooks/useCnabStore';

/**
 * Componente principal de Geração de Remessa
 * Segue o fluxo completo: Upload → Mapping → Validate → Generate REM
 */
const GerarRemessaView = () => {
    const {
        step, setStep,
        paymentType,
        loading,
        rawHeaders, rawData,
        tableHtml,
        columnMapping, setColumnMapping,
        validatedTableHtml,
        tableData,
        validationErrors,
        remessaFile,
        remessaFilename,
        handleUpload,
        confirmMapping,
        updateTableHtml,
        updateCellValue,
        finalize,
        downloadRemessa,
        reset,
        schemas,
        effectivePaymentType
    } = useGerarRemessa();

    const { selectedBank, setSelectedBank, bradescoRemessaVariant, setBradescoRemessaVariant } = useCnabStore();
    const [showAssistant, setShowAssistant] = useState(false);
    const [showErrorLogs, setShowErrorLogs] = useState(false);
    const inputRef = useRef(null);
    
    // Estado para controlar edição inline de células
    const [editingCell, setEditingCell] = useState(null); // { rowId, field }
    const [editValue, setEditValue] = useState('');

    /**
     * Converte dados brutos para formato do ExcelTable
     */
    const previewColumns = useMemo(() => {
        if (!rawHeaders || rawHeaders.length === 0) return [];
        return rawHeaders.map(header => ({
            header,
            field: header,
            width: 180,
            render: (row) => (
                <div className="text-slate-700 dark:text-zinc-300 font-mono text-xs truncate" title={row[header]}>
                    {row[header] || '---'}
                </div>
            )
        }));
    }, [rawHeaders]);

    /**
     * Processa HTML validado para extrair dados estruturados
     * NOTA: tableData é a fonte de verdade - sempre use tableData diretamente
     * Este useMemo é mantido apenas para compatibilidade com validationInfo
     * DEVE SER DEFINIDO ANTES DE validatedColumns
     */
    const processedValidatedData = useMemo(() => {
        // IMPORTANTE: tableData é sempre a fonte de verdade
        // Não leia do HTML, use tableData diretamente
        return tableData || [];
    }, [tableData]);

    /**
     * Extrai informações de validação do HTML validado
     * DEVE SER DEFINIDO DEPOIS DE processedValidatedData
     */
    const validationInfo = useMemo(() => {
        const info = {
            errorMap: {}, // { rowIndex: { field: errorMessage } }
            cellStyles: {} // { rowIndex_field: { bgColor, textColor, title } }
        };

        // Primeiro, processa erros do JSON de validação
        if (validationErrors?.erros) {
            console.log('📋 Processando erros do JSON de validação:', validationErrors.erros);
            validationErrors.erros.forEach(([rowIndex, errors]) => {
                info.errorMap[rowIndex] = errors;
                console.log(`   - Linha ${rowIndex}:`, errors);
            });
        }

        // Depois, extrai informações do HTML validado (cores, mensagens)
        if (validatedTableHtml) {
            try {
                const parser = new DOMParser();
                const doc = parser.parseFromString(validatedTableHtml, 'text/html');
                const table = doc.querySelector('table#editable-table, table');
                
                if (table) {
                    const rows = Array.from(table.querySelectorAll('tbody tr'));
                    console.log(`🔍 Extraindo validação de ${rows.length} linhas do HTML`);
                    
                    rows.forEach((tr, rowIdx) => {
                        const cells = Array.from(tr.querySelectorAll('td[data-col]'));
                        cells.forEach(cell => {
                            const field = cell.getAttribute('data-col');
                            if (!field) return;
                            
                            // Obtém estilos inline e atributos
                            const bgColor = cell.style.backgroundColor || '';
                            const textColor = cell.style.color || '';
                            const title = cell.title || cell.getAttribute('title') || '';
                            
                            // Normaliza a cor para comparação (remove espaços, converte para lowercase)
                            const normalizedBg = bgColor ? bgColor.toLowerCase().replace(/\s/g, '') : '';
                            
                            // Verifica se tem cor vermelha (múltiplos formatos possíveis)
                            const isErrorColor = normalizedBg && (
                                normalizedBg.includes('ffb3b3') || 
                                normalizedBg.includes('rgb(255,179,179)') ||
                                normalizedBg.includes('rgb(255, 179, 179)') ||
                                normalizedBg.includes('#ffb3b3') ||
                                normalizedBg.includes('rose') || 
                                normalizedBg.includes('red') ||
                                (normalizedBg.startsWith('rgb(255') && !normalizedBg.includes('255,255,255')) // RGB vermelho (não branco)
                            );
                            
                            // Verifica se tem cor verde (válido)
                            const isValidColor = normalizedBg && (
                                normalizedBg.includes('4c724c') ||
                                normalizedBg.includes('rgb(76,114,76)') ||
                                normalizedBg.includes('rgb(76, 114, 76)') ||
                                normalizedBg.includes('#4c724c') ||
                                normalizedBg.includes('emerald') || 
                                normalizedBg.includes('green') ||
                                (normalizedBg.startsWith('rgb(76,114') || normalizedBg.startsWith('rgb(34,197,94')) // Verde escuro ou emerald
                            );
                            
                            if (isErrorColor) {
                                const key = `${rowIdx}_${field}`;
                                const errorMsg = title || 'Campo inválido';
                                
                                info.cellStyles[key] = {
                                    hasError: true,
                                    errorMessage: errorMsg,
                                    bgColor,
                                    textColor
                                };
                                
                                // Adiciona ao errorMap se não existir (prioriza JSON se já existir)
                                if (!info.errorMap[rowIdx]) {
                                    info.errorMap[rowIdx] = {};
                                }
                                // Só adiciona se não existir erro do JSON para este campo
                                if (!info.errorMap[rowIdx][field]) {
                                    info.errorMap[rowIdx][field] = errorMsg;
                                    console.log(`   ✅ Erro detectado no HTML: Linha ${rowIdx}, Campo ${field}: ${errorMsg}`);
                                }
                            } else if (isValidColor) {
                                // Campo válido
                                const key = `${rowIdx}_${field}`;
                                info.cellStyles[key] = {
                                    hasError: false,
                                    isValid: true,
                                    bgColor,
                                    textColor
                                };
                            }
                        });
                    });
                }
            } catch (e) {
                console.warn('⚠️ Erro ao extrair validação do HTML:', e);
            }
        }
        
        console.log('📊 ValidationInfo final:', {
            errorMapKeys: Object.keys(info.errorMap),
            cellStylesKeys: Object.keys(info.cellStyles),
            totalErrors: Object.values(info.errorMap).reduce((sum, errors) => sum + Object.keys(errors).length, 0)
        });

        return info;
    }, [validationErrors, validatedTableHtml]);

    /**
     * Converte dados validados para formato do ExcelTable com indicadores visuais
     * DEVE SER DEFINIDO DEPOIS DE processedValidatedData E validationInfo
     */
    const validatedColumns = useMemo(() => {
        if (!schemas[effectivePaymentType]) return [];

        return schemas[effectivePaymentType].map(field => ({
            header: field.label,
            field: field.key,
            width: 180,
            render: (row) => {
                // IMPORTANTE: Usa diretamente o valor do row (que vem de tableData)
                // tableData é a fonte de verdade e já contém as edições do usuário
                const value = row[field.key] || '';
                const rowId = row.id;
                const isEditing = editingCell?.rowId === rowId && editingCell?.field === field.key;
                
                // Encontra o índice da linha no array processado (usa o índice do array, não o ID)
                const dataArray = processedValidatedData.length > 0 ? processedValidatedData : tableData;
                const rowIndex = dataArray.findIndex(r => r.id === row.id);
                
                // Se não encontrou pelo ID, tenta pelo índice direto
                const finalRowIndex = rowIndex >= 0 ? rowIndex : (row.id - 1);
                
                // Verifica erros do JSON de validação
                const rowErrors = validationInfo.errorMap[finalRowIndex];
                const hasErrorFromJson = rowErrors && rowErrors[field.key];
                const errorMessage = hasErrorFromJson ? rowErrors[field.key] : null;
                
                // Verifica estilos do HTML validado
                const cellKey = `${finalRowIndex}_${field.key}`;
                const cellStyle = validationInfo.cellStyles[cellKey];
                
                // Determina se tem erro (prioriza JSON, depois HTML)
                const hasError = hasErrorFromJson || cellStyle?.hasError;
                const isValid = !hasError && value && (cellStyle?.isValid || (!cellStyle && value && !hasError));
                const finalErrorMessage = errorMessage || cellStyle?.errorMessage;

                // Se está editando, mostra input
                if (isEditing) {
                    return (
                        <div className="px-1 py-1">
                            <input
                                type="text"
                                value={editValue}
                                onChange={(e) => setEditValue(e.target.value)}
                                onBlur={() => {
                                    if (editValue !== value) {
                                        updateCellValue(rowId, field.key, editValue);
                                    }
                                    setEditingCell(null);
                                    setEditValue('');
                                }}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        if (editValue !== value) {
                                            updateCellValue(rowId, field.key, editValue);
                                        }
                                        setEditingCell(null);
                                        setEditValue('');
                                    } else if (e.key === 'Escape') {
                                        setEditingCell(null);
                                        setEditValue('');
                                    }
                                }}
                                autoFocus
                                className={cn(
                                    "w-full px-3 py-2 rounded-md text-xs font-mono bg-slate-50 dark:bg-zinc-900 border-2 border-emerald-500 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50"
                                )}
                            />
                        </div>
                    );
                }

                // Célula normal (editável ao clicar)
                return (
                    <div 
                        className={cn(
                            "px-3 py-2 rounded-md text-xs font-mono transition-all cursor-pointer hover:scale-[1.02]",
                            hasError 
                                ? "bg-rose-500/30 text-rose-700 dark:text-rose-300 border-2 border-rose-500/50 shadow-lg shadow-rose-500/20 font-bold hover:bg-rose-500/40" 
                                : isValid 
                                    ? "bg-emerald-500/20 text-emerald-700 dark:text-emerald-300 border-2 border-emerald-500/30 shadow-sm shadow-emerald-500/10 hover:bg-emerald-500/30"
                                    : "text-slate-600 dark:text-zinc-400 border border-slate-300 dark:border-zinc-700/50 bg-slate-100 dark:bg-zinc-800/30 hover:bg-slate-200 dark:hover:bg-zinc-800/50"
                        )}
                        title={hasError ? `${finalErrorMessage || 'Campo com erro'} - Clique para editar` : 'Clique para editar'}
                        onClick={() => {
                            setEditingCell({ rowId, field: field.key });
                            setEditValue(value);
                        }}
                        onDoubleClick={() => {
                            setEditingCell({ rowId, field: field.key });
                            setEditValue(value);
                        }}
                    >
                        <div className="flex items-center justify-between gap-2">
                            <span className={cn(
                                "truncate",
                                hasError && "text-rose-700 dark:text-rose-200"
                            )}>
                                {value || <span className="text-slate-500 dark:text-zinc-600 italic">Vazio</span>}
                            </span>
                            {hasError && (
                                <AlertCircle size={14} className="text-rose-600 dark:text-rose-400 flex-shrink-0" />
                            )}
                            {isValid && !hasError && (
                                <CheckCircle2 size={14} className="text-emerald-600 dark:text-emerald-400 flex-shrink-0" />
                            )}
                        </div>
                    </div>
                );
            }
        }));
    }, [schemas, paymentType, validationInfo, processedValidatedData, tableData, editingCell, editValue, updateCellValue]);

    return (
        <div className="p-8 max-w-[1920px] mx-auto space-y-8 font-inter h-full flex flex-col overflow-hidden">
            
            {/* Top Bar */}
            <div className="flex justify-between items-center shrink-0">
                <div>
                    <h1 className="text-3xl font-bold tracking-tighter text-slate-900 dark:text-white">
                        Gerar <span className="text-emerald-600">Remessa {paymentType}{selectedBank === 'BRADESCO' && paymentType === 'TED' && bradescoRemessaVariant === 'folha_pagamento' ? ' (Folha de pagamento)' : ''}</span> - <span className="text-blue-600">{selectedBank}</span>
                    </h1>
                    <p className="text-slate-500 dark:text-zinc-400 text-sm">
                        {step === 'upload' && "Escolha o modelo e carregue o arquivo de pagamentos."}
                        {step === 'mapping' && "Correlacione as colunas da sua planilha com os campos do sistema."}
                        {step === 'validate' && "Revise os dados destacados em vermelho antes de gerar o arquivo."}
                        {step === 'success' && "Arquivo gerado com sucesso! Faça o download do arquivo .REM."}
                    </p>
                </div>

                <div className="flex gap-4 items-center flex-wrap">
                    {step === 'upload' && (
                        <>
                            {/* Seletor de Banco  opition BRADESCO*/}
                            <div className="bg-white dark:bg-zinc-900/50 p-1 rounded-xl flex border border-slate-200 dark:border-zinc-800 shadow-inner">
                                {['INTER', ].map(bank => (
                                    <button
                                        key={bank}
                                        onClick={() => setSelectedBank(bank)}
                                        className={cn(
                                            "px-4 py-2 rounded-lg text-xs font-bold tracking-widest transition-all",
                                            selectedBank === bank ? "bg-blue-600 text-white shadow-lg" : "text-slate-600 dark:text-zinc-500 hover:text-slate-900 dark:hover:text-zinc-300"
                                        )}
                                    >
                                        {bank}
                                    </button>
                                ))}
                            </div>
                            {/* Variante TED Bradesco: TED ou Folha de pagamento (rota /cnab/bradesco/folha_pagamento) */}
                            {selectedBank === 'BRADESCO' && paymentType === 'TED' && (
                                <div className="bg-white dark:bg-zinc-900/50 p-1 rounded-xl flex border border-slate-200 dark:border-zinc-800 shadow-inner">
                                    {[
                                        { value: 'ted', label: 'TED' },
                                        { value: 'folha_pagamento', label: 'Folha' },
                                        { value: 'cobranca', label: 'Cobrança' }
                                    ].map(({ value, label }) => (
                                        <button
                                            key={value}
                                            onClick={() => setBradescoRemessaVariant(value)}
                                            className={cn(
                                                "px-4 py-2 rounded-lg text-xs font-bold tracking-widest transition-all",
                                                bradescoRemessaVariant === value ? "bg-emerald-600 text-white shadow-lg" : "text-slate-600 dark:text-zinc-500 hover:text-slate-900 dark:hover:text-zinc-300"
                                            )}
                                        >
                                            {label}
                                        </button>
                                    ))}
                                </div>
                            )}
                        </>
                    )}
                    {step !== 'upload' && step !== 'success' && (
                        <button onClick={reset} className="text-slate-600 dark:text-zinc-500 hover:text-slate-900 dark:hover:text-white text-xs font-bold uppercase tracking-wider transition-colors flex items-center gap-2">
                            <ArrowLeft size={16} />
                            Reiniciar
                        </button>
                    )}
                </div>
            </div>

            {/* --- STEP 1: UPLOAD --- */}
            {step === 'upload' && (
                <motion.div 
                    initial={{ opacity: 0, scale: 0.98 }} animate={{ opacity: 1, scale: 1 }}
                    onClick={() => !loading && inputRef.current?.click()}
                    className={cn(
                        "flex-1 border-2 border-dashed rounded-3xl flex flex-col items-center justify-center text-center space-y-6 transition-all duration-500 cursor-pointer relative overflow-hidden",
                        loading ? "border-emerald-500/50 bg-emerald-500/5 cursor-wait" : "border-slate-200 dark:border-zinc-800 bg-slate-50 dark:bg-[#161616] hover:border-emerald-500/40 hover:bg-emerald-500/[0.02] group"
                    )}
                >
                    <div className={cn(
                        "w-24 h-24 rounded-3xl flex items-center justify-center transition-all duration-500 shadow-xl",
                        loading ? "bg-emerald-500 text-white animate-pulse" : "bg-emerald-500/10 text-emerald-500 group-hover:scale-110 shadow-emerald-500/5"
                    )}>
                        <Upload className="w-10 h-10" strokeWidth={1.5} />
                    </div>
                    <div className="space-y-2 z-10">
                        <h3 className="text-2xl font-bold text-slate-900 dark:text-white tracking-tight">
                            {loading ? "Processando arquivo..." : `Importar Planilha ${paymentType}`}
                        </h3>
                        <p className="text-slate-600 dark:text-zinc-500 max-w-sm mx-auto">
                            Clique ou arraste seu arquivo .xlsx ou .xls aqui para iniciar o mapeamento.
                        </p>
                    </div>
                    <input ref={inputRef} type="file" accept=".xlsx,.xls" className="hidden" onChange={(e) => handleUpload(e.target.files?.[0])} />
                </motion.div>
            )}

            {/* --- STEP 2: MAPPING --- */}
            {step === 'mapping' && (
                <div className="flex-1 flex gap-8 min-h-0 animate-in fade-in slide-in-from-bottom-4 duration-700">
                    {/* Left: Raw Data Preview com ExcelTable */}
                    <div className="flex-1 bg-white dark:bg-[#1b1b1b] rounded-3xl border border-slate-200 dark:border-zinc-800 overflow-hidden flex flex-col shadow-2xl relative">
                        <div className="bg-slate-50 dark:bg-[#151515] p-5 border-b border-slate-200 dark:border-zinc-800 flex justify-between items-center text-slate-600 dark:text-zinc-400 shrink-0">
                            <div className="flex items-center gap-3">
                                <FileSpreadsheet size={18} className="text-emerald-500" />
                                <span className="font-bold text-sm tracking-tight text-slate-900 dark:text-zinc-200">Pré-visualização dos Dados</span>
                            </div>
                            <HelpCircle size={18} className="cursor-pointer hover:text-emerald-500 transition-colors" onClick={() => setShowAssistant(true)} />
                        </div>
                        <div className="flex-1 min-h-0">
                            {rawData.length > 0 && previewColumns.length > 0 ? (
                                <CnabExcelTable
                                    data={rawData}
                                    columns={previewColumns}
                                    pageSize={20}
                                    rowKey="id"
                                />
                            ) : (
                                <div className="flex items-center justify-center h-full text-slate-600 dark:text-zinc-500">
                                    <p>Carregando dados...</p>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Right: Mapping Controls */}
                    <div className="w-[480px] bg-white dark:bg-[#1b1b1b] rounded-3xl border border-slate-200 dark:border-zinc-800 flex flex-col shadow-2xl overflow-hidden">
                        <div className="p-8 border-b border-slate-200 dark:border-zinc-800 bg-slate-50 dark:bg-[#1e1e1e] shrink-0">
                            <h3 className="text-xl font-bold text-slate-900 dark:text-white mb-2">Mapeamento de Colunas</h3>
                            <p className="text-xs text-slate-600 dark:text-zinc-500 leading-relaxed uppercase font-bold tracking-widest">Ajuste as relações abaixo</p>
                        </div>
                        <div className="flex-1 overflow-y-auto p-8 space-y-8 custom-scrollbar">
                            {schemas[paymentType].map(field => (
                                <div key={field.key} className="space-y-3">
                                    <div className="flex justify-between items-center px-1">
                                        <span className="text-xs font-bold text-slate-700 dark:text-zinc-400 uppercase tracking-widest">{field.label}</span>
                                        {field.required && <span className="text-[10px] text-emerald-500 font-bold bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20">Obrigatório</span>}
                                    </div>
                                    <select 
                                        value={columnMapping[field.key] || ''}
                                        onChange={(e) => setColumnMapping(prev => ({ ...prev, [field.key]: e.target.value }))}
                                        className="w-full bg-slate-50 dark:bg-[#151515] border border-slate-200 dark:border-zinc-800 rounded-2xl px-5 py-4 text-sm text-slate-900 dark:text-white focus:border-emerald-600 transition-all outline-none appearance-none cursor-pointer hover:bg-slate-100 dark:hover:bg-zinc-800/50"
                                    >
                                        <option value="">Ignorar este campo</option>
                                        {rawHeaders.map(h => <option key={h} value={h}>{h}</option>)}
                                    </select>
                                </div>
                            ))}
                        </div>
                        <div className="p-8 bg-slate-50 dark:bg-[#151515] border-t border-slate-200 dark:border-zinc-800 flex justify-end shrink-0">
                            <button 
                                onClick={confirmMapping}
                                disabled={loading}
                                className="w-full py-4 bg-emerald-600 hover:bg-emerald-500 text-white rounded-2xl font-bold text-sm uppercase tracking-widest shadow-xl shadow-emerald-900/40 transition-all hover:-translate-y-1 active:translate-y-0 flex items-center justify-center gap-3 disabled:opacity-50"
                            >
                                {loading ? "Validando..." : "Próxima Etapa: Validar"}
                                <ArrowRight size={20} />
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* --- STEP 3: VALIDATE --- */}
            {step === 'validate' && (
                <div className="flex-1 flex flex-col space-y-6 min-h-0 animate-in fade-in zoom-in-95 duration-700">
                    <div className="bg-white dark:bg-[#1b1b1b] p-5 rounded-3xl border border-slate-200 dark:border-zinc-800 flex justify-between items-center shadow-2xl shrink-0">
                        <div className="flex items-center gap-6 flex-wrap">
                            {validationErrors?.erros && validationErrors.erros.length > 0 ? (
                                <span className="bg-rose-500 text-white text-[10px] font-bold px-4 py-1.5 rounded-full uppercase tracking-[0.2em] shadow-lg shadow-rose-500/20 flex items-center gap-2">
                                    <AlertCircle size={14} />
                                    {validationErrors.erros.length} Erro(s) Encontrado(s)
                                </span>
                            ) : (
                                <span className="bg-emerald-500 text-white text-[10px] font-bold px-4 py-1.5 rounded-full uppercase tracking-[0.2em] shadow-lg shadow-emerald-500/20">Validação Ativa</span>
                            )}
                            <div className="flex items-center gap-2 text-slate-600 dark:text-zinc-500 text-xs">
                                <AlertCircle size={14} className={validationErrors?.erros?.length > 0 ? "text-rose-500" : "text-emerald-500"} />
                                <span>
                                    {validationErrors?.erros && validationErrors.erros.length > 0 
                                        ? "Campos em vermelho contêm erros. Corrija antes de gerar a remessa."
                                        : "Todos os campos estão válidos. Você pode gerar a remessa."}
                                </span>
                            </div>
                            {validationErrors?.erros && validationErrors.erros.length > 0 && (
                                <button
                                    onClick={() => setShowErrorLogs(!showErrorLogs)}
                                    className="flex items-center gap-2 px-3 py-1.5 bg-rose-500/10 text-rose-500 hover:bg-rose-500/20 border border-rose-500/20 rounded-lg transition-colors"
                                >
                                    <FileText size={14} />
                                    <span className="text-xs font-bold uppercase">Ver Logs ({validationErrors.erros.length})</span>
                                </button>
                            )}
                        </div>
                        <button 
                            disabled={loading || (validationErrors?.erros && validationErrors.erros.length > 0)}
                            className={cn(
                                "px-8 py-3 rounded-2xl font-bold text-xs uppercase tracking-widest flex items-center gap-2 shadow-xl transition-all",
                                validationErrors?.erros && validationErrors.erros.length > 0
                                    ? "bg-slate-300 dark:bg-zinc-700 text-slate-600 dark:text-zinc-400 cursor-not-allowed"
                                    : "bg-emerald-600 hover:bg-emerald-500 text-white shadow-emerald-900/40"
                            )}
                            onClick={finalize}
                        >
                            <Save size={18} />
                            {loading ? "Gerando..." : "Gerar Remessa"}
                        </button>
                    </div>

                    {/* Painel de Logs de Erro */}
                    {validationErrors?.erros && validationErrors.erros.length > 0 && (
                        <AnimatePresence>
                            {showErrorLogs && (
                                <motion.div
                                    initial={{ opacity: 0, height: 0 }}
                                    animate={{ opacity: 1, height: 'auto' }}
                                    exit={{ opacity: 0, height: 0 }}
                                    className="bg-rose-500/10 border-2 border-rose-500/40 rounded-2xl p-6 space-y-4 shadow-xl shadow-rose-500/10"
                                >
                                    <div className="flex justify-between items-center">
                                        <h3 className="text-lg font-bold text-rose-600 dark:text-rose-400 flex items-center gap-2">
                                            <AlertCircle size={20} />
                                            logs de erro da remessa
                                            <span className="text-xs bg-rose-500/20 px-2 py-1 rounded-full">
                                                {validationErrors.erros.length} erro(s)
                                            </span>
                                        </h3>
                                        <button
                                            onClick={() => setShowErrorLogs(false)}
                                            className="text-rose-600 dark:text-rose-400 hover:text-rose-700 dark:hover:text-rose-300 transition-colors p-1 hover:bg-rose-500/10 rounded"
                                        >
                                            <X size={20} />
                                        </button>
                                    </div>
                                    <div className="bg-slate-50 dark:bg-[#151515] rounded-xl p-4 border border-rose-500/20">
                                        <div className="space-y-2 text-xs">
                                            <div className="text-slate-600 dark:text-zinc-400 mb-4">
                                                <span className="text-emerald-500 dark:text-emerald-400 font-bold">Total de linhas processadas:</span> {validationErrors.total_linhas || 0}
                                            </div>
                                            <div className="space-y-3">
                                                <div className="text-rose-500 dark:text-rose-400 font-bold text-sm mb-3 flex items-center gap-2">
                                                    <AlertCircle size={16} />
                                                    Erros encontrados por linha:
                                                </div>
                                                {validationErrors.erros.map(([rowIndex, errors], idx) => (
                                                    <div key={idx} className="bg-rose-500/10 border border-rose-500/30 rounded-lg p-4 hover:bg-rose-500/15 transition-colors">
                                                        <div className="text-rose-500 dark:text-rose-400 font-bold mb-2 flex items-center gap-2">
                                                            <span className="bg-rose-500/20 px-2 py-1 rounded text-xs">Linha {rowIndex + 1}</span>
                                                        </div>
                                                        <div className="space-y-2 ml-2">
                                                            {Object.entries(errors).map(([field, message]) => (
                                                                <div key={field} className="text-rose-600 dark:text-rose-300 text-xs">
                                                                    <span className="text-rose-600 dark:text-rose-500 font-bold font-mono">{field}:</span>
                                                                    <span className="ml-2">{message}</span>
                                                                </div>
                                                            ))}
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                </motion.div>
                            )}
                        </AnimatePresence>
                    )}

                    {/* Tabela de Validação com ExcelTable */}
                    <div className="flex-1 min-h-0">
                        {tableData.length > 0 && validatedColumns.length > 0 ? (
                            <CnabExcelTable
                                data={tableData}
                                columns={validatedColumns}
                                pageSize={20}
                                rowKey="id"
                            />
                        ) : (
                            <div className="bg-[#1b1b1b] rounded-3xl border border-zinc-800 overflow-hidden shadow-2xl p-4 h-full flex items-center justify-center">
                                <div className="text-zinc-500">Carregando dados de validação...</div>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* --- STEP 4: SUCCESS --- */}
            {step === 'success' && (
                <motion.div initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} className="flex-1 flex flex-col items-center justify-center space-y-10 text-center">
                    <div className="relative">
                        <div className="absolute inset-0 bg-emerald-500 rounded-full blur-[60px] opacity-20 animate-pulse" />
                        <div className="w-40 h-40 bg-emerald-600 rounded-full flex items-center justify-center shadow-2xl relative">
                            <CheckCircle2 className="w-20 h-20 text-white" strokeWidth={3} />
                        </div>
                    </div>
                    <div className="space-y-3">
                        <h2 className="text-5xl font-bold text-slate-900 dark:text-white tracking-tighter">Missão Cumprida!</h2>
                        <p className="text-slate-600 dark:text-zinc-500 text-lg max-w-md mx-auto">O arquivo CNAB 240 foi gerado com sucesso e está pronto para o banco.</p>
                    </div>
                    <div className="flex gap-6 items-center">
                        <button onClick={reset} className="px-10 py-5 bg-slate-200 dark:bg-[#1b1b1b] hover:bg-slate-300 dark:hover:bg-zinc-800 text-slate-700 dark:text-zinc-300 rounded-2xl font-bold text-sm uppercase tracking-widest transition-all">
                            Nova Remessa
                        </button>
                        <button 
                            onClick={downloadRemessa}
                            className="px-10 py-5 bg-white dark:bg-white text-slate-900 dark:text-black hover:bg-slate-100 dark:hover:bg-zinc-200 rounded-2xl font-bold text-sm uppercase tracking-widest transition-all shadow-2xl flex items-center gap-3"
                        >
                            <Download size={20} />
                            Baixar Arquivo .REM
                        </button>
                    </div>
                </motion.div>
            )}

            {/* Assistant Modal */}
            <AnimatePresence>
                {showAssistant && (
                    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-xl p-6" onClick={() => setShowAssistant(false)}>
                        <motion.div 
                            initial={{ opacity:0, y:20 }} 
                            animate={{ opacity:1, y:0 }} 
                            exit={{ opacity:0, y:20 }} 
                            onClick={(e) => e.stopPropagation()}
                            className="bg-white dark:bg-[#1e1e1e] border border-slate-200 dark:border-zinc-800 w-full max-w-3xl rounded-[2.5rem] shadow-2xl overflow-hidden p-10 space-y-8"
                        >
                            <div className="space-y-4">
                                <h3 className="text-3xl font-bold text-slate-900 dark:text-white tracking-tighter">Assistente Inteligente</h3>
                                <p className="text-slate-600 dark:text-zinc-400 text-lg leading-relaxed">
                                    Antes de validar os dados, certifique-se de que as colunas da sua planilha estão corretamente alinhadas.
                                    Use os seletores acima para indicar qual informação cada coluna representa.
                                </p>
                            </div>

                            <div className="bg-slate-50 dark:bg-[#151515] border border-slate-200 dark:border-zinc-800 rounded-[1.5rem] overflow-hidden">
                                <table className="w-full text-left text-sm">
                                    <thead className="bg-emerald-600 text-white font-bold uppercase tracking-widest text-[10px]">
                                        <tr>
                                            <th className="px-6 py-4">Coluna</th>
                                            <th className="px-6 py-4">Descrição</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-200 dark:divide-zinc-800 text-slate-700 dark:text-zinc-400">
                                        {schemas[effectivePaymentType].map(f => (
                                            <tr key={f.key}>
                                                <td className="px-6 py-4 font-mono text-emerald-500 dark:text-emerald-400 font-bold">{f.key}</td>
                                                <td className="px-6 py-4">{f.label}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>

                            <button onClick={() => setShowAssistant(false)} className="w-full py-5 bg-emerald-600 hover:bg-emerald-500 text-white font-bold uppercase tracking-widest rounded-2xl transition-all shadow-xl shadow-emerald-900/40">
                                Entendi
                            </button>
                        </motion.div>
                    </div>
                )}
            </AnimatePresence>
        </div>
    );
};

export default GerarRemessaView;
