import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { projectsService } from '../../services/projects.service';
import KanbanBoard from './KanbanBoard';
import ProjectPropertiesModal from './ProjectPropertiesModal';

const RAG_BADGE = {
  VERDE:    'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-400',
  AMARILLO: 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-400',
  ROJO:     'bg-red-100 text-red-700 dark:bg-red-500/15 dark:text-red-400',
};

const fmt = n => {
  if (!n) return '—';
  const num = Number(n);
  return num >= 1_000_000 ? `$${(num/1_000_000).toFixed(1)}M` : num >= 1000 ? `$${(num/1000).toFixed(0)}K` : `$${num}`;
};

export default function ProjectDetail() {
  const { id } = useParams();
  const [project, setProject] = useState(null);
  const [tasks,   setTasks]   = useState([]);
  const [loading, setLoading] = useState(true);
  const [tab,       setTab]       = useState('kanban');
  const [showProps, setShowProps] = useState(false);

  useEffect(() => {
    Promise.all([
      projectsService.getById(id),
      projectsService.getTasks(id),
    ]).then(([pd, td]) => {
      setProject(pd.project);
      setTasks(td.tasks || []);
    }).finally(() => setLoading(false));
  }, [id]);

  if (loading) return (
    <div className="space-y-4 animate-pulse">
      <div className="h-6 w-48 bg-slate-100 dark:bg-surface-700 rounded"/>
      <div className="h-10 w-96 bg-slate-100 dark:bg-surface-700 rounded"/>
      <div className="grid grid-cols-4 gap-3">
        {[1,2,3,4].map(i=><div key={i} className="h-20 bg-slate-100 dark:bg-surface-800 rounded-xl border border-slate-200 dark:border-surface-700"/>)}
      </div>
    </div>
  );

  if (!project) return (
    <div className="text-center py-16 text-slate-400 dark:text-gray-500 text-sm">Proyecto no encontrado</div>
  );

  const pct = project.progressPct ?? 0;
  const barColor = pct >= 75 ? '#10B981' : pct >= 40 ? '#2563EB' : '#F59E0B';
  const done  = tasks.filter(t=>t.status==='COMPLETADA').length;
  const inProg= tasks.filter(t=>t.status==='EN_PROCESO').length;
  const blocked=tasks.filter(t=>t.status==='BLOQUEADA').length;

  return (
    <div className="space-y-5 pb-6">
      {/* Breadcrumb + header */}
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <nav className="flex items-center gap-2 text-sm text-slate-400 dark:text-gray-500 mb-2">
            <Link to="/projects" className="hover:text-blue-600 dark:hover:text-blue-400 transition">Proyectos</Link>
            <span>/</span>
            <span className="text-slate-600 dark:text-gray-400 font-mono text-xs">{project.code}</span>
          </nav>
          <h1 className="text-xl font-bold text-slate-900 dark:text-white">{project.name}</h1>
          {project.client && <p className="text-sm text-slate-500 dark:text-gray-400 mt-0.5">{project.client} · {project.methodology}</p>}
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <span className={`text-xs px-3 py-1.5 rounded-full font-semibold ${RAG_BADGE[project.ragStatus] || RAG_BADGE.VERDE}`}>
            RAG: {project.ragStatus}
          </span>
          <button onClick={() => setShowProps(true)}
            title="Propiedades del proyecto"
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-lg border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 transition-colors 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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
            </svg>
            Propiedades
          </button>
        </div>
      </div>

      {/* KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        {[
          { label:'Avance',      value:`${pct}%`,                    sub:`${done} de ${tasks.length} tareas` },
          { label:'Presupuesto', value:fmt(project.budget),          sub:project.category },
          { label:'En proceso',  value:inProg,                       sub:'tareas activas' },
          { label:'Bloqueadas',  value:blocked, sub:'requieren atención',
            cls: blocked > 0 ? 'text-red-600 dark:text-red-400' : 'text-slate-900 dark:text-white' },
        ].map(({label,value,sub,cls})=>(
          <div key={label} 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 text-slate-400 dark:text-gray-500 mb-1.5 uppercase tracking-wider font-semibold">{label}</p>
            <p className={`text-xl font-bold tabular-nums ${cls || 'text-slate-900 dark:text-white'}`}>{value}</p>
            {sub && <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{sub}</p>}
          </div>
        ))}
      </div>

      {/* Progress bar */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl p-4 border border-slate-200 dark:border-surface-700 shadow-sm">
        <div className="flex justify-between text-xs mb-2">
          <span className="text-slate-500 dark:text-gray-400 font-medium">Avance del proyecto</span>
          <span className="font-bold tabular-nums" style={{color:barColor}}>{pct}%</span>
        </div>
        <div className="h-2.5 bg-slate-100 dark:bg-surface-600 rounded-full overflow-hidden">
          <div className="h-full rounded-full transition-all" style={{width:`${pct}%`, background:barColor}}/>
        </div>
        <div className="flex justify-between text-xs text-slate-300 dark:text-gray-600 mt-1.5">
          <span>{project.startDate ? new Date(project.startDate).toLocaleDateString('es-MX',{month:'short',day:'numeric',year:'numeric'}) : '—'}</span>
          <span>{project.plannedEndDate ? new Date(project.plannedEndDate).toLocaleDateString('es-MX',{month:'short',day:'numeric',year:'numeric'}) : '—'}</span>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-slate-100 dark:bg-surface-800 rounded-xl p-1 w-fit border border-slate-200 dark:border-surface-700">
        {[
          {id:'kanban', label:'Tablero Kanban'},
          {id:'info',   label:'Información'},
        ].map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)}
            className={`px-4 py-1.5 text-sm font-medium rounded-lg transition cursor-pointer
              ${tab===t.id
                ? 'bg-white dark:bg-surface-700 text-slate-900 dark:text-white shadow-sm'
                : 'text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200'}`}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'kanban' && (
        <KanbanBoard projectId={id} tasks={tasks} onTasksChange={setTasks}/>
      )}

      {showProps && (
        <ProjectPropertiesModal
          project={project}
          onClose={() => setShowProps(false)}
          onSave={updated => {
            const merged = { ...project, ...updated };
            setProject(merged);
            // Persist to localStorage (only for non-mock projects)
            try {
              const stored = JSON.parse(localStorage.getItem('arpm_projects') || '[]');
              const idx = stored.findIndex(p => p.id === merged.id);
              if (idx >= 0) { stored[idx] = merged; }
              else { stored.push(merged); }
              localStorage.setItem('arpm_projects', JSON.stringify(stored));
            } catch {}
            setShowProps(false);
          }}
        />
      )}

      {tab === 'info' && (
        <div className="bg-white dark:bg-surface-800 rounded-2xl p-6 border border-slate-200 dark:border-surface-700 shadow-sm space-y-4">
          {project.description && (
            <p className="text-sm text-slate-600 dark:text-gray-300 leading-relaxed">{project.description}</p>
          )}
          <div className="grid grid-cols-2 gap-x-8 gap-y-3 text-sm border-t border-slate-100 dark:border-surface-700 pt-4">
            {[
              ['Inicio',       project.startDate ? new Date(project.startDate).toLocaleDateString('es-MX') : '—'],
              ['Fin planeado', project.plannedEndDate ? new Date(project.plannedEndDate).toLocaleDateString('es-MX') : '—'],
              ['Tipo',         project.type || '—'],
              ['Categoría',    project.category || '—'],
              ['Estado',       (project.status||'').replace('_',' ')],
              ['Metodología',  project.methodology || '—'],
            ].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>
      )}
    </div>
  );
}
