import { useState, useMemo } from 'react';
import {
  AreaChart, Area, BarChart, Bar,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend,
  ResponsiveContainer, ReferenceLine,
} from 'recharts';
import { useProject } from '../../context/ProjectContext';

// ─── Mock Projects ────────────────────────────────────────────────────────────
const MOCK_PROJECTS = [
  { id: 'p4', code: 'PRY-2026-004', name: 'Construcción AR-ProjectManagement Norte', client: 'Inmobiliaria Del Valle',   budget: 4200000, startDate: '2026-01-15' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement "Horizontes"',           client: 'Sony Music Latin',        budget:  320000, startDate: '2026-02-01' },
  { id: 'p4', code: 'PRY-2026-004', name: 'Implementación AR-ProjectManagement',       client: 'Grupo Empresarial XYZ',   budget:  980000, startDate: '2026-01-20' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement — Plataforma ERP',client: 'AR Electronics',          budget:  560000, startDate: '2026-03-01' },
];

const DEFAULT_SLIDERS = {
  budgetVar:    0,
  delay:        0,
  productivity: 0,
  inflation:    5,
  usdCop:       4100,
  contingency:  5,
  retention:    10,
};

const fmt = (n, decimals = 0) =>
  new Intl.NumberFormat('es-CO', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }).format(n);

const fmtCurrency = (n) =>
  new Intl.NumberFormat('es-CO', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(n);

// ─── Slider Control ───────────────────────────────────────────────────────────
function SliderRow({ label, value, min, max, step = 1, unit = '', onChange, color = 'blue' }) {
  const pct = ((value - min) / (max - min)) * 100;
  const colorMap = { blue: '#3b82f6', red: '#ef4444', green: '#10b981', amber: '#f59e0b' };
  const c = colorMap[color] || colorMap.blue;
  return (
    <div className="space-y-1.5">
      <div className="flex justify-between items-center">
        <span className="text-sm font-medium text-slate-700 dark:text-slate-300">{label}</span>
        <span className="text-sm font-bold tabular-nums" style={{ color: c }}>
          {unit === 'USD/COP' ? fmt(value) : `${value > 0 && unit !== 'meses' ? '+' : ''}${value}${unit}`}
        </span>
      </div>
      <input
        type="range" min={min} max={max} step={step} value={value}
        onChange={e => onChange(Number(e.target.value))}
        className="w-full h-2 rounded-full appearance-none cursor-pointer"
        style={{
          background: `linear-gradient(to right, ${c} 0%, ${c} ${pct}%, #e2e8f0 ${pct}%, #e2e8f0 100%)`,
        }}
      />
      <div className="flex justify-between text-xs text-slate-400 dark:text-slate-600">
        <span>{min}{unit === 'USD/COP' ? '' : unit}</span>
        <span>{max}{unit === 'USD/COP' ? '' : unit}</span>
      </div>
    </div>
  );
}

// ─── KPI Card ─────────────────────────────────────────────────────────────────
function KPICard({ title, value, delta, deltaLabel, sub, valueColor }) {
  const isPos = delta > 0;
  const isNeg = delta < 0;
  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
      <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">{title}</p>
      <p className={`text-2xl font-bold ${valueColor || 'text-slate-900 dark:text-white'}`}>{value}</p>
      {delta !== undefined && (
        <p className={`text-xs mt-1 font-medium ${isNeg ? 'text-red-500' : isPos ? 'text-green-500' : 'text-slate-400'}`}>
          {isPos ? '▲' : isNeg ? '▼' : '—'} {Math.abs(delta).toFixed(1)}{deltaLabel}
        </p>
      )}
      {sub && <p className="text-xs text-slate-400 dark:text-slate-500 mt-0.5">{sub}</p>}
    </div>
  );
}

let scenarioCounter = 1;

export default function ScenarioSimulatorPage() {
  const { selectedProjectId } = useProject();

  const defaultProject = selectedProjectId
    ? MOCK_PROJECTS.find(p => p.id === selectedProjectId) || MOCK_PROJECTS[0]
    : MOCK_PROJECTS[0];

  const [selectedId, setSelectedId] = useState(defaultProject.id);
  const [sliders, setSliders] = useState(DEFAULT_SLIDERS);
  const [savedScenarios, setSavedScenarios] = useState([]);
  const [compareId, setCompareId] = useState(null);

  const project = MOCK_PROJECTS.find(p => p.id === selectedId) || MOCK_PROJECTS[0];

  const set = (key) => (val) => setSliders(prev => ({ ...prev, [key]: val }));

  // ─── Core Calculations ─────────────────────────────────────────────────────
  const calc = useMemo(() => {
    const baseCost = project.budget;
    const revenue = baseCost * 1.25;

    const scenarioCost = baseCost
      * (1 + sliders.budgetVar / 100)
      * (1 + sliders.inflation / 100)
      * (1 - (sliders.productivity / 100) * 0.3);

    const scheduleImpact = sliders.delay * baseCost * 0.02;
    const contingencyAmt = scenarioCost * (sliders.contingency / 100);
    const totalCost = scenarioCost + scheduleImpact + contingencyAmt;
    const margin = ((revenue - totalCost) / revenue) * 100;
    const baseMargin = ((revenue - baseCost) / revenue) * 100;

    // Cash flow — 18 months
    const cashFlow = Array.from({ length: 18 }, (_, i) => {
      const month = i + 1;
      const baseIn = revenue * (month / 18);
      const baseOut = baseCost * (month / 18);
      const baseNet = baseIn - baseOut;

      const retention = sliders.retention / 100;
      const scenIn = revenue * (1 - retention) * (month / (18 + sliders.delay));
      const scenOut = totalCost * (month / (18 + sliders.delay));
      const scenNet = scenIn - scenOut;

      return {
        month: `M${month}`,
        base: Math.round(baseNet),
        scenario: Math.round(scenNet),
      };
    });

    const minCashFlow = Math.min(...cashFlow.map(d => d.scenario));

    // Cost breakdown — Labor 40%, Materials 30%, Subcontractors 20%, Overhead 10%
    const breakdown = [
      { category: 'Labor',          base: baseCost * 0.40, scenario: totalCost * 0.40 },
      { category: 'Materiales',     base: baseCost * 0.30, scenario: totalCost * 0.30 },
      { category: 'Subcontratistas',base: baseCost * 0.20, scenario: totalCost * 0.20 },
      { category: 'Overhead',       base: baseCost * 0.10, scenario: totalCost * 0.10 },
    ];

    // Finish date
    const start = new Date(project.startDate);
    const baseEnd = new Date(start);
    baseEnd.setMonth(baseEnd.getMonth() + 18);
    const scenEnd = new Date(start);
    scenEnd.setMonth(scenEnd.getMonth() + 18 + sliders.delay);
    const fmtDate = (d) => d.toLocaleDateString('es-CO', { year: 'numeric', month: 'short', day: 'numeric' });

    return {
      baseCost, revenue, totalCost, margin, baseMargin,
      cashFlow, minCashFlow, breakdown,
      baseEndDate: fmtDate(baseEnd),
      scenEndDate: fmtDate(scenEnd),
      costDelta: ((totalCost - baseCost) / baseCost) * 100,
    };
  }, [project, sliders]);

  // Compare scenario cash flow overlay
  const compareScenario = savedScenarios.find(s => s.id === compareId);
  const chartData = calc.cashFlow.map((d, i) => ({
    ...d,
    compare: compareScenario ? compareScenario.cashFlow[i]?.scenario : undefined,
  }));

  const handleSave = () => {
    const name = `Escenario ${scenarioCounter++}`;
    setSavedScenarios(prev => [{
      id: Date.now(),
      name,
      budgetVar: sliders.budgetVar,
      delay: sliders.delay,
      totalCost: calc.totalCost,
      margin: calc.margin,
      savedAt: new Date().toLocaleDateString('es-CO'),
      cashFlow: calc.cashFlow,
    }, ...prev]);
  };

  const handleReset = () => setSliders(DEFAULT_SLIDERS);

  const marginColor = calc.margin > 15 ? 'text-green-600 dark:text-green-400'
    : calc.margin > 5 ? 'text-amber-600 dark:text-amber-400'
    : 'text-red-600 dark:text-red-400';

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto space-y-6">

        {/* ── Header ─────────────────────────────────────────────────────── */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Simulador de Escenarios Financieros</h1>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">¿Qué pasa si...? — Ajusta variables y ve el impacto en tiempo real</p>
          </div>
          <div className="flex items-center gap-3 flex-wrap">
            <select
              value={selectedId}
              onChange={e => setSelectedId(e.target.value)}
              className="text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2 text-slate-700 dark:text-slate-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {MOCK_PROJECTS.map(p => (
                <option key={p.id} value={p.id}>{p.code} — {p.name}</option>
              ))}
            </select>
            <button
              onClick={handleSave}
              className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors"
            >
              Guardar escenario
            </button>
            <button
              onClick={handleReset}
              className="bg-white dark:bg-slate-800 hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 rounded-xl px-4 py-2.5 text-sm font-medium transition-colors"
            >
              Resetear
            </button>
          </div>
        </div>

        {/* ── Controls + Results ─────────────────────────────────────────── */}
        <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">

          {/* Controls — 40% */}
          <div className="lg:col-span-2 bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 space-y-5">
            <div className="flex items-center gap-2 mb-1">
              <div className="w-2 h-2 rounded-full bg-blue-500 animate-pulse" />
              <h2 className="text-base font-bold text-slate-900 dark:text-white">Variables del Escenario</h2>
            </div>

            <SliderRow
              label="Variación de presupuesto"
              value={sliders.budgetVar} min={-30} max={30} unit="%"
              onChange={set('budgetVar')}
              color={sliders.budgetVar < 0 ? 'green' : sliders.budgetVar > 0 ? 'red' : 'blue'}
            />
            <SliderRow
              label="Retraso del cronograma"
              value={sliders.delay} min={0} max={6} unit=" meses"
              onChange={set('delay')}
              color={sliders.delay > 0 ? 'amber' : 'blue'}
            />
            <SliderRow
              label="Cambio en productividad del equipo"
              value={sliders.productivity} min={-40} max={40} unit="%"
              onChange={set('productivity')}
              color={sliders.productivity < 0 ? 'red' : sliders.productivity > 0 ? 'green' : 'blue'}
            />
            <SliderRow
              label="Inflación de materiales"
              value={sliders.inflation} min={0} max={20} unit="%"
              onChange={set('inflation')}
              color={sliders.inflation > 10 ? 'red' : 'amber'}
            />
            <div className="space-y-1.5">
              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-slate-700 dark:text-slate-300">Tasa de cambio USD/COP</span>
                <span className="text-sm font-bold text-blue-600 tabular-nums">{fmt(sliders.usdCop)}</span>
              </div>
              <input
                type="number" value={sliders.usdCop} min={3000} max={6000} step={50}
                onChange={e => set('usdCop')(Number(e.target.value))}
                className="w-full text-sm bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2 text-slate-700 dark:text-slate-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <SliderRow
              label="Contingencia adicional"
              value={sliders.contingency} min={0} max={15} unit="%"
              onChange={set('contingency')}
              color="purple"
            />
            <SliderRow
              label="% Retención del cliente"
              value={sliders.retention} min={5} max={15} unit="%"
              onChange={set('retention')}
              color="amber"
            />

            {/* Project info */}
            <div className="pt-2 border-t border-slate-100 dark:border-slate-800 text-xs text-slate-400 dark:text-slate-500 space-y-1">
              <div className="flex justify-between"><span>Presupuesto base</span><span className="font-medium text-slate-600 dark:text-slate-400">{fmtCurrency(calc.baseCost)}</span></div>
              <div className="flex justify-between"><span>Ingreso proyectado</span><span className="font-medium text-slate-600 dark:text-slate-400">{fmtCurrency(calc.revenue)}</span></div>
              <div className="flex justify-between"><span>Cliente</span><span className="font-medium text-slate-600 dark:text-slate-400">{project.client}</span></div>
            </div>
          </div>

          {/* Results — 60% */}
          <div className="lg:col-span-3 space-y-5">

            {/* KPI Cards */}
            <div className="grid grid-cols-2 gap-4">
              <KPICard
                title="Nuevo costo proyectado"
                value={fmtCurrency(calc.totalCost)}
                delta={calc.costDelta}
                deltaLabel="% vs base"
                sub={`Base: ${fmtCurrency(calc.baseCost)}`}
              />
              <KPICard
                title="Nuevo margen"
                value={`${calc.margin.toFixed(1)}%`}
                delta={calc.margin - calc.baseMargin}
                deltaLabel="pp vs base"
                sub={`Base: ${calc.baseMargin.toFixed(1)}%`}
                valueColor={marginColor}
              />
              <KPICard
                title="Fecha estimada de finalización"
                value={calc.scenEndDate}
                sub={`Original: ${calc.baseEndDate}`}
                delta={sliders.delay}
                deltaLabel=" meses de retraso"
              />
              <KPICard
                title="Flujo de caja mínimo"
                value={fmtCurrency(calc.minCashFlow)}
                valueColor={calc.minCashFlow < 0 ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'}
                sub={calc.minCashFlow < 0 ? 'Alerta: flujo negativo' : 'Flujo positivo'}
              />
            </div>

            {/* Area Chart — Cash Flow */}
            <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
              <h3 className="text-sm font-bold text-slate-900 dark:text-white mb-4">Flujo de Caja Acumulado — Base vs Escenario</h3>
              <ResponsiveContainer width="100%" height={260}>
                <AreaChart data={chartData} margin={{ top: 5, right: 10, left: 10, bottom: 0 }}>
                  <defs>
                    <linearGradient id="gradBase" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.2} />
                      <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                    </linearGradient>
                    <linearGradient id="gradScen" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#ef4444" stopOpacity={0.2} />
                      <stop offset="95%" stopColor="#ef4444" stopOpacity={0} />
                    </linearGradient>
                    <linearGradient id="gradComp" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#8b5cf6" stopOpacity={0.2} />
                      <stop offset="95%" stopColor="#8b5cf6" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" strokeOpacity={0.5} />
                  <XAxis dataKey="month" tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false}
                    tickFormatter={v => `$${(v / 1000).toFixed(0)}k`} />
                  <Tooltip
                    formatter={(v, name) => [fmtCurrency(v), name === 'base' ? 'Base' : name === 'scenario' ? 'Escenario' : 'Comparar']}
                    contentStyle={{ background: '#1e293b', border: 'none', borderRadius: 12, fontSize: 12, color: '#f8fafc' }}
                  />
                  <Legend formatter={v => v === 'base' ? 'Base' : v === 'scenario' ? 'Escenario' : 'Comparar'} />
                  <ReferenceLine y={0} stroke="#ef4444" strokeDasharray="4 4" strokeOpacity={0.7} />
                  <Area type="monotone" dataKey="base" stroke="#3b82f6" fill="url(#gradBase)" strokeWidth={2} dot={false} />
                  <Area type="monotone" dataKey="scenario" stroke="#ef4444" fill="url(#gradScen)" strokeWidth={2} dot={false} />
                  {compareScenario && (
                    <Area type="monotone" dataKey="compare" stroke="#8b5cf6" fill="url(#gradComp)" strokeWidth={2} dot={false} strokeDasharray="5 3" />
                  )}
                </AreaChart>
              </ResponsiveContainer>
            </div>

            {/* Bar Chart — Cost Breakdown */}
            <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
              <h3 className="text-sm font-bold text-slate-900 dark:text-white mb-4">Desglose de Costos — Base vs Escenario</h3>
              <ResponsiveContainer width="100%" height={220}>
                <BarChart data={calc.breakdown} margin={{ top: 5, right: 10, left: 10, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" strokeOpacity={0.5} />
                  <XAxis dataKey="category" tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false}
                    tickFormatter={v => `$${(v / 1000).toFixed(0)}k`} />
                  <Tooltip
                    formatter={v => fmtCurrency(v)}
                    contentStyle={{ background: '#1e293b', border: 'none', borderRadius: 12, fontSize: 12, color: '#f8fafc' }}
                  />
                  <Legend />
                  <Bar dataKey="base" name="Base" fill="#3b82f6" radius={[4, 4, 0, 0]} />
                  <Bar dataKey="scenario" name="Escenario" fill="#ef4444" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>

        {/* ── Saved Scenarios Table ──────────────────────────────────────── */}
        {savedScenarios.length > 0 && (
          <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
            <div className="px-6 py-4 border-b border-slate-100 dark:border-slate-800">
              <h2 className="text-base font-bold text-slate-900 dark:text-white">Escenarios Guardados</h2>
              <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Haz clic en "Comparar" para superponer el flujo de caja en el gráfico</p>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-slate-50 dark:bg-slate-800/50">
                  <tr>
                    {['Nombre', 'Var. Presupuesto', 'Retraso', 'Costo Proyectado', 'Margen', 'Guardado', 'Acción'].map(h => (
                      <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                  {savedScenarios.map(s => (
                    <tr key={s.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
                      <td className="px-4 py-3 text-sm font-medium text-slate-900 dark:text-white">{s.name}</td>
                      <td className="px-4 py-3 text-sm">
                        <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${s.budgetVar > 0 ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' : s.budgetVar < 0 ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400'}`}>
                          {s.budgetVar > 0 ? '+' : ''}{s.budgetVar}%
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-400">
                        {s.delay > 0 ? `+${s.delay} meses` : 'Sin retraso'}
                      </td>
                      <td className="px-4 py-3 text-sm font-medium text-slate-900 dark:text-white tabular-nums">{fmtCurrency(s.totalCost)}</td>
                      <td className="px-4 py-3 text-sm">
                        <span className={`font-bold ${s.margin > 15 ? 'text-green-600 dark:text-green-400' : s.margin > 5 ? 'text-amber-600 dark:text-amber-400' : 'text-red-600 dark:text-red-400'}`}>
                          {s.margin.toFixed(1)}%
                        </span>
                      </td>
                      <td className="px-4 py-3 text-xs text-slate-500 dark:text-slate-400">{s.savedAt}</td>
                      <td className="px-4 py-3">
                        <button
                          onClick={() => setCompareId(compareId === s.id ? null : s.id)}
                          className={`text-xs font-medium rounded-lg px-3 py-1.5 transition-colors ${
                            compareId === s.id
                              ? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400'
                              : 'bg-slate-100 hover:bg-slate-200 text-slate-600 dark:bg-slate-800 dark:hover:bg-slate-700 dark:text-slate-400'
                          }`}
                        >
                          {compareId === s.id ? 'Quitar' : 'Comparar'}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

      </div>
    </div>
  );
}
