import React, { useState } from 'react';
import { MOCK_PROJECTS, MOCK_TASKS, getAllProjects, getProjectById, getTasksForProject } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';
import CSVImportModal from '../shared/CSVImportModal';

const STATUS_COLOR = { COMPLETADA:'#10B981', EN_PROCESO:'#2563EB', EN_VERIFICACION:'#8B5CF6', PENDIENTE:'#94a3b8', BLOQUEADA:'#EF4444' };
const STATUS_LABEL = { COMPLETADA:'Completada', EN_PROCESO:'En proceso', EN_VERIFICACION:'Verificación', PENDIENTE:'Pendiente', BLOQUEADA:'Bloqueada' };
const PRIORITY_DOT = { CRITICO:'bg-red-500', ALTO:'bg-orange-400', MEDIO:'bg-amber-400', BAJO:'bg-slate-400' };

const fmt = n => n>=1000?`$${(n/1000).toFixed(1)}K`:`$${n}`;

function buildWBS(tasks) {
  // Group by phase, then sub-group by wbsCode prefix
  const phases = {};
  tasks.forEach(t => {
    const ph = t.phase || 'Sin fase';
    if (!phases[ph]) phases[ph] = [];
    phases[ph].push(t);
  });
  return phases;
}

function PhaseRow({ phase, tasks, expanded, onToggle }) {
  const total    = tasks.length;
  const done     = tasks.filter(t=>t.status==='COMPLETADA').length;
  const pct      = total ? Math.round(done/total*100) : 0;
  const budget   = tasks.reduce((s,t)=>s+(t.plannedCost||0),0);
  const spent    = tasks.reduce((s,t)=>s+(t.actualCost||0),0);
  const hours    = tasks.reduce((s,t)=>s+(t.estimatedHours||0),0);
  const actHours = tasks.reduce((s,t)=>s+(t.actualHours||0),0);
  const barColor = pct>=75?'#10B981':pct>=40?'#2563EB':'#F59E0B';

  return (
    <div className="border border-slate-200 dark:border-surface-700 rounded-xl overflow-hidden mb-2">
      {/* Phase header */}
      <button onClick={onToggle}
        className="w-full flex items-center gap-3 px-4 py-3 bg-slate-50 dark:bg-surface-700/60 hover:bg-slate-100 dark:hover:bg-surface-700 transition-colors cursor-pointer text-left">
        <span className={`text-slate-400 dark:text-gray-500 transition-transform ${expanded?'rotate-90':''}`}>▶</span>
        <span className="flex-1 text-sm font-bold text-slate-800 dark:text-gray-200">{phase}</span>
        <div className="hidden sm:flex items-center gap-6 text-xs text-slate-500 dark:text-gray-400">
          <span><b className="text-slate-800 dark:text-white">{done}/{total}</b> tareas</span>
          <span><b className="text-slate-800 dark:text-white">{hours}h</b> planeadas</span>
          <span><b className="text-slate-800 dark:text-white">{fmt(budget)}</b> costo</span>
        </div>
        <div className="flex items-center gap-2 w-28">
          <div className="flex-1 h-1.5 bg-slate-200 dark:bg-surface-600 rounded-full overflow-hidden">
            <div className="h-full rounded-full" style={{width:`${pct}%`,background:barColor}}/>
          </div>
          <span className="text-xs font-semibold w-8 text-right" style={{color:barColor}}>{pct}%</span>
        </div>
      </button>

      {/* Task rows */}
      {expanded && (
        <div className="divide-y divide-slate-50 dark:divide-surface-700">
          {tasks.map(t=>{
            const isOver = t.actualCost > t.plannedCost && t.plannedCost > 0;
            const behind = (t.actualHours||0) > (t.estimatedHours||0);
            return (
              <div key={t.id} className={`flex items-center gap-3 px-5 py-2.5 hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors ${t.isMilestone?'bg-amber-50/40 dark:bg-amber-500/5':''}`}>
                {/* WBS code */}
                <span className="text-xs font-mono text-slate-400 dark:text-gray-600 w-8 flex-shrink-0">{t.wbsCode}</span>

                {/* Milestone diamond or priority dot */}
                {t.isMilestone
                  ? <span className="text-amber-400 flex-shrink-0">◆</span>
                  : <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${PRIORITY_DOT[t.priority]}`}/>
                }

                {/* Title */}
                <span className={`flex-1 text-sm truncate ${t.isMilestone?'font-semibold text-amber-700 dark:text-amber-400':'text-slate-800 dark:text-gray-200'}`}>
                  {t.title}
                </span>

                {/* Deps */}
                {(t.predecessors||[]).length > 0 && (
                  <span className="hidden lg:flex items-center gap-1 text-xs text-slate-400 dark:text-gray-500 flex-shrink-0">
                    <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M13 5l7 7-7 7M5 5l7 7-7 7"/></svg>
                    {t.predecessors.map(p=>`${p.id}(${p.type})`).join(', ')}
                  </span>
                )}

                {/* Assignee */}
                <span className="hidden md:block text-xs text-slate-400 dark:text-gray-500 w-20 truncate flex-shrink-0 text-right">
                  {t.assignee ? `${t.assignee.firstName} ${t.assignee.lastName[0]}.` : '—'}
                </span>

                {/* Hours */}
                <span className={`hidden lg:block text-xs w-16 text-right flex-shrink-0 tabular-nums font-mono ${behind?'text-red-600 dark:text-red-400':'text-slate-500 dark:text-gray-400'}`}>
                  {t.actualHours||0}h/{t.estimatedHours||0}h
                </span>

                {/* Cost */}
                <span className={`hidden xl:block text-xs w-20 text-right flex-shrink-0 tabular-nums font-mono ${isOver?'text-red-600 dark:text-red-400':'text-slate-500 dark:text-gray-400'}`}>
                  {fmt(t.actualCost||0)}/{fmt(t.plannedCost||0)}
                </span>

                {/* Status badge */}
                <span className="text-xs px-2 py-0.5 rounded-full font-medium flex-shrink-0"
                  style={{background:`${STATUS_COLOR[t.status]}18`, color:STATUS_COLOR[t.status]}}>
                  {STATUS_LABEL[t.status]}
                </span>

                {/* Critical flag */}
                {t.isCritical && !t.isMilestone && (
                  <span className="text-red-400 text-xs flex-shrink-0" title="Ruta crítica">⚡</span>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default function WBSPage() {
  const { selectedProjectId } = useProject();
  const projId = selectedProjectId || getAllProjects()[0]?.id || 'p4';
  const [expanded, setExpanded] = useState({});
  const [showImport, setShowImport] = useState(false);
  const [importedTasks, setImportedTasks] = useState([]);

  const project = getProjectById(projId);
  const baseTasks = getTasksForProject(project.id);
  const tasks   = [...baseTasks, ...importedTasks.filter(t => !selectedProjectId || t.projectId === projId)];
  const phases  = buildWBS(tasks);

  const handleImport = (newTasks) => {
    const withProject = newTasks.map(t => ({ ...t, projectId: projId }));
    setImportedTasks(prev => [...prev, ...withProject]);
  };

  const toggle = ph => setExpanded(e=>({...e,[ph]:!e[ph]}));
  const expandAll  = () => { const e={}; Object.keys(phases).forEach(k=>e[k]=true);  setExpanded(e); };
  const collapseAll= () => setExpanded({});

  // Totals
  const totalBudget = tasks.reduce((s,t)=>s+(t.plannedCost||0),0);
  const totalSpent  = tasks.reduce((s,t)=>s+(t.actualCost||0),0);
  const totalHours  = tasks.reduce((s,t)=>s+(t.estimatedHours||0),0);
  const totalActH   = tasks.reduce((s,t)=>s+(t.actualHours||0),0);
  const totalDone   = tasks.filter(t=>t.status==='COMPLETADA').length;

  return (
    <div className="space-y-4 pb-6">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">EDT / WBS</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">Estructura de Desglose del Trabajo</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>
          <button onClick={expandAll}   className="text-xs px-3 py-1.5 rounded-lg border border-slate-200 dark:border-surface-700 text-slate-500 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-surface-700 transition cursor-pointer">Expandir todo</button>
          <button onClick={collapseAll} className="text-xs px-3 py-1.5 rounded-lg border border-slate-200 dark:border-surface-700 text-slate-500 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-surface-700 transition cursor-pointer">Colapsar todo</button>
          <button onClick={() => setShowImport(true)}
            className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-medium transition cursor-pointer">
            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
            </svg>
            Importar CSV/Excel
          </button>
        </div>
      </div>

      {/* Summary KPIs */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
        {[
          {l:'Tareas totales',    v:`${totalDone}/${tasks.length}`, sub:`${tasks.filter(t=>t.isMilestone).length} hitos`, c:'text-slate-900 dark:text-white'},
          {l:'Costo planeado',   v:fmt(totalBudget), sub:`Ejecutado: ${fmt(totalSpent)}`, c: totalSpent>totalBudget?'text-red-600 dark:text-red-400':'text-blue-600 dark:text-blue-400'},
          {l:'Horas estimadas',  v:`${totalHours}h`, sub:`Registradas: ${totalActH}h`,   c: totalActH>totalHours?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400'},
          {l:'Tareas críticas',  v:tasks.filter(t=>t.isCritical&&!t.isMilestone).length, sub:'en ruta crítica', c:'text-red-600 dark:text-red-400'},
        ].map(({l,v,sub,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>
            {sub && <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{sub}</p>}
          </div>
        ))}
      </div>

      {/* Column headers */}
      <div className="flex items-center gap-3 px-5 py-2 text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider">
        <span className="w-8 flex-shrink-0">WBS</span>
        <span className="w-4 flex-shrink-0"/>
        <span className="flex-1">Tarea</span>
        <span className="hidden lg:block w-32 text-right">Predecesoras</span>
        <span className="hidden md:block w-20 text-right">Responsable</span>
        <span className="hidden lg:block w-16 text-right">Horas</span>
        <span className="hidden xl:block w-20 text-right">Costo</span>
        <span className="w-20 text-center">Estado</span>
        <span className="w-4 flex-shrink-0"/>
      </div>

      {/* Phase groups */}
      {Object.entries(phases).map(([ph, tasks]) => (
        <PhaseRow key={ph} phase={ph} tasks={tasks}
          expanded={!!expanded[ph]} onToggle={()=>toggle(ph)}/>
      ))}

      {importedTasks.length > 0 && (
        <div className="flex items-center gap-2 text-xs text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-500/10 border border-emerald-200 dark:border-emerald-500/30 rounded-xl px-4 py-2">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/>
          </svg>
          {importedTasks.length} tarea{importedTasks.length !== 1 ? 's' : ''} importada{importedTasks.length !== 1 ? 's' : ''} en esta sesión
          <button onClick={() => setImportedTasks([])} className="ml-auto text-emerald-500 hover:text-emerald-700 dark:hover:text-emerald-300 cursor-pointer">✕ Limpiar</button>
        </div>
      )}

      {showImport && (
        <CSVImportModal
          projectName={project.name}
          onClose={() => setShowImport(false)}
          onImport={(tasks) => { handleImport(tasks); setShowImport(false); }}
        />
      )}
    </div>
  );
}
