import { useState, useEffect } from 'react';
import {
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  AreaChart, Area, PieChart, Pie, Cell
} from 'recharts';
import {
  TrendingUp, DollarSign, FileText, Calendar,
  Download, Clock, Zap, ArrowUpRight
} from 'lucide-react';
import { motion } from 'framer-motion';
import { dashboardService } from '../services/dashboardService';
import api from '../services/api';
import clsx from 'clsx';

interface DashboardStats {
  revenueToday: number;
  adsToday: number;
  ticketAverage: number;
  paperOccupation: number;
  weeklyTrend: Array<{ day: string; amount: number }>;
  channelMix: Array<{ name: string; value: number }>;
}

interface RecentListing {
  id: number;
  title: string;
  categoryName: string;
  createdAt: string;
  adFee: number;
  status: string;
}

const COLORS = ['#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#f43f5e'];

export default function AdminDashboard() {
  const [data, setData] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [recentAds, setRecentAds] = useState<RecentListing[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const stats = await dashboardService.getStats();
        setData(stats);
        const res = await api.get('/listings');
        setRecentAds(res.data.slice(0, 5));
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  // Formateadores locales
  const formatCurrency = (val: number) =>
    val.toLocaleString('es-AR', { minimumFractionDigits: 2 });

  const formatLocalTime = (dateString: string) => {
    if (!dateString) return "--:--";
    let isoStr = dateString.replace(" ", "T");
    if (!isoStr.endsWith("Z")) isoStr += "Z";
    return new Date(isoStr).toLocaleTimeString('es-AR', {
      hour: '2-digit', minute: '2-digit', hour12: true,
      timeZone: 'America/Argentina/Buenos_Aires'
    });
  };

  if (loading || !data) return (
    <div className="flex h-screen items-center justify-center bg-slate-50">
      <div className="h-10 w-10 animate-spin rounded-full border-4 border-blue-600 border-t-transparent" />
    </div>
  );

  return (
    <div className="min-h-screen bg-[#f8fafc] p-6 space-y-6">

      {/* HEADER COMPACTO */}
      <div className="flex items-end justify-between">
        <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }}>
          <span className="text-[9px] font-black text-blue-600 uppercase tracking-[0.3em] mb-0.5 block">Inteligencia de Negocio</span>
          <h1 className="text-2xl font-black tracking-tight text-slate-900 uppercase flex items-center gap-2">
            <span className="bg-blue-600 w-1.5 h-6 rounded-full"></span>
            Métricas Globales
          </h1>
          <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mt-1 opacity-80">Estado operativo del diario en tiempo real</p>
        </motion.div>

        <div className="flex gap-3">
          <button className="flex items-center gap-2 rounded-xl bg-white px-4 py-2 text-[10px] font-black uppercase tracking-widest text-slate-600 shadow-sm border border-slate-200 hover:bg-slate-50 transition-all">
            <Download size={14} /> Exportar
          </button>
          <button className="flex items-center gap-2 rounded-xl bg-blue-600 px-4 py-2 text-[10px] font-black uppercase tracking-widest text-white shadow-lg shadow-blue-500/20 hover:bg-blue-700 transition-all">
            <Calendar size={14} /> Últimos 30 días
          </button>
        </div>
      </div>

      {/* GRID DE STATS REFINADO */}
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
        <StatsCard title="Recaudación Hoy" value={`$ ${formatCurrency(data.revenueToday)}`} icon={DollarSign} color="blue" delay={0.1} />
        <StatsCard title="Avisos Publicados" value={data.adsToday} icon={FileText} color="emerald" delay={0.2} />
        <StatsCard title="Ticket Promedio" value={`$ ${formatCurrency(data.ticketAverage)}`} icon={TrendingUp} color="purple" delay={0.3} />
        <StatsCard title="Ocupación Papel" value={`${data.paperOccupation.toFixed(1)}%`} icon={Zap} color="amber" delay={0.4} />
      </div>

      {/* SECCIÓN GRÁFICOS */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">

        {/* Tendencia de Ingresos */}
        <div className="lg:col-span-2 rounded-[2rem] border border-slate-200 bg-white p-8 shadow-xl shadow-slate-200/50">
          <div className="mb-8 flex items-center justify-between">
            <h3 className="text-xs font-black text-slate-500 uppercase tracking-[0.2em]">Tendencia Semanal</h3>
            <span className="text-[10px] font-black text-blue-600 bg-blue-50 px-2.5 py-1 rounded-lg border border-blue-100">+12% vs semana anterior</span>
          </div>
          <div className="h-[280px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={data.weeklyTrend}>
                <defs>
                  <linearGradient id="colorRev" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.1} />
                    <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                <XAxis dataKey="day" axisLine={false} tickLine={false} tick={{ fill: '#94a3b8', fontSize: 10, fontWeight: 'bold' }} dy={10} />
                <YAxis axisLine={false} tickLine={false} tick={{ fill: '#94a3b8', fontSize: 10, fontWeight: 'bold' }} />
                <Tooltip
                  contentStyle={{ borderRadius: '16px', border: 'none', boxShadow: '0 20px 25px -5px rgb(0 0 0 / 0.1)', fontSize: '12px', fontWeight: 'bold' }}
                />
                <Area type="monotone" dataKey="amount" stroke="#3b82f6" strokeWidth={4} fillOpacity={1} fill="url(#colorRev)" />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Canales de Venta */}
        <div className="rounded-[2rem] border border-slate-200 bg-white p-8 shadow-xl shadow-slate-200/50">
          <h3 className="mb-8 text-xs font-black text-slate-500 uppercase tracking-[0.2em]">Mix de Canales</h3>
          <div className="h-[220px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie data={data.channelMix} innerRadius={65} outerRadius={85} paddingAngle={8} dataKey="value">
                  {data.channelMix.map((_, idx) => <Cell key={idx} fill={COLORS[idx % COLORS.length]} />)}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div className="mt-6 space-y-3">
            {data.channelMix.map((item, idx) => (
              <div key={item.name} className="flex items-center justify-between bg-slate-50 px-4 py-2 rounded-xl">
                <div className="flex items-center gap-3">
                  <div className="h-2 w-2 rounded-full" style={{ backgroundColor: COLORS[idx] }} />
                  <span className="text-[10px] text-slate-600 font-black uppercase tracking-tighter">{item.name}</span>
                </div>
                <span className="text-xs font-black text-slate-900">{item.value} ads</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* TABLA DE ÚLTIMAS OPERACIONES (ESTILO CAJA DIARIA) */}
      <div className="rounded-[2rem] border border-slate-200 bg-white overflow-hidden shadow-xl shadow-slate-200/50 flex flex-col">
        <div className="p-6 border-b border-slate-100 bg-slate-50/50 flex items-center justify-between">
          <h3 className="text-xs font-black text-slate-800 uppercase tracking-[0.2em]">Últimas Operaciones Recibidas</h3>
          <button className="text-[10px] font-black text-blue-600 uppercase tracking-widest hover:text-blue-700 flex items-center gap-1">
            Ver todas <ArrowUpRight size={14} />
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-slate-50/30 text-[9px] uppercase text-slate-400 font-black tracking-[0.15em] border-b border-slate-100">
              <tr>
                <th className="px-8 py-4">Aviso / Detalle</th>
                <th className="px-8 py-4 text-center">Horario (GMT-3)</th>
                <th className="px-8 py-4 text-center">Estado</th>
                <th className="px-8 py-4 text-right">Monto Neto</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {recentAds.map((ad) => (
                <tr key={ad.id} className="hover:bg-blue-50/30 transition-colors group">
                  <td className="px-8 py-4">
                    <div className="font-extrabold text-slate-900 uppercase text-xs tracking-tight group-hover:text-blue-600 transition-colors">{ad.title}</div>
                    <div className="text-[9px] text-slate-500 font-bold uppercase tracking-tighter mt-0.5">
                      {ad.categoryName} • ID #{ad.id.toString().padStart(6, '0')}
                    </div>
                  </td>
                  <td className="px-8 py-4 text-center">
                    <div className="inline-flex items-center gap-1.5 text-slate-800 font-black bg-slate-100 px-2.5 py-1 rounded-lg text-[10px]">
                      <Clock size={12} className="text-blue-500" />
                      {formatLocalTime(ad.createdAt)}
                    </div>
                  </td>
                  <td className="px-8 py-4 text-center">
                    <span className={clsx(
                      "inline-flex items-center rounded-md px-2.5 py-1 text-[8px] font-black uppercase tracking-tighter border",
                      ad.status === 'Published'
                        ? 'bg-emerald-50 text-emerald-700 border-emerald-100'
                        : 'bg-amber-50 text-amber-700 border-amber-100'
                    )}>
                      {ad.status === 'Published' ? 'Cobrado' : 'Pendiente'}
                    </span>
                  </td>
                  <td className="px-8 py-4 text-right font-black text-slate-950 text-sm">
                    <span className="text-[10px] opacity-40 mr-1">$</span>
                    {formatCurrency(ad.adFee)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// StatsCard actualizado con estética Premium
function StatsCard({ title, value, icon: Icon, color, delay }: any) {
  const colorMap: any = {
    blue: 'text-blue-600 bg-blue-50 border-blue-100',
    emerald: 'text-emerald-600 bg-emerald-50 border-emerald-100',
    purple: 'text-purple-600 bg-purple-50 border-purple-100',
    amber: 'text-amber-600 bg-amber-50 border-amber-100',
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 15 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay }}
      whileHover={{ y: -3 }}
      className="relative overflow-hidden rounded-[2rem] border border-slate-200 bg-white p-6 shadow-lg shadow-slate-200/50"
    >
      <div className="flex items-center justify-between">
        <div>
          <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1.5">{title}</p>
          <h3 className="text-2xl font-black tracking-tighter text-slate-900">{value}</h3>
        </div>
        <div className={clsx("flex h-11 w-11 items-center justify-center rounded-2xl border shadow-inner", colorMap[color])}>
          <Icon size={20} />
        </div>
      </div>
      <div className="absolute -bottom-4 -right-4 h-16 w-16 rounded-full bg-slate-50 opacity-50" />
    </motion.div>
  );
}