import { useEffect, useState, useCallback, type ReactNode } from 'react';
import { dashboardService } from '../services/dashboardService';
import type {
  AdvancedAnalyticsData,
  PaymentMethodStat,
  CategoryPerformanceStat
} from '../types/Analytics';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell, AreaChart, Area
} from 'recharts';
import {
  TrendingUp, DollarSign,
  Clock, ArrowUpRight, ArrowDownRight, Award, PieChart as PieChartIcon
} from 'lucide-react';
import { motion } from 'framer-motion';
import clsx from 'clsx';

// Colores para gráficos con estética premium
const COLORS = ['#3b82f6', '#8b5cf6', '#ec4899', '#f59e0b', '#10b981'];

export default function AdvancedAnalytics() {
  const [data, setData] = useState<AdvancedAnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState('month');

  const loadAnalytics = useCallback(async () => {
    setLoading(true);
    try {
      const end = new Date().toISOString();
      const start = new Date();
      if (timeRange === 'week') start.setDate(start.getDate() - 7);
      else if (timeRange === 'month') start.setMonth(start.getMonth() - 1);
      else if (timeRange === 'year') start.setFullYear(start.getFullYear() - 1);

      const res = await dashboardService.getAdvancedAnalytics(start.toISOString(), end);
      setData(res);
    } catch (error) {
      console.error('Error al cargar analítica:', error);
    } finally {
      setLoading(false);
    }
  }, [timeRange]);

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

  if (loading || !data) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <div className="flex flex-col items-center gap-4">
          <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          <p className="text-slate-500 font-bold uppercase tracking-widest text-xs text-center">Sincronizando con el servidor central...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-8 max-w-7xl mx-auto space-y-8 animate-in fade-in duration-700">
      {/* Encabezado con selector de rango temporal */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-4xl font-black text-slate-900 tracking-tighter uppercase flex items-center gap-3">
            <span className="bg-blue-600 w-2 h-8 rounded-full"></span>
            BI & Analítica Avanzada
          </h1>
          <p className="text-slate-400 font-bold uppercase tracking-widest text-[10px] mt-1">Inteligencia de negocios y reportes gerenciales</p>
        </div>

        <div className="bg-white p-1 rounded-2xl shadow-xl border border-slate-100 flex gap-1">
          {['week', 'month', 'year'].map((r) => (
            <button
              key={r}
              onClick={() => setTimeRange(r)}
              className={`px-6 py-2 rounded-xl text-xs font-black uppercase tracking-widest transition-all ${timeRange === r ? 'bg-slate-900 text-white shadow-lg' : 'text-slate-400 hover:text-slate-600 hover:bg-slate-50'
                }`}
            >
              {r === 'week' ? '7 Días' : r === 'month' ? '30 Días' : 'Año'}
            </button>
          ))}
        </div>
      </div>

      {/* Tarjetas de KPIs Principales */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <KPICard
          title="Recaudación Neto"
          value={`$${data.totalRevenue?.toLocaleString() || 0}`}
          growth={data.revenueGrowth}
          icon={<DollarSign className="text-blue-600" />}
          color="blue"
        />
        <KPICard
          title="Avisos Publicados"
          value={data.totalAds}
          growth={data.adsGrowth}
          icon={<Award className="text-emerald-600" />}
          color="emerald"
        />
        <KPICard
          title="Promedio por Aviso"
          value={`$${((data.totalRevenue || 0) / (data.totalAds || 1)).toLocaleString()}`}
          icon={<TrendingUp className="text-indigo-600" />}
          color="indigo"
          simple
        />
        <KPICard
          title="Crecimiento vs Ant."
          value={`${data.revenueGrowth?.toFixed(1) || 0}%`}
          icon={<PieChartIcon className="text-amber-600" />}
          color="amber"
          simple
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        {/* Gráfico de Línea: Tendencia Temporal */}
        <div className="lg:col-span-8 bg-white p-8 rounded-[3rem] shadow-2xl shadow-slate-200/50 border border-slate-100">
          <h3 className="text-lg font-black text-slate-800 uppercase tracking-tight mb-8">Tendencia de Ingresos Diarios</h3>
          <div className="h-[350px]">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={data.dailyTrends}>
                <defs>
                  <linearGradient id="colorAmountArea" 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={{ fontSize: 10, fill: '#64748b' }} dy={10} />
                <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 10, fill: '#64748b' }} />
                <Tooltip
                  contentStyle={{ borderRadius: '16px', border: 'none', boxShadow: '0 20px 25px -5px rgb(0 0 0 / 0.1)' }}
                  labelStyle={{ fontWeight: 'bold', color: '#1e293b' }}
                />
                <Area type="monotone" dataKey="amount" stroke="#3b82f6" strokeWidth={4} fillOpacity={1} fill="url(#colorAmountArea)" />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Gráfico de Torta: Canales de Cobro */}
        <div className="lg:col-span-4 bg-white p-8 rounded-[3rem] shadow-2xl shadow-slate-200/50 border border-slate-100">
          <h3 className="text-lg font-black text-slate-800 uppercase tracking-tight mb-8">Manejo de Tesorería</h3>
          <div className="h-[350px]">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={data.paymentsDistribution}
                  innerRadius={70}
                  outerRadius={100}
                  paddingAngle={8}
                  dataKey="total"
                  nameKey="method"
                >
                  {data.paymentsDistribution?.map((_: PaymentMethodStat, index: number) => (
                    <Cell key={`cell-analytics-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div className="grid grid-cols-1 gap-2 mt-4 px-4 overflow-y-auto max-h-[100px]">
            {data.paymentsDistribution?.map((p: PaymentMethodStat, idx: number) => (
              <div key={idx} className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: COLORS[idx % COLORS.length] }}></div>
                  <span className="text-[10px] font-bold text-slate-500 uppercase">{p.method}</span>
                </div>
                <span className="text-[10px] font-black text-slate-900">${p.total?.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Dentro del return de AdvancedAnalytics.tsx */}
      <div className="bg-white p-8 rounded-[3rem] shadow-xl border border-slate-100">
        <div className="flex items-center justify-between mb-8">
          <h3 className="text-xs font-black text-slate-500 uppercase tracking-widest">Eficiencia de Canales</h3>
          <span className="text-[10px] font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded-lg">Real-time</span>
        </div>

        <div className="space-y-8">
          <ChannelProgress
            label="Mostrador (Venta Presencial)"
            value={data.sourceMix?.mostradorPercent || 0}
            count={data.sourceMix?.mostradorCount || 0}
            color="bg-slate-900"
          />
          <ChannelProgress
            label="Web (Wizard Digital)"
            value={data.sourceMix?.webPercent || 0}
            count={data.sourceMix?.webCount || 0}
            color="bg-blue-600"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Gráfico de Barras: Horas Pico */}
        <div className="bg-slate-900 p-10 rounded-[3rem] text-white shadow-2xl relative overflow-hidden">
          <div className="absolute top-0 right-0 w-64 h-64 bg-blue-600/10 rounded-full -mr-32 -mt-32 blur-[80px]"></div>
          <h3 className="text-lg font-black uppercase tracking-tight mb-10 flex items-center gap-3 relative z-10">
            <Clock size={20} className="text-blue-400" />
            Frecuencia de Operatividad (Horas Pico)
          </h3>
          <div className="h-[280px] relative z-10">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={data.hourlyActivity}>
                <XAxis dataKey="hour" axisLine={false} tickLine={false} tick={{ fill: '#94a3b8', fontSize: 10 }} />
                <Tooltip cursor={{ fill: '#ffffff10' }} contentStyle={{ color: '#000', borderRadius: '12px', border: 'none' }} />
                <Bar dataKey="count" fill="#3b82f6" radius={[6, 6, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Listado de Rubros: Participación en Ingresos */}
        <div className="bg-white p-10 rounded-[3rem] shadow-2xl shadow-slate-200/50 border border-slate-100">
          <h3 className="text-lg font-black text-slate-800 uppercase tracking-tight mb-10">Ranking de Rubros por Ingresos</h3>
          <div className="space-y-6">
            {data.categoryPerformance?.slice(0, 5).map((cp: CategoryPerformanceStat, idx: number) => (
              <div key={idx} className="group cursor-default">
                <div className="flex justify-between items-end mb-2">
                  <span className="text-[10px] font-black text-slate-900 uppercase tracking-widest">{cp.categoryName}</span>
                  <div className="text-right">
                    <span className="text-xs font-black text-blue-600 block leading-none">${cp.revenue?.toLocaleString()}</span>
                  </div>
                </div>
                <div className="w-full h-2.5 bg-slate-50 rounded-full overflow-hidden border border-slate-100">
                  <motion.div
                    initial={{ width: 0 }}
                    animate={{ width: `${cp.share || 0}%` }}
                    transition={{ duration: 1, ease: 'easeOut' }}
                    className="h-full bg-gradient-to-r from-blue-500 to-indigo-600 rounded-full"
                  ></motion.div>
                </div>
                <div className="flex justify-between mt-1.5 opacity-60">
                  <span className="text-[9px] font-bold text-slate-400 uppercase">{cp.adsCount} avisos</span>
                  <span className="text-[9px] font-black text-indigo-500 uppercase">{cp.share?.toFixed(1)}% del total</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

interface KPICardProps {
  title: string;
  value: string | number;
  growth?: number;
  icon: ReactNode;
  color: string;
  simple?: boolean;
}

function ChannelProgress({ label, value, count, color }: any) {
  return (
    <div>
      <div className="flex justify-between items-end text-[10px] font-black uppercase mb-2">
        <div className="flex flex-col">
          <span className="text-slate-400">{label}</span>
          <span className="text-slate-900 text-xs">{count} avisos</span>
        </div>
        <span className="text-blue-600 text-lg tracking-tighter">{value.toFixed(1)}%</span>
      </div>
      <div className="h-2.5 w-full bg-slate-100 rounded-full overflow-hidden border border-slate-200">
        <motion.div
          initial={{ width: 0 }}
          animate={{ width: `${value}%` }}
          transition={{ duration: 1, ease: "easeOut" }}
          className={clsx("h-full shadow-lg", color)}
        />
      </div>
    </div>
  )
}

// Subcomponente reutilizable para tarjetas de métricas (KPIs)
function KPICard({ title, value, growth, icon, color, simple = false }: KPICardProps) {
  const isPositive = (growth ?? 0) >= 0;

  return (
    <motion.div
      whileHover={{ y: -5, scale: 1.02 }}
      className="bg-white p-8 rounded-[2.5rem] shadow-2xl shadow-slate-200/50 border border-slate-100 relative overflow-hidden"
    >
      <div className={`absolute top-0 right-0 w-20 h-20 bg-${color}-500/5 rounded-full -mr-10 -mt-10`}></div>
      <div className="flex justify-between items-start mb-6">
        <div className={`p-3 rounded-2xl bg-${color}-50`}>
          {icon}
        </div>
        {!simple && growth !== undefined && (
          <div className={`flex items-center gap-1 text-[9px] font-black uppercase px-2 py-1 rounded-lg ${isPositive ? 'bg-emerald-50 text-emerald-600' : 'bg-rose-50 text-rose-600'
            }`}>
            {isPositive ? <ArrowUpRight size={12} /> : <ArrowDownRight size={12} />}
            {Math.abs(growth).toFixed(1)}%
          </div>
        )}
      </div>
      <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-2 leading-none">{title}</h4>
      <div className="text-3xl font-black text-slate-900 tracking-tighter leading-none">{value}</div>
    </motion.div>
  );
}
