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

const PORTFOLIO_DATA = {
  p1: {
    ragStatus: 'VERDE',
    methodology: 'PMI',
    progressPct: 62,
    cpi: 1.04,
    spi: 0.98,
    budget: 18500000,
    spent: 11470000,
    committed: 2100000,
    activeRisks: 3,
    manager: 'Carlos Mendoza',
    nextMilestone: { name: 'Estructura Nivel 12', date: '2026-07-15' },
  },
  p2: {
    ragStatus: 'AMARILLO',
    methodology: 'Agile',
    progressPct: 45,
    cpi: 0.91,
    spi: 0.88,
    budget: 2200000,
    spent: 1089000,
    committed: 320000,
    activeRisks: 5,
    manager: 'Laura Vásquez',
    nextMilestone: { name: 'Mezcla Final Pista 4', date: '2026-07-02' },
  },
  p3: {
    ragStatus: 'ROJO',
    methodology: 'PMI',
    progressPct: 31,
    cpi: 0.78,
    spi: 0.72,
    budget: 9400000,
    spent: 3822000,
    committed: 1800000,
    activeRisks: 11,
    manager: 'Roberto Salas',
    nextMilestone: { name: 'Go-Live Módulo Finanzas', date: '2026-08-01' },
  },
  p4: {
    ragStatus: 'VERDE',
    methodology: 'Scrum',
    progressPct: 78,
    cpi: 1.02,
    spi: 1.05,
    budget: 1800000,
    spent: 1270000,
    committed: 180000,
    activeRisks: 2,
    manager: 'Álvaro Romero',
    nextMilestone: { name: 'Sprint 14 Demo', date: '2026-07-05' },
  },
};

const RAG_CONFIG = {
  VERDE:    { label: 'Verde',    dot: 'bg-emerald-500', badge: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400', bar: 'bg-emerald-500' },
  AMARILLO: { label: 'Amarillo', dot: 'bg-amber-400',   badge: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400',       bar: 'bg-amber-400' },
  ROJO:     { label: 'Rojo',     dot: 'bg-red-500',     badge: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400',                bar: 'bg-red-500' },
};

const RAG_ORDER = { ROJO: 0, AMARILLO: 1, VERDE: 2 };

function fmt(n) {
  if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000)     return `$${(n / 1_000).toFixed(0)}K`;
  return `$${n}`;
}

function fmtLarge(n) {
  return `$${(n / 1_000_000).toFixed(1)}M`;
}

function daysRemaining(dateStr) {
  const diff = Math.ceil((new Date(dateStr) - new Date()) / (1000 * 60 * 60 * 24));
  return diff;
}

function CPIBadge({ value }) {
  const color = value >= 0.95 ? 'text-emerald-600 dark:text-emerald-400' : value >= 0.85 ? 'text-amber-600 dark:text-amber-400' : 'text-red-600 dark:text-red-400';
  return <span className={`font-semibold ${color}`}>{value.toFixed(2)}</span>;
}

function SPIBadge({ value }) {
  const color = value >= 0.95 ? 'text-emerald-600 dark:text-emerald-400' : value >= 0.85 ? 'text-amber-600 dark:text-amber-400' : 'text-red-600 dark:text-red-400';
  return <span className={`font-semibold ${color}`}>{value.toFixed(2)}</span>;
}

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

  const allProjects = useMemo(() =>
    MOCK_PROJECTS.map(p => ({ ...p, ...PORTFOLIO_DATA[p.id] }))
  , []);

  const filteredProjects = useMemo(() =>
    allProjects.filter(p => !selectedProjectId || p.id === selectedProjectId)
  , [allProjects, selectedProjectId]);

  const kpis = useMemo(() => {
    const active = filteredProjects.length;
    const totalBudget = filteredProjects.reduce((s, p) => s + p.budget, 0);
    const avgCpi = filteredProjects.length
      ? filteredProjects.reduce((s, p) => s + p.cpi, 0) / filteredProjects.length
      : 0;
    const atRisk = filteredProjects.filter(p => p.ragStatus === 'ROJO').length;
    return { active, totalBudget, avgCpi, atRisk };
  }, [filteredProjects]);

  const sortedForTable = useMemo(() =>
    [...filteredProjects].sort((a, b) => RAG_ORDER[a.ragStatus] - RAG_ORDER[b.ragStatus])
  , [filteredProjects]);

  const chartData = useMemo(() =>
    filteredProjects.map(p => ({
      code: p.code.replace('PRY-2026-', 'PRY-'),
      'Presupuesto': parseFloat((p.budget / 1_000_000).toFixed(2)),
      'Incurrido':   parseFloat((p.spent  / 1_000_000).toFixed(2)),
      'Comprometido':parseFloat((p.committed / 1_000_000).toFixed(2)),
    }))
  , [filteredProjects]);

  const today = new Date().toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });

  const cpiColor = kpis.avgCpi >= 0.95 ? 'text-emerald-600 dark:text-emerald-400' : kpis.avgCpi >= 0.85 ? '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">

        {/* 1. HEADER */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Portafolio de Proyectos</h1>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5 capitalize">{today}</p>
          </div>
          <div className="flex items-center gap-3 flex-wrap">
            <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300">
              <span className="w-2 h-2 rounded-full bg-slate-400"></span>
              {filteredProjects.length} proyecto{filteredProjects.length !== 1 ? 's' : ''} total
            </span>
            <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-400">
              <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
              {filteredProjects.filter(p => p.ragStatus === 'VERDE').length} en verde
            </span>
            {kpis.atRisk > 0 && (
              <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-400">
                <span className="w-2 h-2 rounded-full bg-red-500"></span>
                {kpis.atRisk} en riesgo
              </span>
            )}
          </div>
        </div>

        {/* 2. KPI STRIP */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
            <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">Proyectos activos</p>
            <p className="mt-2 text-3xl font-bold text-slate-900 dark:text-white">{kpis.active}</p>
            <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">en portafolio</p>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
            <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">Presupuesto total</p>
            <p className="mt-2 text-3xl font-bold text-slate-900 dark:text-white">
              {`$${(kpis.totalBudget / 1_000_000).toFixed(1)}M`}
            </p>
            <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">presupuesto aprobado</p>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
            <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">CPI promedio</p>
            <p className={`mt-2 text-3xl font-bold ${cpiColor}`}>{kpis.avgCpi.toFixed(2)}</p>
            <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">índice costo-desempeño</p>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
            <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">Proyectos RAG rojo</p>
            <div className="mt-2 flex items-center gap-2">
              <p className="text-3xl font-bold text-slate-900 dark:text-white">{kpis.atRisk}</p>
              {kpis.atRisk > 0 && (
                <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400">
                  Atención
                </span>
              )}
            </div>
            <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">requieren acción</p>
          </div>
        </div>

        {/* 3. PROJECT CARDS GRID */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          {filteredProjects.map(project => {
            const rag = RAG_CONFIG[project.ragStatus];
            const days = daysRemaining(project.nextMilestone.date);
            const variacion = project.budget - project.spent;
            return (
              <div
                key={project.id}
                className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden transition-shadow hover:shadow-lg hover:shadow-slate-200/60 dark:hover:shadow-slate-900/80"
              >
                {/* Card header */}
                <div className="p-5 pb-4">
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex items-center gap-2.5 min-w-0">
                      <span className={`w-3 h-3 rounded-full flex-shrink-0 ${rag.dot}`}></span>
                      <div className="min-w-0">
                        <h3 className="font-bold text-slate-900 dark:text-white text-sm leading-tight truncate">{project.name}</h3>
                        <p className="text-xs text-slate-500 dark:text-slate-400">{project.code}</p>
                      </div>
                    </div>
                    <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium flex-shrink-0 ${rag.badge}`}>
                      {rag.label}
                    </span>
                  </div>

                  <div className="mt-3 flex items-center gap-2 flex-wrap">
                    <span className="text-xs text-slate-500 dark:text-slate-400">{project.client}</span>
                    <span className="text-slate-300 dark:text-slate-600">·</span>
                    <span className="rounded-full px-2 py-0.5 text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400">
                      {project.methodology}
                    </span>
                    <span className="text-slate-300 dark:text-slate-600">·</span>
                    <span className="text-xs text-slate-500 dark:text-slate-400">{project.manager}</span>
                  </div>

                  {/* Progress bar */}
                  <div className="mt-4">
                    <div className="flex justify-between items-center mb-1.5">
                      <span className="text-xs text-slate-500 dark:text-slate-400">Avance general</span>
                      <span className="text-xs font-semibold text-slate-700 dark:text-slate-300">{project.progressPct}%</span>
                    </div>
                    <div className="h-2 bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
                      <div
                        className={`h-full rounded-full ${rag.bar} transition-all`}
                        style={{ width: `${project.progressPct}%` }}
                      ></div>
                    </div>
                  </div>

                  {/* Mini metrics 2x2 */}
                  <div className="mt-4 grid grid-cols-2 gap-3">
                    <div className="bg-slate-50 dark:bg-slate-800/50 rounded-xl p-3">
                      <p className="text-xs text-slate-500 dark:text-slate-400">Presupuesto</p>
                      <p className="text-sm font-bold text-slate-900 dark:text-white mt-0.5">{fmt(project.budget)}</p>
                    </div>
                    <div className="bg-slate-50 dark:bg-slate-800/50 rounded-xl p-3">
                      <p className="text-xs text-slate-500 dark:text-slate-400">CPI</p>
                      <p className="text-sm font-bold mt-0.5"><CPIBadge value={project.cpi} /></p>
                    </div>
                    <div className="bg-slate-50 dark:bg-slate-800/50 rounded-xl p-3">
                      <p className="text-xs text-slate-500 dark:text-slate-400">SPI</p>
                      <p className="text-sm font-bold mt-0.5"><SPIBadge value={project.spi} /></p>
                    </div>
                    <div className="bg-slate-50 dark:bg-slate-800/50 rounded-xl p-3">
                      <p className="text-xs text-slate-500 dark:text-slate-400">Riesgos activos</p>
                      <p className={`text-sm font-bold mt-0.5 ${project.activeRisks >= 8 ? 'text-red-600 dark:text-red-400' : project.activeRisks >= 4 ? 'text-amber-600 dark:text-amber-400' : 'text-slate-900 dark:text-white'}`}>
                        {project.activeRisks}
                      </p>
                    </div>
                  </div>

                  {/* Next milestone */}
                  <div className="mt-4 flex items-center gap-2 p-3 rounded-xl bg-slate-50 dark:bg-slate-800/50 border border-slate-100 dark:border-slate-800">
                    <svg className="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs text-slate-500 dark:text-slate-400">Próximo hito</p>
                      <p className="text-xs font-semibold text-slate-800 dark:text-slate-200 truncate">{project.nextMilestone.name}</p>
                    </div>
                    <div className="text-right flex-shrink-0">
                      <p className="text-xs text-slate-500 dark:text-slate-400">{new Date(project.nextMilestone.date).toLocaleDateString('es-ES', { day: '2-digit', month: 'short' })}</p>
                      <p className={`text-xs font-semibold ${days <= 7 ? 'text-red-600 dark:text-red-400' : days <= 14 ? 'text-amber-600 dark:text-amber-400' : 'text-slate-600 dark:text-slate-400'}`}>
                        {days > 0 ? `en ${days}d` : days === 0 ? 'hoy' : `hace ${Math.abs(days)}d`}
                      </p>
                    </div>
                  </div>
                </div>

                {/* Status bar */}
                <div className={`h-1 w-full ${rag.bar}`}></div>
              </div>
            );
          })}
        </div>

        {/* 4. PERFORMANCE COMPARISON CHART */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
          <div className="mb-4">
            <h2 className="text-base font-bold text-slate-900 dark:text-white">Comparativa de Desempeño Financiero</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">Presupuesto vs Costo incurrido vs Comprometido — en millones USD</p>
          </div>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" strokeOpacity={0.6} />
              <XAxis dataKey="code" tick={{ fontSize: 11, fill: '#94a3b8' }} />
              <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} tickFormatter={v => `$${v}M`} />
              <Tooltip
                formatter={(value, name) => [`$${value}M`, name]}
                contentStyle={{ borderRadius: '12px', border: '1px solid #e2e8f0', fontSize: '12px' }}
              />
              <Legend wrapperStyle={{ fontSize: '12px' }} />
              <Bar dataKey="Presupuesto"  fill="#3b82f6" radius={[4, 4, 0, 0]} />
              <Bar dataKey="Incurrido"    fill="#ef4444" radius={[4, 4, 0, 0]} />
              <Bar dataKey="Comprometido" fill="#f59e0b" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>

        {/* 5. PORTFOLIO HEALTH TABLE */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
          <div className="p-6 pb-4">
            <h2 className="text-base font-bold text-slate-900 dark:text-white">Salud del Portafolio</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">Ordenado por prioridad RAG — proyectos en riesgo primero</p>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-slate-50 dark:bg-slate-800/60">
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Código</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Proyecto</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-right">% Avance</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-right">CPI</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-right">SPI</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-right">Presupuesto</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-right">Incurrido</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-right">Variacion</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-center">RAG</th>
                  <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Gerente</th>
                </tr>
              </thead>
              <tbody>
                {sortedForTable.map(project => {
                  const rag = RAG_CONFIG[project.ragStatus];
                  const variacion = project.budget - project.spent;
                  const varColor = variacion >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400';
                  return (
                    <tr key={project.id} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
                      <td className="px-4 py-3 text-xs font-mono text-slate-600 dark:text-slate-400 whitespace-nowrap">{project.code}</td>
                      <td className="px-4 py-3">
                        <div>
                          <p className="text-sm font-medium text-slate-900 dark:text-white whitespace-nowrap">{project.name}</p>
                          <p className="text-xs text-slate-500 dark:text-slate-400">{project.client}</p>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <div className="w-16 h-1.5 bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
                            <div className={`h-full rounded-full ${rag.bar}`} style={{ width: `${project.progressPct}%` }}></div>
                          </div>
                          <span className="text-sm font-semibold text-slate-700 dark:text-slate-300 w-8 text-right">{project.progressPct}%</span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-right"><CPIBadge value={project.cpi} /></td>
                      <td className="px-4 py-3 text-right"><SPIBadge value={project.spi} /></td>
                      <td className="px-4 py-3 text-right text-sm text-slate-700 dark:text-slate-300 whitespace-nowrap">{fmtLarge(project.budget)}</td>
                      <td className="px-4 py-3 text-right text-sm text-slate-700 dark:text-slate-300 whitespace-nowrap">{fmtLarge(project.spent)}</td>
                      <td className={`px-4 py-3 text-right text-sm font-semibold whitespace-nowrap ${varColor}`}>
                        {variacion >= 0 ? '+' : ''}{fmtLarge(variacion)}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${rag.badge}`}>{rag.label}</span>
                      </td>
                      <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-400 whitespace-nowrap">{project.manager}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

      </div>
    </div>
  );
}
