import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Search, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import CnabExcelTable from '../components/CnabExcelTable';
import PagamentosDetailsModal from '../components/PagamentosDetailsModal';
import { useCnabStore } from '../hooks/useCnabStore';
import cnabService from '../services/cnabService';

const TransacoesView = () => {
  const { paymentMode } = useCnabStore();
  const isTed = paymentMode === 'TED';
  const [loading, setLoading] = useState(true);
  const [logsData, setLogsData] = useState([]);
  const [selectedDetailRow, setSelectedDetailRow] = useState(null);

  // Callbacks de formatação
  const formatMoney = useCallback((val) => {
    const numVal = parseFloat(val);
    if (isNaN(numVal) || numVal === null || numVal === undefined) return 'R$ 0,00';
    return `R$ ${numVal.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  }, []);
  
  const formatDoc = useCallback((val) => {
    const clean = String(val || "").replace(/\D/g, "");
    if (clean.length === 11) return clean.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
    if (clean.length === 14) return clean.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1.$2.$3/$4-$5");
    return val;
  }, []);

  // Carrega dados de relatórios
  const loadTransacoesData = useCallback(async () => {
    setLoading(true);
    try {
      const logs = await cnabService.getRelatoriosLogs(isTed);
      // Nova estrutura: a resposta já vem como array de objetos com cpf_cnpj, nomes, etc.
      const logsContent = Array.isArray(logs) ? logs : (logs.Base_Dados_API || []);
      setLogsData(logsContent);
    } catch (error) {
      console.error('[TransacoesView] Erro no carregamento de relatórios:', error);
      toast.error('Erro ao carregar relatórios.');
    } finally {
      setLoading(false);
    }
  }, [isTed]);

  useEffect(() => {
    loadTransacoesData();
  }, [loadTransacoesData]);

  const logsColumns = useMemo(() => isTed ? [
    { field: 'cpf_cnpj', header: 'Documento ID', width: '180px', render: (row) => <span className="font-bold text-slate-800 dark:text-zinc-200">{formatDoc(row.cpf_cnpj)}</span> },
    { field: 'banco', header: 'Banco', width: '100px', render: (row) => <span className="text-slate-600 dark:text-zinc-400 font-mono text-[clamp(0.75rem,0.9vw,0.8125rem)]">{row.banco || '---'}</span> },
    { field: 'agencia', header: 'Agência', width: '100px', render: (row) => <span className="text-slate-600 dark:text-zinc-400 font-mono text-[clamp(0.75rem,0.9vw,0.8125rem)]">{row.agencia || '---'}</span> },
    { field: 'conta', header: 'Conta', width: '120px', render: (row) => <span className="text-slate-600 dark:text-zinc-400 font-mono text-[clamp(0.75rem,0.9vw,0.8125rem)]">{row.conta || '---'}</span> },
    { field: 'valor_total', header: 'Valor Acumulado', width: '180px', render: (row) => <span className="font-mono font-bold text-emerald-500">{formatMoney(row.valor_total)}</span> },
    { field: 'nomes_e_valores', header: 'Ações', width: '150px', render: (row) => (
      <button 
        onClick={(e) => {
          e.stopPropagation();
          setSelectedDetailRow(row);
        }}
        className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 dark:bg-zinc-800 hover:bg-slate-300 dark:hover:bg-zinc-700 rounded-xl transition-colors text-[clamp(0.6vw,0.55rem,0.7rem)] font-bold uppercase tracking-widest text-slate-700 dark:text-zinc-400 hover:text-slate-900 dark:hover:text-white border border-slate-300 dark:border-zinc-700"
      >
        <Search size={12} />
        Detalhes
      </button>
    )}
  ] : [
    { field: 'cpf_cnpj', header: 'Documento ID', width: '180px', render: (row) => <span className="font-bold text-slate-800 dark:text-zinc-200">{formatDoc(row.cpf_cnpj)}</span> },
    { field: 'qtd_nomes', header: 'Qtd. Nomes', width: '120px', render: (row) => (
      <div className="flex items-center gap-2">
        <span className="px-2 py-0.5 rounded-full bg-slate-200 dark:bg-zinc-800 text-slate-700 dark:text-zinc-300 text-[clamp(0.75vw,0.7rem,0.9rem)] font-bold">{row.qtd_nomes}</span>
      </div>
    )},
    { field: 'valor_total', header: 'Valor Acumulado', width: '180px', render: (row) => <span className="font-mono font-bold text-emerald-500">{formatMoney(row.valor_total)}</span> },
    { field: 'CHAVE_PIX', header: 'Dados Pix', width: '220px', render: (row) => <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-600 dark:text-zinc-500 font-mono italic">{row.CHAVE_PIX || 'N/A'}</span> },
    { field: 'nomes_e_valores', header: 'Ações', width: '150px', render: (row) => (
      <button 
        onClick={(e) => {
          e.stopPropagation();
          setSelectedDetailRow(row);
        }}
        className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 dark:bg-zinc-800 hover:bg-slate-300 dark:hover:bg-zinc-700 rounded-xl transition-colors text-[clamp(0.6vw,0.55rem,0.7rem)] font-bold uppercase tracking-widest text-slate-700 dark:text-zinc-400 hover:text-slate-900 dark:hover:text-white border border-slate-300 dark:border-zinc-700"
      >
        <Search size={12} />
        Detalhes
      </button>
    )}
  ], [isTed, formatDoc, formatMoney]);

  const handleClosePagamentosModal = useCallback(() => {
    setSelectedDetailRow(null);
  }, []);

  return (
    <div className="h-full flex flex-col space-y-6 animate-in fade-in duration-700">
      {/* Header */}
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 shrink-0 bg-white dark:bg-zinc-900/50 p-6 rounded-[2.5rem] border border-slate-200 dark:border-white/5 shadow-2xl">
        <div className="flex items-center gap-4">
           <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center shadow-lg shadow-emerald-500/20">
              <Search className="text-white" size={28} />
           </div>
           <div>
              <h2 className="text-[clamp(1.25rem,2vw,1.75rem)] font-bold text-slate-900 dark:text-white tracking-tighter leading-none mb-1">
                <span className="text-emerald-500">Relatórios</span>
              </h2>
              <p className="text-slate-600 dark:text-zinc-300 text-[clamp(0.875rem,1.2vw,1rem)] font-bold uppercase tracking-widest">
                Ambiente de Gestão <span className="text-emerald-500">{paymentMode}</span>
              </p>
           </div>
        </div>
      </div>

      {loading ? (
        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          className="flex-1 flex flex-col items-center justify-center space-y-4"
        >
          <div className="w-16 h-16 rounded-3xl bg-emerald-500/10 border border-emerald-500/20 animate-spin flex items-center justify-center">
            <Loader2 className="text-emerald-500 w-8 h-8" />
          </div>
          <p className="text-slate-600 dark:text-zinc-300 text-[clamp(0.875rem,1vw,0.9375rem)] font-bold uppercase tracking-[0.3em]">Carregando relatórios...</p>
        </motion.div>
      ) : (
        <motion.div 
          key={`transacoes-${paymentMode}`}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          className="flex-1 space-y-6 overflow-auto custom-scrollbar pr-2 pb-8"
        >
          {/* Tabela de Relatórios */}
          <div className="min-h-[500px]">
            <CnabExcelTable 
              data={logsData}
              columns={logsColumns}
              rowKey="cpf_cnpj"
            />
          </div>
        </motion.div>
      )}

      <PagamentosDetailsModal
        isOpen={!!selectedDetailRow}
        onClose={handleClosePagamentosModal}
        row={selectedDetailRow}
      />
    </div>
  );
};

export default TransacoesView;
