import { useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, Edit2, Trash2, Calendar, FileText, Smartphone, DollarSign, Activity, FileCheck, ArrowRight, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';
import { useCnabStore } from '../hooks/useCnabStore';
import { useFavorecidos } from '../hooks/useFavorecidos';
import { getTipoChavePixText } from '../utils/pixUtils';

const DetailsPanel = ({ favorecido, onClose, onEdit }) => {
  const { paymentMode } = useCnabStore();
  const { historico, loadingHistorico, fetchHistorico, handleDelete } = useFavorecidos();
  
  const nomeExibicao = favorecido?.NOME_FAVORECIDO || favorecido?.nome || '';
  const documentoExibicao = favorecido?.CPF_CNPJ_FAVORECIDO || favorecido?.documento || '';

  useEffect(() => {
    if (nomeExibicao) {
        fetchHistorico(nomeExibicao);
    }
  }, [nomeExibicao, fetchHistorico]);

  if (!favorecido) return null;

  // Formata o histórico para o gráfico (agregando por mês se necessário, ou mostrando itens)
  // Baseado no legado, ele espera uma estrutura de gráfico de barras.
  const chartData = (historico || []).slice(0, 6).map(item => {
      // Formata a data para exibição (DD/MM/YYYY ou YYYY-MM-DD)
      let dateLabel = '---';
      if (item.data) {
          if (item.data.includes('/')) {
              // Formato DD/MM/YYYY
              dateLabel = item.data;
          } else if (item.data.includes('-')) {
              // Formato YYYY-MM-DD
              const [year, month, day] = item.data.split('-');
              dateLabel = `${day}/${month}/${year}`;
          } else {
              dateLabel = item.data;
          }
      }
      
      return {
          name: dateLabel,
          value: parseFloat(item.valor) || 0,
          fullDate: item.data
      };
  }).reverse();

  // Função para formatar documentos conforme legado
  const formatDocumento = (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;
  };

  return (
    <motion.div 
      initial={{ x: '100%', opacity: 0 }}
      animate={{ x: 0, opacity: 1 }}
      exit={{ x: '100%', opacity: 0 }}
      transition={{ type: "spring", stiffness: 300, damping: 30 }}
      className="fixed top-0 right-0 h-full w-full md:w-[600px] bg-white dark:bg-[#1b1b1b] border-l border-slate-200 dark:border-zinc-800 shadow-2xl z-[70] overflow-y-auto custom-scrollbar"
    >
      {/* Header */}
      <div className="sticky top-0 bg-white/95 dark:bg-[#1b1b1b]/95 backdrop-blur-sm border-b border-slate-200 dark:border-zinc-800 p-6 flex justify-between items-start z-10 text-slate-900 dark:text-white">
        <div>
           <div className="flex items-center gap-3 mb-2">
               <div className="w-12 h-12 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-500 font-bold text-[clamp(1rem,1.5vw,1.375rem)] uppercase">
                    {nomeExibicao.charAt(0)}
               </div>
               <div>
                   <h2 className="text-[clamp(1rem,1.5vw,1.375rem)] font-bold leading-tight max-w-[300px] text-slate-900 dark:text-white">{nomeExibicao}</h2>
                   <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-600 dark:text-zinc-300 font-mono">{formatDocumento(documentoExibicao)}</span>
               </div>
           </div>
           
           <div className="flex gap-2 mt-2">
                 <span className={cn(
                     "px-2 py-0.5 rounded text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase border",
                     (favorecido.status === 'Ativo' || !favorecido.status)
                     ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-500" 
                     : "bg-slate-200 dark:bg-zinc-800 border-slate-300 dark:border-zinc-700 text-slate-700 dark:text-zinc-300"
                 )}>
                     {favorecido.status || 'Ativo'}
                 </span>
                 <span className="px-2 py-0.5 rounded text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase border bg-slate-200 dark:bg-zinc-800 border-slate-300 dark:border-zinc-700 text-slate-700 dark:text-zinc-300 font-mono">
                     TIPO: {paymentMode}
                 </span>
           </div>
        </div>

        <div className="flex gap-2">
             <button 
                title="Editar" 
                onClick={() => {
                  if (onEdit) {
                    onEdit(favorecido);
                    onClose();
                  }
                }}
                className="p-2 hover:bg-slate-100 dark:hover:bg-zinc-800 rounded-lg text-slate-600 dark:text-zinc-400 hover:text-slate-900 dark:hover:text-white transition-colors"
             >
                 <Edit2 size={18} />
             </button>
             <button 
                title="Desativar" 
                onClick={() => {
                  if (confirm("Deseja realmente inativar este favorecido?")) {
                    handleDelete(favorecido.id || favorecido.idfavorecido || favorecido.idcnab_pralog);
                  }
                }}
                className="p-2 hover:bg-rose-900/10 rounded-lg text-zinc-400 hover:text-rose-500 transition-colors"
             >
                 <Trash2 size={18} />
             </button>
             <button onClick={onClose} className="p-2 hover:bg-zinc-800 rounded-lg text-zinc-400 hover:text-white transition-colors">
                 <X size={20} />
             </button>
        </div>
      </div>

      {/* Content */}
      <div className="p-6 space-y-8">
        
        {/* Core Information Section */}
        <div className={cn(
            "p-6 rounded-3xl border space-y-6",
            paymentMode === 'TED' ? "bg-emerald-500/5 border-emerald-500/10" : "bg-amber-500/5 border-amber-500/10"
        )}>
            <div className="flex items-center gap-2">
                {paymentMode === 'TED' ? <DollarSign size={16} className="text-emerald-500" /> : <Smartphone size={16} className="text-amber-500" />}
                <h4 className={cn(
                    "text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-[0.2em]",
                    paymentMode === 'TED' ? "text-emerald-500" : "text-amber-500"
                )}>
                    {paymentMode === 'TED' ? "Detalhamento Bancário (TED)" : "Configuração de Chave PIX"}
                </h4>
            </div>
            
            <div className="grid grid-cols-2 gap-6">
                {paymentMode === 'TED' ? (
                    <>
                        <div>
                            <p className="text-slate-600 dark:text-zinc-600 text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold tracking-widest mb-1">Banco</p>
                            <p className="text-slate-900 dark:text-white font-mono text-[clamp(0.875rem,1vw,0.9375rem)] uppercase">{favorecido.BANCO_FAVORECIDO || favorecido.banco || '---'}</p>
                        </div>
                        <div>
                            <p className="text-slate-600 dark:text-zinc-600 text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold tracking-widest mb-1">Finalidade</p>
                            <p className="text-slate-900 dark:text-white font-mono text-[clamp(0.875rem,1vw,0.9375rem)] uppercase">{favorecido.FINALIDADE_TED || favorecido.finalidade || '---'}</p>
                        </div>
                        <div>
                            <p className="text-slate-600 dark:text-zinc-600 text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold tracking-widest mb-1">Agência</p>
                            <p className="text-slate-900 dark:text-white font-mono text-[clamp(0.875rem,1vw,0.9375rem)]">{favorecido.AGENCIA_FAVORECIDA || favorecido.agencia || '---'}{favorecido.DIGITO_AGENCIA ? `-${favorecido.DIGITO_AGENCIA}` : ''}</p>
                        </div>
                        <div>
                            <p className="text-slate-600 dark:text-zinc-600 text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold tracking-widest mb-1">Conta Corrente</p>
                            <p className="text-slate-900 dark:text-white font-mono text-[clamp(0.875rem,1vw,0.9375rem)]">{favorecido.CONTA_FAVORECIDA || favorecido.conta || '---'}-{favorecido.DIGITO_CONTA_FAVORECIDA || favorecido.digitoConta || '0'}</p>
                        </div>
                    </>
                ) : (
                    <>
                        <div className="col-span-2">
                            <p className="text-slate-600 dark:text-zinc-600 text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold tracking-widest mb-1">Chave Pix</p>
                            <p className="text-slate-900 dark:text-white font-mono text-[clamp(1rem,1.5vw,1.375rem)] break-all">{favorecido.CHAVE_PIX || favorecido.pix || '---'}</p>
                        </div>
                        <div>
                            <p className="text-slate-600 dark:text-zinc-600 text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold tracking-widest mb-1">Tipo de Chave</p>
                            <p className="text-slate-900 dark:text-white font-medium text-[clamp(0.875rem,1vw,0.9375rem)]">
                                {getTipoChavePixText(favorecido.TIPO_CHAVE_PIX || favorecido.tipoPix || favorecido.tipo_chave_pix)}
                            </p>
                        </div>
                        <div>
                            <p className="text-slate-600 dark:text-zinc-600 text-[clamp(0.75rem,0.9vw,0.8125rem)] uppercase font-bold tracking-widest mb-1">ID Sistema</p>
                            <p className="text-slate-900 dark:text-white font-mono text-[clamp(0.875rem,1vw,0.9375rem)]">{favorecido.idfavorecido || favorecido.id || '---'}</p>
                        </div>
                    </>
                )}
            </div>
        </div>

        {/* Financial Growth Chart */}
        <div>
            <div className="flex items-center justify-between mb-4">
                <h3 className="text-slate-900 dark:text-white text-[clamp(1rem,1.5vw,1.375rem)] font-bold flex items-center gap-2">
                    <Activity size={18} className="text-emerald-500" />
                    Faturamento / Pagamentos
                </h3>
                <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-600 dark:text-zinc-500 font-medium bg-slate-100 dark:bg-zinc-900 px-2 py-1 rounded">Volume Recente</span>
            </div>
            
            <div className="h-48 w-full bg-slate-50 dark:bg-[#151515] border border-slate-200 dark:border-zinc-800 rounded-3xl p-6 shadow-inner relative flex flex-col justify-center">
                 {loadingHistorico ? (
                     <div className="flex flex-col items-center gap-2">
                         <Loader2 className="animate-spin text-emerald-500" />
                         <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-600 dark:text-zinc-600 font-bold uppercase tracking-widest">Sincronizando faturamento...</span>
                     </div>
                 ) : chartData.length > 0 ? (
                     <ResponsiveContainer width="100%" height="100%">
                        <LineChart data={chartData} margin={{ top: 5, right: 10, left: -20, bottom: 40 }}>
                            <CartesianGrid strokeDasharray="3 3" stroke={document.documentElement.classList.contains('dark') ? "#27272a" : "#e2e8f0"} vertical={false} />
                            <XAxis 
                                dataKey="name" 
                                stroke="#64748b" 
                                className="dark:stroke-[#a1a1aa]"
                                fontSize={13} 
                                fontWeight="bold"
                                tickLine={false} 
                                axisLine={false}
                                angle={-45}
                                textAnchor="end"
                                height={60}
                                tick={{ fill: document.documentElement.classList.contains('dark') ? '#d4d4d8' : '#475569' }}
                            />
                            <YAxis 
                                stroke="#64748b" 
                                className="dark:stroke-[#a1a1aa]"
                                fontSize={13} 
                                fontWeight="bold"
                                tickLine={false} 
                                axisLine={false}
                                tickFormatter={(value) => `R$ ${(value / 1000).toFixed(0)}k`}
                                tick={{ fill: document.documentElement.classList.contains('dark') ? '#d4d4d8' : '#475569' }}
                            />
                            <Tooltip 
                                cursor={{stroke: '#10b981', strokeWidth: 1, strokeDasharray: '5 5'}}
                                contentStyle={{ 
                                    backgroundColor: document.documentElement.classList.contains('dark') ? '#18181b' : '#ffffff', 
                                    borderColor: document.documentElement.classList.contains('dark') ? '#27272a' : '#e2e8f0', 
                                    color: document.documentElement.classList.contains('dark') ? '#fff' : '#1e293b', 
                                    borderRadius: '8px' 
                                }}
                                itemStyle={{ color: '#10b981' }}
                                formatter={(value) => [`R$ ${value.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`, 'Valor Pagamento']}
                            />
                            <Line 
                                type="monotone" 
                                dataKey="value" 
                                stroke="#10b981" 
                                strokeWidth={3}
                                dot={{ fill: '#10b981', r: 4, strokeWidth: 2, stroke: '#065f46' }}
                                activeDot={{ r: 6, fill: '#10b981', stroke: '#065f46', strokeWidth: 2 }}
                            />
                        </LineChart>
                     </ResponsiveContainer>
                 ) : (
                     <div className="text-center text-slate-600 dark:text-zinc-600 italic text-[clamp(0.875rem,1vw,0.9375rem)]">Sem histórico de faturamento disponível.</div>
                 )}
            </div>
        </div>

        {/* Recent Transactions List (HISTORY) */}
        <div>
            <h3 className="text-slate-900 dark:text-white text-[clamp(1rem,1.5vw,1.375rem)] font-bold flex items-center gap-2 mb-4">
                <FileCheck size={18} className="text-emerald-500" />
                Histórico de Remessas
            </h3>
            
            <div className="space-y-3">
                 {loadingHistorico ? (
                     Array(3).fill(0).map((_, i) => (
                         <div key={i} className="h-16 bg-slate-100 dark:bg-zinc-900/50 rounded-xl animate-pulse" />
                     ))
                 ) : historico.length > 0 ? (
                     historico.slice(0, 10).map((rem, i) => (
                         <div key={i} className="flex items-center justify-between p-4 rounded-2xl bg-slate-50 dark:bg-zinc-900/50 border border-slate-200 dark:border-zinc-800 hover:bg-slate-100 dark:hover:bg-zinc-800/80 transition-colors group cursor-pointer">
                             <div className="flex items-center gap-4">
                                 <div className="w-10 h-10 rounded-xl bg-slate-200 dark:bg-zinc-800 flex items-center justify-center text-slate-600 dark:text-zinc-500 group-hover:text-emerald-400 transition-colors">
                                     <FileText size={16} />
                                 </div>
                                 <div className="flex flex-col">
                                     <p className="text-slate-900 dark:text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-bold group-hover:text-emerald-400 transition-colors uppercase tracking-tight">REM-{rem.codigoSolicitacao || i + 1000}</p>
                                     <p className="text-slate-600 dark:text-zinc-500 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase">{rem.data || rem.dataEmissao || 'Data N/D'}</p>
                                 </div>
                             </div>
                             <div className="text-right">
                                 <p className="text-slate-900 dark:text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-mono font-bold">R$ {(parseFloat(rem.valor) || 0).toLocaleString()}</p>
                                 <span className={cn(
                                     "text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-wider",
                                     rem.situacao?.includes('PAGO') ? "text-emerald-500" : "text-amber-500"
                                 )}>
                                     {rem.situacao || 'PROCESSADA'}
                                 </span>
                             </div>
                         </div>
                     ))
                 ) : (
                     <div className="p-10 border border-dashed border-slate-200 dark:border-zinc-800 rounded-3xl flex flex-col items-center gap-2 opacity-30">
                         <FileText size={32} strokeWidth={1} />
                         <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest text-slate-500 dark:text-zinc-500">Nenhuma remessa encontrada</span>
                     </div>
                 )}
                 
                 {historico.length > 10 && (
                     <button className="w-full py-4 mt-2 flex items-center justify-center gap-2 text-slate-600 dark:text-zinc-500 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-[0.2em] hover:text-emerald-500 hover:bg-emerald-500/5 rounded-2xl transition-all border border-transparent hover:border-emerald-500/20">
                         Ver histórico completo ({historico.length})
                         <ArrowRight size={14} />
                     </button>
                 )}
            </div>
        </div>

      </div>
    </motion.div>
  );
};

export default DetailsPanel;
