// ============================================================================
// COMPONENT: FutureProjections.jsx
// Planificación, Proyecciones Futuras & Simulador Interactivo de Cuotas y Servicios
// ============================================================================

const { useState, useEffect, useMemo, useRef } = React;

function FutureProjections() {
  const { dashboardData: initialDashboard, settings } = window.useFinance ? window.useFinance() : {};
  const { Button, Card, CardHeader, CardTitle, CardDescription, CardContent, Badge, Lucide } = window.Shadcn || {};

  // Estado del simulador interactivo
  const [currentBalance, setCurrentBalance] = useState(28958000);
  const [monthlyCuota, setMonthlyCuota] = useState(2974000);
  const [eventsPerMonth, setEventsPerMonth] = useState(3); // Cantidad de eventos/reels (800mil c/u)
  const [eventPrice, setEventPrice] = useState(800000);
  const [extraVideosPerMonth, setExtraVideosPerMonth] = useState(2); // Videos avulsos/creativos (410mil c/u)
  const [extraVideoPrice, setExtraVideoPrice] = useState(410000);

  const canvasRef = useRef(null);
  const chartRef = useRef(null);

  // Obtener saldo real de la base de datos
  useEffect(() => {
    window.Api.getDashboard().then(data => {
      if (data?.totals?.netBalance) {
        setCurrentBalance(data.totals.netBalance);
      }
    }).catch(console.error);
  }, []);

  const fmt = (v) => window.formatCurrencyPYG ? window.formatCurrencyPYG(v) : `G$ ${v}`;

  // Cálculos del simulador
  const calculations = useMemo(() => {
    const projectedMonthlyServices = (eventsPerMonth * eventPrice) + (extraVideosPerMonth * extraVideoPrice);
    const monthlyNetFlow = projectedMonthlyServices - monthlyCuota;
    const monthsCoveredByCurrentBalance = monthlyCuota > 0 ? (currentBalance / monthlyCuota) : 0;

    // Generar proyección mes a mes para los próximos 12 meses
    const monthsAhead = [];
    let runningBalance = currentBalance;
    const baseDate = new Date(); // Octubre 2026

    for (let i = 1; i <= 12; i++) {
      const d = new Date(baseDate.getFullYear(), baseDate.getMonth() + i, 1);
      const monthLabel = d.toLocaleDateString('es-PY', { month: 'short', year: 'numeric' });
      const fullMonthName = d.toLocaleDateString('es-PY', { month: 'long', year: 'numeric' });
      
      runningBalance = runningBalance + monthlyNetFlow;

      monthsAhead.push({
        index: i,
        monthLabel: monthLabel.charAt(0).toUpperCase() + monthLabel.slice(1),
        fullMonthName: fullMonthName.charAt(0).toUpperCase() + fullMonthName.slice(1),
        cuota: monthlyCuota,
        projectedServices: projectedMonthlyServices,
        monthlyNet: monthlyNetFlow,
        accumulatedBalance: runningBalance,
        isCovered: runningBalance >= 0
      });
    }

    return {
      projectedMonthlyServices,
      monthlyNetFlow,
      monthsCoveredByCurrentBalance,
      monthsAhead,
      balanceAt3Months: monthsAhead[2]?.accumulatedBalance || 0,
      balanceAt6Months: monthsAhead[5]?.accumulatedBalance || 0,
      balanceAt12Months: monthsAhead[11]?.accumulatedBalance || 0
    };
  }, [currentBalance, monthlyCuota, eventsPerMonth, eventPrice, extraVideosPerMonth, extraVideoPrice]);

  // Renderizar gráfico de proyección interactivo con Chart.js
  useEffect(() => {
    if (!canvasRef.current || typeof window.Chart === 'undefined') return;

    if (chartRef.current) {
      chartRef.current.destroy();
      chartRef.current = null;
    }

    const labels = ['Actual (Oct)', ...calculations.monthsAhead.map(m => m.monthLabel)];
    const dataPoints = [currentBalance, ...calculations.monthsAhead.map(m => m.accumulatedBalance)];

    const ctx = canvasRef.current.getContext('2d');
    chartRef.current = new window.Chart(ctx, {
      type: 'line',
      data: {
        labels,
        datasets: [
          {
            label: 'Saldo Acumulado Proyectado',
            data: dataPoints,
            borderColor: '#10b981',
            backgroundColor: 'rgba(16, 185, 129, 0.08)',
            fill: true,
            tension: 0.35,
            pointRadius: 4,
            pointHoverRadius: 6,
            pointBackgroundColor: '#10b981',
            pointBorderColor: '#ffffff',
            pointBorderWidth: 2,
            borderDash: [5, 5]
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            backgroundColor: '#09090b',
            titleColor: '#ffffff',
            bodyColor: '#a1a1aa',
            borderColor: '#27272a',
            borderWidth: 1,
            padding: 10,
            callbacks: {
              label: (ctx) => `Saldo Proyectado: ${fmt(ctx.raw)}`
            }
          }
        },
        scales: {
          x: {
            grid: { display: false },
            ticks: { font: { size: 10, family: 'sans-serif' }, color: '#71717a' }
          },
          y: {
            grid: { color: 'rgba(0,0,0,0.05)' },
            ticks: {
              font: { size: 10, family: 'monospace' },
              color: '#71717a',
              callback: (v) => `${Math.round(v / 1000000)}M`
            }
          }
        }
      }
    });

    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
        chartRef.current = null;
      }
    };
  }, [calculations, currentBalance]);

  return (
    <div className="space-y-6">
      {/* CABECERA */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 border-b border-zinc-200 dark:border-zinc-800 pb-5">
        <div>
          <div className="flex items-center gap-2">
            <span className="text-xl">🔮</span>
            <h1 className="text-2xl font-bold tracking-tight text-zinc-950 dark:text-white">Proyecciones & Simulador Futuro</h1>
            <span className="text-[11px] font-mono font-bold bg-emerald-50 text-emerald-700 border border-emerald-300 px-2 py-0.5 rounded-full">
              PREDICTIVO
            </span>
          </div>
          <p className="text-sm text-zinc-500 mt-1">
            Simula escenarios de producción mensual, cobertura anticipada de cuotas y saldo futuro proyectado
          </p>
        </div>
      </div>

      {/* KPI HERO: COBERTURA DE CUOTAS (RUNWAY) */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="p-5 rounded-xl border border-emerald-300 bg-emerald-50/30 dark:bg-emerald-950/20 space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold uppercase tracking-wider text-emerald-800 dark:text-emerald-400">
              Meses de Cuota Cubiertos
            </span>
            <span className="text-lg">🛡️</span>
          </div>
          <div className="text-3xl font-extrabold text-emerald-600 font-mono">
            {calculations.monthsCoveredByCurrentBalance.toFixed(1)} meses
          </div>
          <p className="text-xs text-zinc-600 dark:text-zinc-400 leading-relaxed">
            Tu saldo actual de <strong>{fmt(currentBalance)}</strong> cubre por adelantado hasta <strong>Julio de 2027</strong> de cuotas universitarias completas.
          </p>
        </div>

        <div className="p-5 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold uppercase tracking-wider text-zinc-500">
              Ingreso Mensual Estimado
            </span>
            <span className="text-lg">🎬</span>
          </div>
          <div className="text-3xl font-extrabold text-zinc-950 dark:text-white font-mono">
            {fmt(calculations.projectedMonthlyServices)}
          </div>
          <p className="text-xs text-zinc-500 leading-relaxed">
            Basado en <strong>{eventsPerMonth} eventos</strong> y <strong>{extraVideosPerMonth} videos/creativos</strong> por mes según los controles del simulador.
          </p>
        </div>

        <div className="p-5 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold uppercase tracking-wider text-zinc-500">
              Flujo Mensual Neto (Servicios - Cuota)
            </span>
            <span className="text-lg">⚖️</span>
          </div>
          <div className={`text-3xl font-extrabold font-mono ${calculations.monthlyNetFlow >= 0 ? 'text-emerald-600' : 'text-rose-600'}`}>
            {calculations.monthlyNetFlow >= 0 ? '+' : ''}{fmt(calculations.monthlyNetFlow)}
          </div>
          <p className="text-xs text-zinc-500 leading-relaxed">
            {calculations.monthlyNetFlow >= 0 
              ? '¡Tu producción mensual supera la cuota! Cada mes tu saldo a favor aumentará.' 
              : 'La cuota supera los servicios estimados en este escenario.'}
          </p>
        </div>
      </div>

      {/* CONTROLES INTERACTIVOS DEL SIMULADOR */}
      <div className="p-6 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-zinc-50/70 dark:bg-zinc-900/60 space-y-6">
        <div className="flex items-center justify-between border-b border-zinc-200 dark:border-zinc-800 pb-3">
          <div>
            <h3 className="font-bold text-sm text-zinc-950 dark:text-white flex items-center gap-2">
              <span>🎛️</span>
              <span>Parámetros del Escenario de Producción</span>
            </h3>
            <p className="text-xs text-zinc-500">Ajusta los controles deslizantes para recalcular al instante las proyecciones</p>
          </div>
          <button
            type="button"
            onClick={() => {
              setEventsPerMonth(3);
              setExtraVideosPerMonth(2);
              setMonthlyCuota(2974000);
            }}
            className="text-xs font-medium text-zinc-600 hover:text-zinc-950 dark:hover:text-white underline cursor-pointer"
          >
            Restaurar Valores Típicos
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* SLIDER 1: EVENTOS AL MES */}
          <div className="space-y-2 bg-white dark:bg-zinc-800/80 p-4 rounded-lg border border-zinc-200 dark:border-zinc-700">
            <div className="flex items-center justify-between">
              <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300">
                Eventos / Reels por Mes
              </label>
              <span className="text-xs font-mono font-bold px-2 py-0.5 rounded bg-zinc-950 text-white">
                {eventsPerMonth} eventos
              </span>
            </div>
            <input 
              type="range" 
              min="0" 
              max="6" 
              step="1"
              value={eventsPerMonth} 
              onChange={(e) => setEventsPerMonth(parseInt(e.target.value, 10))}
              className="slider-thumb-modern cursor-pointer"
            />
            <div className="flex items-center justify-between text-[10px] text-zinc-400 font-mono">
              <span>0</span>
              <span>Valor: {fmt(eventPrice)} c/u</span>
              <span>6/mes</span>
            </div>
          </div>

          {/* SLIDER 2: VIDEOS / CREATIVOS AL MES */}
          <div className="space-y-2 bg-white dark:bg-zinc-800/80 p-4 rounded-lg border border-zinc-200 dark:border-zinc-700">
            <div className="flex items-center justify-between">
              <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300">
                Videos Avulsos / Creativos
              </label>
              <span className="text-xs font-mono font-bold px-2 py-0.5 rounded bg-zinc-950 text-white">
                {extraVideosPerMonth} videos
              </span>
            </div>
            <input 
              type="range" 
              min="0" 
              max="8" 
              step="1"
              value={extraVideosPerMonth} 
              onChange={(e) => setExtraVideosPerMonth(parseInt(e.target.value, 10))}
              className="slider-thumb-modern cursor-pointer"
            />
            <div className="flex items-center justify-between text-[10px] text-zinc-400 font-mono">
              <span>0</span>
              <span>Valor: {fmt(extraVideoPrice)} c/u</span>
              <span>8/mes</span>
            </div>
          </div>

          {/* INPUT: VALOR DE LA CUOTA MENSUAL */}
          <div className="space-y-2 bg-white dark:bg-zinc-800/80 p-4 rounded-lg border border-zinc-200 dark:border-zinc-700">
            <div className="flex items-center justify-between">
              <label className="text-xs font-bold text-zinc-700 dark:text-zinc-300">
                Cuota Mensual Universitaria
              </label>
              <span className="text-[10px] text-zinc-400 font-mono">PYG</span>
            </div>
            <input 
              type="text" 
              value={window.maskCurrencyPYG ? window.maskCurrencyPYG(monthlyCuota) : monthlyCuota}
              onChange={(e) => {
                const raw = window.unmaskCurrencyPYG ? window.unmaskCurrencyPYG(e.target.value) : parseInt(e.target.value, 10) || 0;
                setMonthlyCuota(raw);
              }}
              className="w-full h-8 px-2.5 text-xs font-mono font-bold rounded border border-zinc-200 dark:border-zinc-600 bg-white dark:bg-zinc-900 text-zinc-950 dark:text-white"
            />
            <div className="text-[10px] text-zinc-400">
              Valor de referencia pactado con Tesorería
            </div>
          </div>
        </div>
      </div>

      {/* GRÁFICO PREDICTIVO */}
      <div className="p-5 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 space-y-3">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="font-bold text-sm text-zinc-950 dark:text-white">Curva de Evolución del Saldo Futuro (12 Meses)</h3>
            <p className="text-xs text-zinc-500">Trayectoria proyectada de tu saldo a favor según el ritmo de servicios</p>
          </div>
          <div className="flex items-center gap-3 text-xs">
            <div className="flex items-center gap-1.5 font-mono">
              <span className="w-2.5 h-2.5 rounded-full bg-emerald-500"></span>
              <span className="text-zinc-700 dark:text-zinc-300">Proyección Estimada</span>
            </div>
          </div>
        </div>
        <div className="w-full h-[240px] relative">
          <canvas ref={canvasRef} />
        </div>
      </div>

      {/* CALENDARIO MENSUAL DE DETALLE (PRÓXIMOS 12 MESES) */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <h3 className="font-bold text-sm text-zinc-950 dark:text-white">Calendario de Cuotas y Cobertura Mensual</h3>
          <span className="text-xs text-zinc-400 font-mono">12 Meses en Proyección</span>
        </div>

        <div className="overflow-x-auto rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900">
          <table className="w-full text-xs text-left">
            <thead>
              <tr className="bg-zinc-50 dark:bg-zinc-800/60 border-b border-zinc-200 dark:border-zinc-800 font-semibold text-zinc-600 dark:text-zinc-400">
                <th className="py-2.5 px-3 w-12 text-center font-mono">#</th>
                <th className="py-2.5 px-3">Mes Proyectado</th>
                <th className="py-2.5 px-3 text-right">Cuota Universidad</th>
                <th className="py-2.5 px-3 text-right">Servicios Proyectados</th>
                <th className="py-2.5 px-3 text-center">Estado de Cobertura</th>
                <th className="py-2.5 px-3 text-right font-mono">Saldo Acumulado a Favor</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800 font-sans">
              {calculations.monthsAhead.map((m) => (
                <tr key={m.index} className="hover:bg-zinc-50/60 dark:hover:bg-zinc-800/40">
                  <td className="py-2.5 px-3 text-center font-mono text-zinc-400">
                    +{m.index}m
                  </td>
                  <td className="py-2.5 px-3 font-semibold text-zinc-900 dark:text-white">
                    {m.fullMonthName}
                  </td>
                  <td className="py-2.5 px-3 text-right font-mono text-rose-600">
                    -{fmt(m.cuota)}
                  </td>
                  <td className="py-2.5 px-3 text-right font-mono text-emerald-600">
                    +{fmt(m.projectedServices)}
                  </td>
                  <td className="py-2.5 px-3 text-center">
                    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-mono font-bold bg-emerald-50 text-emerald-700 border border-emerald-300">
                      ✓ 100% CUBIERTO
                    </span>
                  </td>
                  <td className="py-2.5 px-3 text-right font-mono font-bold text-zinc-950 dark:text-white">
                    {fmt(m.accumulatedBalance)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

window.FutureProjections = FutureProjections;
