import React, { useState } from 'react';
import { MOCK_PROJECTS, MOCK_RISKS, getAllProjects, getProjectById, getRisksForProject } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';

const PROB_LABEL  = {1:'Muy baja',2:'Baja',3:'Media',4:'Alta',5:'Muy alta'};
const IMP_LABEL   = {1:'Mínimo',2:'Menor',3:'Moderado',4:'Mayor',5:'Crítico'};
const RESP_CFG    = {
  Mitigar:   'bg-blue-100 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400',
  Transferir:'bg-purple-100 text-purple-700 dark:bg-purple-500/10 dark:text-purple-400',
  Aceptar:   'bg-slate-100 text-slate-600 dark:bg-gray-500/10 dark:text-gray-400',
  Evitar:    'bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-400',
};
const STATUS_CFG  = {
  ACTIVO: 'bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-400',
  CERRADO:'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400',
  OCURRIDO:'bg-amber-100 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400',
};

function riskScore(p, i) { return p * i; }
function riskColor(score) {
  if (score >= 15) return { bg:'#EF4444', label:'Crítico',    text:'text-red-600 dark:text-red-400',    ring:'border-red-300 dark:border-red-500/50' };
  if (score >= 9)  return { bg:'#F97316', label:'Alto',       text:'text-orange-600 dark:text-orange-400', ring:'border-orange-300 dark:border-orange-500/50' };
  if (score >= 4)  return { bg:'#F59E0B', label:'Medio',      text:'text-amber-600 dark:text-amber-400',  ring:'border-amber-300 dark:border-amber-500/50' };
  return               { bg:'#10B981', label:'Bajo',       text:'text-emerald-600 dark:text-emerald-400', ring:'border-emerald-300 dark:border-emerald-500/50' };
}

// ── 5×5 Heat Matrix ─────────────────────────────────────────────────────────
function HeatMatrix({ risks }) {
  const cells = {};
  risks.forEach(r => {
    const k = `${r.probability}-${r.impact}`;
    if (!cells[k]) cells[k] = [];
    cells[k].push(r);
  });

  const cellBg = (p, i) => {
    const s = p*i;
    if (s>=15) return 'bg-red-500';
    if (s>=9)  return 'bg-orange-400';
    if (s>=4)  return 'bg-amber-300';
    return 'bg-emerald-200 dark:bg-emerald-900/30';
  };

  return (
    <div>
      <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-3">Matriz de calor (Probabilidad × Impacto)</p>
      <div className="flex gap-1">
        {/* Y axis label */}
        <div className="flex flex-col justify-between items-center w-5 py-1">
          {[5,4,3,2,1].map(p=>(
            <span key={p} className="text-xs text-slate-400 dark:text-gray-600 w-5 text-center">{p}</span>
          ))}
        </div>
        <div className="flex-1">
          {[5,4,3,2,1].map(p=>(
            <div key={p} className="flex gap-1 mb-1">
              {[1,2,3,4,5].map(i=>{
                const k = `${p}-${i}`;
                const list = cells[k] || [];
                return (
                  <div key={i} className={`flex-1 h-10 rounded-lg flex items-center justify-center relative ${cellBg(p,i)} opacity-80`}>
                    {list.length > 0 && (
                      <span className="absolute top-0.5 right-1 text-xs font-bold text-white">{list.length}</span>
                    )}
                    {list.map((r,ri)=>(
                      <div key={ri} className="w-2.5 h-2.5 rounded-full bg-white/80 shadow-sm mx-0.5" title={r.title}/>
                    ))}
                  </div>
                );
              })}
            </div>
          ))}
          {/* X axis */}
          <div className="flex gap-1 mt-1">
            {[1,2,3,4,5].map(i=><span key={i} className="flex-1 text-xs text-center text-slate-400 dark:text-gray-600">{i}</span>)}
          </div>
          <div className="flex justify-between text-xs text-slate-400 dark:text-gray-500 mt-0.5">
            <span>↑ Prob.</span><span>Impacto →</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Risk detail modal ────────────────────────────────────────────────────────
function RiskModal({ risk, onClose }) {
  const score    = riskScore(risk.probability, risk.impact);
  const cfg      = riskColor(score);
  const resScore = riskScore(risk.residualProb, risk.residualImpact);
  const resCfg   = riskColor(resScore);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onClose}/>
      <div className="relative w-full max-w-lg bg-white dark:bg-surface-800 rounded-2xl shadow-2xl border border-slate-200 dark:border-surface-700 overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <div>
            <span className="text-xs font-mono text-slate-400 dark:text-gray-500">{risk.code}</span>
            <h2 className="text-sm font-bold text-slate-900 dark:text-white mt-0.5">{risk.title}</h2>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-surface-700 transition cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>
        <div className="p-5 space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div className={`rounded-xl p-3 border ${cfg.ring}`}>
              <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">Riesgo inherente</p>
              <p className={`text-xl font-bold tabular-nums ${cfg.text}`}>{score}</p>
              <p className={`text-xs font-semibold ${cfg.text}`}>{cfg.label}</p>
              <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">P:{risk.probability} × I:{risk.impact}</p>
            </div>
            <div className={`rounded-xl p-3 border ${resCfg.ring}`}>
              <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">Riesgo residual</p>
              <p className={`text-xl font-bold tabular-nums ${resCfg.text}`}>{resScore}</p>
              <p className={`text-xs font-semibold ${resCfg.text}`}>{resCfg.label}</p>
              <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">P:{risk.residualProb} × I:{risk.residualImpact}</p>
            </div>
          </div>
          <div className="space-y-2.5 text-sm">
            {[
              ['Categoría',  risk.category],
              ['Respuesta',  risk.response],
              ['Responsable',risk.owner ? `${risk.owner.firstName} ${risk.owner.lastName}` : '—'],
              ['Fecha límite',risk.dueDate],
            ].map(([k,v])=>(
              <div key={k} className="flex gap-2">
                <span className="text-slate-400 dark:text-gray-500 w-28 flex-shrink-0">{k}:</span>
                <span className="text-slate-800 dark:text-gray-200 font-medium">{v}</span>
              </div>
            ))}
          </div>
          <div>
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">Plan de respuesta</p>
            <p className="text-sm text-slate-700 dark:text-gray-300 bg-slate-50 dark:bg-surface-700 rounded-xl p-3 leading-relaxed">{risk.plan}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function RisksPage() {
  const { selectedProjectId } = useProject();
  const projId = selectedProjectId || getAllProjects()[0]?.id || 'p4';
  const [selected,setSelected]= useState(null);
  const [filter,  setFilter]  = useState('all');

  const project = getProjectById(projId);
  const allRisks = getRisksForProject(projId);
  const risks = allRisks.filter(r => filter==='all' || r.status===filter);

  const active = allRisks.filter(r=>r.status==='ACTIVO');
  const critical= active.filter(r=>riskScore(r.probability,r.impact)>=15);
  const high    = active.filter(r=>{ const s=riskScore(r.probability,r.impact); return s>=9&&s<15; });

  return (
    <div className="space-y-5 pb-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Registro de Riesgos</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">{active.length} riesgos activos · {critical.length} críticos</p>
        </div>
        <div className="flex gap-2 flex-wrap">
          <span className="text-sm bg-white dark:bg-surface-800 border border-slate-200 dark:border-surface-700 rounded-lg px-3 py-1.5 text-slate-700 dark:text-gray-300 font-medium">
            {getProjectById(projId)?.code}
          </span>
          <select value={filter} onChange={e=>setFilter(e.target.value)}
            className="text-sm bg-white dark:bg-surface-800 border border-slate-200 dark:border-surface-700 rounded-lg px-3 py-1.5 text-slate-700 dark:text-gray-300 cursor-pointer">
            <option value="all">Todos</option>
            <option value="ACTIVO">Activos</option>
            <option value="CERRADO">Cerrados</option>
          </select>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
        {[
          {l:'Riesgos activos', v:active.length, c:'text-slate-900 dark:text-white'},
          {l:'Críticos (≥15)',  v:critical.length, c:critical.length?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400'},
          {l:'Altos (9–14)',    v:high.length, c:high.length?'text-orange-600 dark:text-orange-400':'text-emerald-600 dark:text-emerald-400'},
          {l:'Cerrados',        v:allRisks.filter(r=>r.status==='CERRADO').length, c:'text-emerald-600 dark:text-emerald-400'},
        ].map(({l,v,c})=>(
          <div key={l} className="bg-white dark:bg-surface-800 rounded-2xl p-4 border border-slate-200 dark:border-surface-700 shadow-sm">
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-widest mb-1.5">{l}</p>
            <p className={`text-2xl font-bold tabular-nums ${c}`}>{v}</p>
          </div>
        ))}
      </div>

      {/* Heat matrix + risk list side by side */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
        <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
          <HeatMatrix risks={active}/>
          <div className="mt-4 space-y-1.5">
            {[{s:15,l:'Crítico',c:'#EF4444'},{s:9,l:'Alto',c:'#F97316'},{s:4,l:'Medio',c:'#F59E0B'},{s:1,l:'Bajo',c:'#10B981'}].map(({s,l,c})=>(
              <div key={s} className="flex items-center gap-2 text-xs text-slate-500 dark:text-gray-400">
                <span className="w-3 h-3 rounded-sm" style={{background:c}}/>
                {l} ({s === 15 ? '≥15' : s === 9 ? '9–14' : s === 4 ? '4–8' : '1–3'})
              </div>
            ))}
          </div>
        </div>

        {/* Risk table */}
        <div className="xl:col-span-2 bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100 dark:border-surface-700">
                {['Código','Título','Categoría','Prob.','Imp.','Score','Respuesta','Estado',''].map(h=>(
                  <th key={h} className="px-4 py-2.5 text-left text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
              {risks.map(r=>{
                const score = riskScore(r.probability, r.impact);
                const cfg   = riskColor(score);
                return (
                  <tr key={r.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors cursor-pointer"
                    onClick={()=>setSelected(r)}>
                    <td className="px-4 py-3 text-xs font-mono text-slate-400 dark:text-gray-500">{r.code}</td>
                    <td className="px-4 py-3 max-w-[160px]">
                      <p className="text-sm font-medium text-slate-800 dark:text-gray-200 truncate">{r.title}</p>
                      <p className="text-xs text-slate-400 dark:text-gray-500">{r.owner ? `${r.owner.firstName} ${r.owner.lastName[0]}.` : '—'}</p>
                    </td>
                    <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">{r.category}</td>
                    <td className="px-4 py-3 text-xs font-semibold text-center text-slate-700 dark:text-gray-300">{PROB_LABEL[r.probability]?.substring(0,3)}</td>
                    <td className="px-4 py-3 text-xs font-semibold text-center text-slate-700 dark:text-gray-300">{IMP_LABEL[r.impact]?.substring(0,3)}</td>
                    <td className="px-4 py-3">
                      <span className={`text-sm font-bold tabular-nums ${cfg.text}`}>{score}</span>
                      <span className={`ml-1 text-xs ${cfg.text}`}>{cfg.label}</span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${RESP_CFG[r.response]||''}`}>{r.response}</span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${STATUS_CFG[r.status]||''}`}>{r.status}</span>
                    </td>
                    <td className="px-4 py-3 text-slate-300 dark:text-gray-600">›</td>
                  </tr>
                );
              })}
              {risks.length === 0 && (
                <tr><td colSpan={9} className="px-4 py-10 text-center text-sm text-slate-400 dark:text-gray-500">Sin riesgos registrados</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {selected && <RiskModal risk={selected} onClose={()=>setSelected(null)}/>}
    </div>
  );
}
