import React, { useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Calendar, DollarSign, FileText, ArrowLeft, Loader2, Filter } from 'lucide-react';
import { useCnabStore } from '../hooks/useCnabStore';
import CnabExcelTable from './CnabExcelTable';

/**
 * Modal de histórico de pagamentos para um favorecido específico
 * Por enquanto usa dados fictícios até implementar o backend
 */
const HistoricoPagamentosModal = ({ isOpen, onClose, favorecido }) => {
  const { paymentMode } = useCnabStore();
  const [periodFilter, setPeriodFilter] = useState({ type: 'todos', dataInicio: null, dataFim: null });

  const formatMoney = React.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 = React.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;
  }, []);

  const formatDate = React.useCallback((dateStr) => {
    if (!dateStr) return '---';
    try {
      // Se já está no formato DD/MM/YYYY, retorna como está
      if (dateStr.includes('/') && dateStr.length === 10) {
        return dateStr;
      }
      // Se está no formato YYYY-MM-DD, converte para DD/MM/YYYY
      if (dateStr.includes('-') && dateStr.length === 10) {
        const [year, month, day] = dateStr.split('-');
        return `${day}/${month}/${year}`;
      }
      // Caso contrário, tenta converter
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;
      return date.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' });
    } catch {
      return dateStr;
    }
  }, []);

  // Usa dados reais das remessas do backend ou dados fictícios como fallback
  const historicoDataRaw = useMemo(() => {
    // Se houver remessas do backend, usa elas
    // Suporta pagamentos (nova estrutura), detalhes_pagamentos e remessas (estrutura antiga)
    const pagamentos = favorecido?.pagamentos || favorecido?.detalhes_pagamentos || favorecido?.remessas;
    
    if (pagamentos && Array.isArray(pagamentos) && pagamentos.length > 0) {
      return pagamentos.map((pagamento, idx) => {
        // Nova estrutura: data, n_remessa, valor
        // Estrutura antiga: data_pagamento, n_remessa, valor
        const dataPagamento = pagamento.data || pagamento.data_pagamento || '---';
        const nRemessa = pagamento.n_remessa || '---';
        const valor = parseFloat(pagamento.valor || 0);
        
        return {
          id: `remessa-${nRemessa}-${idx}`,
          data_pagamento: dataPagamento,
          valor: valor,
          n_remessa: nRemessa,
          nome_favorecido: favorecido.nome || 'Favorecido'
        };
      }).sort((a, b) => {
        // Ordena por data (mais recente primeiro)
        // Converte DD/MM/YYYY ou YYYY-MM-DD para Date para ordenação
        try {
          let dateA = a.data_pagamento;
          let dateB = b.data_pagamento;
          
          // Se está no formato DD/MM/YYYY, converte
          if (dateA.includes('/') && dateA.length === 10) {
            dateA = dateA.split('/').reverse().join('-');
          }
          if (dateB.includes('/') && dateB.length === 10) {
            dateB = dateB.split('/').reverse().join('-');
          }
          
          return new Date(dateB) - new Date(dateA);
        } catch {
          return 0;
        }
      });
    }

    // Fallback: Gera dados fictícios se não houver remessas
    if (!favorecido?.cpf_cnpj) return [];

    const doc = favorecido.cpf_cnpj;
    const nomeBase = favorecido.nome || 'Favorecido';
    
    const pagamentosFicticios = [];
    const hoje = new Date();
    const mesesAtras = 6;
    
    for (let i = 0; i < 10; i++) {
      const diasAtras = Math.floor(Math.random() * (mesesAtras * 30));
      const dataPagamento = new Date(hoje);
      dataPagamento.setDate(dataPagamento.getDate() - diasAtras);
      
      const valor = Math.floor(Math.random() * 49500) + 500;
      const nRemessa = Math.floor(Math.random() * 9999) + 1000;
      
      pagamentosFicticios.push({
        id: `hist-${doc}-${i}`,
        data_pagamento: dataPagamento.toISOString().split('T')[0],
        valor: valor,
        n_remessa: nRemessa,
        nome_favorecido: nomeBase
      });
    }
    
    return pagamentosFicticios.sort((a, b) => new Date(b.data_pagamento) - new Date(a.data_pagamento));
  }, [favorecido, paymentMode]);

  // Aplica filtro de período
  const historicoData = useMemo(() => {
    if (!historicoDataRaw || historicoDataRaw.length === 0) return [];
    
    if (periodFilter.type === 'todos') {
      return historicoDataRaw;
    }
    
    if (periodFilter.type === 'periodo' && periodFilter.dataInicio && periodFilter.dataFim) {
      return historicoDataRaw.filter(item => {
        try {
          let dataPagamento = item.data_pagamento;
          
          // Converte DD/MM/YYYY para YYYY-MM-DD se necessário
          if (dataPagamento.includes('/') && dataPagamento.length === 10) {
            const [day, month, year] = dataPagamento.split('/');
            dataPagamento = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
          }
          
          // Garante formato YYYY-MM-DD
          if (!dataPagamento.match(/^\d{4}-\d{2}-\d{2}$/)) {
            const date = new Date(dataPagamento);
            if (isNaN(date.getTime())) return false;
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            dataPagamento = `${year}-${month}-${day}`;
          }
          
          // As datas do filtro já vêm no formato YYYY-MM-DD do input type="date"
          const dataInicio = periodFilter.dataInicio;
          const dataFim = periodFilter.dataFim;
          
          // Compara strings no formato YYYY-MM-DD (ordem lexicográfica funciona)
          return dataPagamento >= dataInicio && dataPagamento <= dataFim;
        } catch {
          return false;
        }
      });
    }
    
    return historicoDataRaw;
  }, [historicoDataRaw, periodFilter]);

  const columns = useMemo(() => [
    {
      field: 'data_pagamento',
      header: 'Data Pagamento',
      width: '150px',
      render: (row) => (
        <div className="flex items-center gap-2">
          <Calendar size={14} className="text-slate-500 dark:text-zinc-400" />
          <span className="text-slate-700 dark:text-zinc-300 font-mono text-[clamp(0.75rem,0.9vw,0.8125rem)]">{formatDate(row.data_pagamento)}</span>
        </div>
      ),
    },
    {
      field: 'valor',
      header: 'Valor',
      width: '180px',
      render: (row) => (
        <div className="flex items-center gap-2">
          <DollarSign size={14} className="text-emerald-500" />
          <span className="font-mono font-bold text-emerald-500">{formatMoney(row.valor)}</span>
        </div>
      ),
    },
    {
      field: 'n_remessa',
      header: 'Remessa',
      width: '120px',
      render: (row) => (
        <span className="font-bold text-emerald-500 font-mono">#{row.n_remessa}</span>
      ),
    },
  ], [formatMoney, formatDate, paymentMode]);

  const valorTotal = useMemo(() => {
    return historicoData.reduce((sum, item) => sum + (parseFloat(item.valor) || 0), 0);
  }, [historicoData]);

  if (!isOpen) return null;

  const documento = favorecido?.cpf_cnpj ?? '---';
  const nomeFavorecido = favorecido?.nome || favorecido?.NOME_FAVORECIDO || 'Favorecido';

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-[110] flex items-center justify-center p-4">
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
          className="absolute inset-0 bg-black/80 backdrop-blur-sm"
        />
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 20 }}
          onClick={(e) => e.stopPropagation()}
          className="bg-white dark:bg-[#1b1b1b] border border-slate-200 dark:border-zinc-800 w-full max-w-5xl rounded-[2.5rem] shadow-2xl relative overflow-hidden flex flex-col max-h-[90vh]"
        >
          {/* Header */}
          <div className="p-8 border-b border-slate-200 dark:border-zinc-800 flex justify-between items-center bg-slate-50 dark:bg-zinc-900/50">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-blue-500/10 rounded-2xl border border-blue-500/20">
                <Calendar className="text-blue-500" size={24} />
              </div>
              <div>
                <h2 className="text-[clamp(1rem,1.5vw,1.375rem)] font-bold text-slate-900 dark:text-white tracking-tighter">
                  Histórico de Pagamentos
                </h2>
                <div className="flex flex-wrap items-center gap-3 mt-1.5 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest text-slate-600 dark:text-zinc-300">
                  <span>
                    Documento: <span className="text-emerald-500 font-mono">{formatDoc(documento)}</span>
                  </span>
                  <span>•</span>
                  <span className="truncate max-w-[300px]" title={nomeFavorecido}>
                    {nomeFavorecido}
                  </span>
                </div>
              </div>
            </div>
            <button
              onClick={onClose}
              className="p-3 hover:bg-slate-100 dark:hover:bg-zinc-800 rounded-2xl text-slate-500 dark:text-zinc-500 hover:text-slate-900 dark:hover:text-white transition-all"
            >
              <X size={24} />
            </button>
          </div>

          {/* Filtro de Período */}
          <div className="p-6 bg-slate-50 dark:bg-[#151515] border-b border-slate-200 dark:border-zinc-800">
            <div className="flex flex-wrap items-center gap-4">
              <div className="flex items-center gap-2">
                <Filter size={16} className="text-slate-600 dark:text-zinc-400" />
                <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest text-slate-700 dark:text-zinc-300">
                  Filtrar por:
                </span>
              </div>
              <div className="flex flex-wrap items-center gap-3">
                <button
                  onClick={() => setPeriodFilter({ type: 'todos', dataInicio: null, dataFim: null })}
                  className={`px-4 py-2 rounded-xl text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest transition-all ${
                    periodFilter.type === 'todos'
                      ? 'bg-emerald-500 text-white'
                      : 'bg-white dark:bg-zinc-900 text-slate-600 dark:text-zinc-400 hover:bg-slate-100 dark:hover:bg-zinc-800 border border-slate-200 dark:border-zinc-800'
                  }`}
                >
                  Todos
                </button>
                <button
                  onClick={() => setPeriodFilter({ type: 'periodo', dataInicio: '', dataFim: '' })}
                  className={`px-4 py-2 rounded-xl text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest transition-all ${
                    periodFilter.type === 'periodo'
                      ? 'bg-emerald-500 text-white'
                      : 'bg-white dark:bg-zinc-900 text-slate-600 dark:text-zinc-400 hover:bg-slate-100 dark:hover:bg-zinc-800 border border-slate-200 dark:border-zinc-800'
                  }`}
                >
                  Período
                </button>
                {periodFilter.type === 'periodo' && (
                  <div className="flex items-center gap-2">
                    <label className="text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold text-slate-700 dark:text-zinc-300">
                      De:
                    </label>
                    <input
                      type="date"
                      value={periodFilter.dataInicio || ''}
                      onChange={(e) => setPeriodFilter({ ...periodFilter, dataInicio: e.target.value })}
                      className="px-3 py-2 rounded-xl bg-white dark:bg-zinc-900 text-slate-700 dark:text-zinc-300 border border-slate-200 dark:border-zinc-800 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold"
                    />
                    <label className="text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold text-slate-700 dark:text-zinc-300">
                      Até:
                    </label>
                    <input
                      type="date"
                      value={periodFilter.dataFim || ''}
                      onChange={(e) => setPeriodFilter({ ...periodFilter, dataFim: e.target.value })}
                      className="px-3 py-2 rounded-xl bg-white dark:bg-zinc-900 text-slate-700 dark:text-zinc-300 border border-slate-200 dark:border-zinc-800 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold"
                    />
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Resumo */}
          <div className="p-6 bg-slate-50 dark:bg-[#151515] border-b border-slate-200 dark:border-zinc-800">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-white dark:bg-zinc-900/50 rounded-2xl p-4 border border-slate-200 dark:border-zinc-800">
                <p className="text-slate-600 dark:text-zinc-400 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest mb-1">
                  Total de Pagamentos
                </p>
                <p className="text-[clamp(1.125rem,1.8vw,1.5rem)] font-bold text-slate-900 dark:text-white">{historicoData.length}</p>
              </div>
              <div className="bg-white dark:bg-zinc-900/50 rounded-2xl p-4 border border-slate-200 dark:border-zinc-800">
                <p className="text-slate-600 dark:text-zinc-400 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest mb-1">
                  Valor Total
                </p>
                <p className="text-[clamp(1.125rem,1.8vw,1.5rem)] font-bold text-emerald-500">{formatMoney(valorTotal)}</p>
              </div>
              <div className="bg-white dark:bg-zinc-900/50 rounded-2xl p-4 border border-slate-200 dark:border-zinc-800">
                <p className="text-slate-600 dark:text-zinc-400 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest mb-1">
                  Modo de Pagamento
                </p>
                <p className="text-[clamp(1.125rem,1.8vw,1.5rem)] font-bold text-blue-500">{paymentMode}</p>
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-auto custom-scrollbar p-6">
            {historicoData.length === 0 ? (
              <div className="py-20 flex flex-col items-center justify-center gap-4 text-slate-500 dark:text-zinc-300">
                <FileText size={48} className="opacity-30" />
                <span className="text-[clamp(0.875rem,1vw,0.9375rem)] font-bold uppercase tracking-widest">
                  Nenhum histórico de pagamento encontrado
                </span>
              </div>
            ) : (
              <div className="min-h-[300px]">
                <CnabExcelTable
                  data={historicoData}
                  columns={columns}
                  rowKey="id"
                  pageSize={10}
                />
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="p-6 bg-slate-50 dark:bg-[#151515] border-t border-slate-200 dark:border-zinc-800 flex justify-between items-center">
            <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-700 dark:text-zinc-300 font-bold uppercase tracking-widest">
              Exibindo <span className="text-emerald-500">{historicoData.length}</span> de{' '}
              <span className="text-emerald-500">{historicoData.length}</span> registros
            </span>
            <button
              onClick={onClose}
              className="px-8 py-3 bg-slate-200 dark:bg-zinc-800 hover:bg-slate-300 dark:hover:bg-zinc-700 text-slate-700 dark:text-zinc-300 rounded-xl text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest transition-all"
            >
              Fechar Histórico
            </button>
          </div>
        </motion.div>
      </div>
    </AnimatePresence>
  );
};

export default HistoricoPagamentosModal;
