import React, { useMemo } from 'react';
import { motion } from 'framer-motion';
import { 
  Users, 
  FileText, 
  DollarSign, 
  BarChart3, 
  Activity
} from 'lucide-react';
import { 
  ResponsiveContainer, 
  AreaChart, 
  Area, 
  CartesianGrid, 
  XAxis, 
  YAxis, 
  Tooltip 
} from 'recharts';
import { cn } from '@/lib/utils';
import CnabExcelTable from '../../components/CnabExcelTable';
import { TrendingUp } from 'lucide-react';

/**
 * Cartão de Estatística (KPI) Premium
 */
const StatCard = ({ title, value, icon: Icon, detail, color = "emerald" }) => {
  const colorMap = {
    emerald: "text-emerald-500 bg-emerald-500/10 border-emerald-500/20",
    amber: "text-amber-500 bg-amber-500/10 border-amber-500/20",
    blue: "text-blue-500 bg-blue-500/10 border-blue-500/20"
  };

  return (
    <motion.div 
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="bg-white dark:bg-[#1b1b1b] border border-zinc-200 dark:border-zinc-800 rounded-3xl p-6 shadow-sm flex flex-col justify-between group hover:border-emerald-500/30 transition-all relative overflow-hidden"
    >
      <div className="flex justify-between items-start mb-4">
          <div className={cn("p-3 rounded-2xl border shadow-inner", colorMap[color])}>
              <Icon size={24} />
          </div>
          <div className="bg-zinc-50 dark:bg-zinc-800/50 p-1.5 rounded-xl border border-zinc-100 dark:border-zinc-700/50">
             <TrendingUp size={14} className="text-zinc-400" />
          </div>
      </div>
      
      <div>
          <h3 className="text-slate-600 dark:text-zinc-300 text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest mb-1">{title}</h3>
          <p className="text-[clamp(1.125rem,1.8vw,1.5rem)] font-bold text-slate-900 dark:text-white tracking-tighter truncate">{value}</p>
          <div className="flex items-center gap-2 mt-1">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
            <p className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-600 dark:text-zinc-300 font-bold uppercase tracking-tighter">{detail}</p>
          </div>
      </div>
    </motion.div>
  );
};

const DashboardMenu = React.memo(({ 
  loading, 
  stats, 
  chartData, 
  reportData, 
  paymentMode,
  timeFilter,
  setTimeFilter,
  onOpenPagamentos,
  formatMoney
}) => {
  const getIcon = (title) => {
    if (title.includes('Favorecidos')) return Users;
    if (title.includes('Valor')) return DollarSign;
    return FileText;
  };

  const dashboardColumns = useMemo(() => [
    { field: 'n_remessa', header: 'Remessa', width: '100px', render: (row) => <span className="font-bold text-emerald-500">#{row.n_remessa || '---'}</span> },
    { field: 'VALOR_PAGAMENTO', header: 'Valor', width: '150px', render: (row) => <span className="font-mono font-bold text-slate-900 dark:text-white text-[clamp(0.875rem,1vw,0.9375rem)]">{formatMoney(row.VALOR_PAGAMENTO || row.total || 0)}</span> },
    { field: 'data_pagamento', header: 'Pagamento', width: '120px', render: (row) => <span className="text-slate-600 dark:text-zinc-400 text-[clamp(0.75rem,0.9vw,0.8125rem)]">{row.data_pagamento || '---'}</span> }
  ], [formatMoney]);

  return (
    <motion.div 
      key={`dashboard-menu-${paymentMode}`}
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.2 }}
      className="flex-1 space-y-8 overflow-auto custom-scrollbar pr-2 pb-8"
    >
        {/* Filtro e Título da Seção */}
        <div className="flex justify-between items-center">
           <div className="flex items-center gap-2">
               <div className="w-1.5 h-6 bg-emerald-500 rounded-full" />
               <h3 className="text-[clamp(1rem,1.5vw,1.375rem)] font-bold text-slate-900 dark:text-white tracking-tight uppercase">Visão Mensal</h3>
           </div>
           
           <div className="flex items-center gap-3 bg-white dark:bg-zinc-900/50 p-1.5 rounded-2xl border border-slate-200 dark:border-zinc-800">
               {['Todos', 'Ano', 'Mes'].map((f) => (
                   <button
                     key={f}
                     onClick={() => setTimeFilter(f)}
                     className={cn(
                        "px-4 py-1.5 rounded-xl text-[clamp(0.75rem,0.9vw,0.8125rem)] font-bold uppercase tracking-widest transition-all",
                        timeFilter === f ? "bg-emerald-500 text-white" : "text-slate-600 dark:text-zinc-500 hover:text-slate-900 dark:hover:text-zinc-300"
                     )}
                   >
                    {f === 'Mes' ? 'Mês Vigente' : f === 'Ano' ? 'Ano Vigente' : 'Todo Período'}
                   </button>
               ))}
           </div>
        </div>

        {/* Grid de Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {stats.map((stat, idx) => (
                <StatCard 
                  key={idx}
                  {...stat}
                  icon={getIcon(stat.title)}
                  color={idx === 1 ? "amber" : "emerald"}
                />
            ))}
        </div>

        {/* Seção de Gráfico e Tabela Lado a Lado ou Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
            {/* Gráfico de Evolução (Valor Total por mês) */}
            <div className="lg:col-span-12 bg-white dark:bg-[#1b1b1b] border border-zinc-200 dark:border-zinc-800 rounded-[2.5rem] p-8 shadow-sm flex flex-col group overflow-hidden relative min-h-[400px]">
                <div className="absolute top-0 right-0 w-64 h-64 bg-emerald-500/5 blur-[100px] rounded-full -translate-y-1/2 translate-x-1/2" />
                
                <div className="flex justify-between items-center mb-8 relative">
                    <div>
                        <h3 className="text-[clamp(1rem,1.5vw,1.375rem)] font-bold text-slate-900 dark:text-white flex items-center gap-2 uppercase tracking-tight">
                            <BarChart3 size={18} className="text-emerald-500" />
                            Fluxo Remessa {paymentMode}
                        </h3>
                        <p className="text-[clamp(0.875rem,1.2vw,1rem)] text-slate-600 dark:text-zinc-300 font-bold uppercase tracking-widest mt-1">Comparativo de volume financeiro mensal</p>
                    </div>
                </div>

                <div className="flex-1 w-full min-h-[300px]">
                    <ResponsiveContainer width="100%" height="100%">
                        <AreaChart data={chartData}>
                            <defs>
                                <linearGradient id="colorValor" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor="#10b981" stopOpacity={0.2}/>
                                    <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                                </linearGradient>
                            </defs>
                            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" className="dark:stroke-[#2a2a2a]" vertical={false} />
                            <XAxis 
                                dataKey="name" 
                                stroke="#64748b" 
                                className="dark:stroke-[#a1a1aa] dark:[&_text]:fill-[#d4d4d8]"
                                fontSize={13} 
                                fontWeight="bold"
                                tickLine={false} 
                                axisLine={false} 
                                dy={10}
                                tick={{ fill: '#475569' }}
                            />
                            <YAxis 
                                stroke="#64748b" 
                                className="dark:stroke-[#a1a1aa] dark:[&_text]:fill-[#d4d4d8]"
                                fontSize={13} 
                                fontWeight="bold"
                                tickLine={false} 
                                axisLine={false} 
                                tickFormatter={(value) => `R$ ${(value / 1000).toFixed(0)}k`}
                                tick={{ fill: '#475569' }}
                            />
                            <Tooltip 
                                contentStyle={{ 
                                  backgroundColor: document.documentElement.classList.contains('dark') ? '#18181b' : '#ffffff',
                                  border: document.documentElement.classList.contains('dark') ? '1px solid #27272a' : '1px solid #e2e8f0',
                                  borderRadius: '16px', 
                                  fontSize: '12px', 
                                  fontWeight: 'bold',
                                  color: document.documentElement.classList.contains('dark') ? '#d4d4d8' : '#1e293b'
                                }}
                                itemStyle={{ color: '#10b981' }}
                                formatter={(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 })}`;
                                }}
                                cursor={{stroke: '#10b981', strokeWidth: 1, strokeDasharray: '4 4'}}
                            />
                            <Area 
                                type="monotone" 
                                dataKey="valor" 
                                stroke="#10b981" 
                                strokeWidth={4}
                                fillOpacity={1} 
                                fill="url(#colorValor)" 
                                animationDuration={1500}
                            />
                        </AreaChart>
                    </ResponsiveContainer>
                </div>
            </div>

            {/* Tabela de Lançamentos Recentes */}
            <div className="lg:col-span-12 space-y-4">
                <div className="flex items-center justify-between px-2">
                    <h3 className="text-[clamp(1rem,1.5vw,1.375rem)] font-bold text-slate-900 dark:text-white uppercase tracking-widest flex items-center gap-2">
                        <Activity size={16} className="text-emerald-500" />
                        Detalhamento de Execuções
                    </h3>
                    <span className="text-[clamp(0.75rem,0.9vw,0.8125rem)] text-slate-600 dark:text-zinc-300 font-bold uppercase tracking-tighter">
                        {reportData.length} registros encontrados
                    </span>
                </div>
                <div className="min-h-[400px]">
                    <CnabExcelTable 
                        data={reportData.map((row, idx) => ({ 
                          ...row, 
                          _uniqueId: `${row.n_remessa || 'rem'}-${row.CPF_CNPJ_FAVORECIDO || idx}-${idx}`
                        }))}
                        columns={dashboardColumns}
                        rowKey="_uniqueId"
                        pageSize={10}
                        onRowClick={onOpenPagamentos}
                    />
                </div>
            </div>
        </div>
    </motion.div>
  );
});

export default DashboardMenu;
