import React, { useEffect, useState, useRef } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { projectsService } from '../../services/projects.service';
import { useProject } from '../../context/ProjectContext';
import { MOCK_PROJECTS } from '../../services/mockData';

const STATUS_COLORS = {
  ACTIVO:     'bg-blue-100 text-blue-700 dark:bg-blue-500/15 dark:text-blue-400',
  PAUSADO:    'bg-slate-100 text-slate-500 dark:bg-gray-500/15 dark:text-gray-400',
  COMPLETADO: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-400',
  EN_RIESGO:  'bg-red-100 text-red-700 dark:bg-red-500/15 dark:text-red-400',
};
const RAG_DOT   = { VERDE:'bg-emerald-500', AMARILLO:'bg-amber-400', ROJO:'bg-red-500' };
const MOCK_IDS  = new Set(MOCK_PROJECTS.map(p => p.id));

// ── Delete modal ──────────────────────────────────────────────────────────────
function DeleteModal({ project, onCancel, onDeleted }) {
  const [pwd, setPwd]     = useState('');
  const [err, setErr]     = useState('');
  const [busy, setBusy]   = useState(false);
  const inputRef          = useRef(null);

  useEffect(() => { inputRef.current?.focus(); }, []);

  const confirm = () => {
    setErr('');
    setBusy(true);
    // Use the same password as login
    const settings = JSON.parse(localStorage.getItem('arpm_settings') || '{}');
    const loginPwd = settings.adminPassword || 'Admin123!';
    if (pwd !== loginPwd) {
      setErr('Contraseña incorrecta');
      setBusy(false);
      inputRef.current?.focus();
      return;
    }
    // Delete from arpm_projects
    const stored  = JSON.parse(localStorage.getItem('arpm_projects') || '[]');
    const updated = stored.filter(p => p.id !== project.id);
    localStorage.setItem('arpm_projects', JSON.stringify(updated));
    // Delete tasks
    const tasks = JSON.parse(localStorage.getItem('arpm_tasks') || '{}');
    delete tasks[project.id];
    localStorage.setItem('arpm_tasks', JSON.stringify(tasks));
    setBusy(false);
    onDeleted(project.id);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-sm p-6 space-y-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-red-100 dark:bg-red-500/15 flex items-center justify-center flex-shrink-0">
            <svg className="w-5 h-5 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
            </svg>
          </div>
          <div>
            <h3 className="font-semibold text-slate-900 dark:text-white text-sm">Eliminar proyecto</h3>
            <p className="text-xs text-slate-500 dark:text-gray-400 mt-0.5 leading-tight">{project.name}</p>
          </div>
        </div>

        <p className="text-xs text-slate-600 dark:text-gray-300 bg-red-50 dark:bg-red-500/10 rounded-xl px-3 py-2 border border-red-100 dark:border-red-500/20">
          Esta acción eliminará el proyecto y todas sus tareas permanentemente. No se puede deshacer.
        </p>

        <div className="space-y-1.5">
          <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">
            Confirma tu contraseña
          </label>
          <input
            ref={inputRef}
            type="password"
            value={pwd}
            onChange={e => { setPwd(e.target.value); setErr(''); }}
            onKeyDown={e => e.key === 'Enter' && confirm()}
            placeholder="••••••••"
            className="w-full px-3 py-2.5 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-900 dark:text-white placeholder-slate-300 dark:placeholder-gray-600 focus:outline-none focus:ring-2 focus:ring-red-500/40 focus:border-red-500 transition"
          />
          {err && <p className="text-xs text-red-500 font-medium">{err}</p>}
        </div>

        <div className="flex gap-2 pt-1">
          <button onClick={onCancel}
            className="flex-1 px-4 py-2.5 text-sm rounded-xl border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700 transition cursor-pointer">
            Cancelar
          </button>
          <button onClick={confirm} disabled={!pwd || busy}
            className="flex-1 px-4 py-2.5 text-sm font-medium rounded-xl bg-red-600 hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed text-white transition cursor-pointer">
            {busy ? 'Eliminando…' : 'Eliminar'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Main page ─────────────────────────────────────────────────────────────────
export default function ProjectsPage() {
  const [projects, setProjects]     = useState([]);
  const [loading, setLoading]       = useState(true);
  const [search, setSearch]         = useState('');
  const [statusF, setStatusF]       = useState('all');
  const [toast, setToast]           = useState(null);
  const [deleting, setDeleting]     = useState(null); // project to delete
  const location                    = useLocation();
  const { selectedProjectId, setSelectedProjectId } = useProject();

  const load = () => {
    projectsService.getAll()
      .then(d => setProjects(d.projects || []))
      .finally(() => setLoading(false));
  };

  useEffect(load, []);

  useEffect(() => {
    if (location.state?.imported) {
      setToast({ name: location.state.name, taskCount: location.state.taskCount });
      window.history.replaceState({}, '');
      const t = setTimeout(() => setToast(null), 6000);
      return () => clearTimeout(t);
    }
  }, [location.state]);

  const handleDeleted = (id) => {
    setDeleting(null);
    if (selectedProjectId === id) setSelectedProjectId(null);
    setProjects(prev => prev.filter(p => p.id !== id));
  };

  const filtered = projects.filter(p => {
    const q = search.toLowerCase();
    const matchQ = p.name.toLowerCase().includes(q) || p.code.toLowerCase().includes(q) || (p.client||'').toLowerCase().includes(q);
    const matchS = statusF === 'all' || p.status === statusF;
    return matchQ && matchS;
  });

  return (
    <div className="space-y-4 pb-6">
      {/* Toast importación */}
      {toast && (
        <div className="fixed top-5 right-5 z-50 flex items-start gap-3 bg-emerald-600 text-white px-5 py-4 rounded-2xl shadow-xl max-w-sm">
          <svg className="w-5 h-5 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
          <div>
            <p className="font-semibold text-sm">¡Proyecto creado desde anteproyecto!</p>
            <p className="text-xs text-emerald-100 mt-0.5">{toast.name} · {toast.taskCount} tareas generadas</p>
          </div>
          <button onClick={() => setToast(null)} className="ml-2 text-emerald-200 hover:text-white 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>
      )}

      {/* Toolbar */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex gap-2 flex-wrap">
          <div className="relative">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
            <input type="search" placeholder="Buscar proyecto, cliente…" value={search} onChange={e=>setSearch(e.target.value)}
              className="pl-9 pr-4 py-2 w-64 text-sm bg-white dark:bg-surface-800 border border-slate-200 dark:border-surface-700 rounded-xl text-slate-900 dark:text-white placeholder-slate-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500 transition"/>
          </div>
          <select value={statusF} onChange={e=>setStatusF(e.target.value)}
            className="text-sm bg-white dark:bg-surface-800 border border-slate-200 dark:border-surface-700 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-300 cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-500/40">
            <option value="all">Todos los estados</option>
            <option value="ACTIVO">Activo</option>
            <option value="EN_RIESGO">En riesgo</option>
            <option value="PAUSADO">Pausado</option>
            <option value="COMPLETADO">Completado</option>
          </select>
        </div>
        <Link to="/projects/new"
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-xl transition shadow-sm 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="M12 4v16m8-8H4"/>
          </svg>
          Nuevo proyecto
        </Link>
      </div>

      {!loading && (
        <p className="text-xs text-slate-400 dark:text-gray-500">
          {filtered.length} proyecto{filtered.length !== 1 ? 's' : ''}{statusF !== 'all' ? ` · ${statusF.replace('_',' ')}` : ''}
        </p>
      )}

      {/* List */}
      {loading ? (
        <div className="space-y-3">
          {[1,2,3].map(i=>(
            <div key={i} className="animate-pulse h-[88px] bg-white dark:bg-surface-800 rounded-2xl border border-slate-100 dark:border-surface-700"/>
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 text-slate-400 dark:text-gray-500">
          <svg className="w-10 h-10 mx-auto mb-3 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
          <p className="text-sm">No se encontraron proyectos</p>
        </div>
      ) : (
        <div className="space-y-2.5">
          {filtered.map(p => {
            const pct  = p.progressPct ?? 0;
            const bar  = pct >= 75 ? 'bg-emerald-500' : pct >= 40 ? 'bg-blue-500' : 'bg-amber-400';
            const isMock = MOCK_IDS.has(p.id);
            return (
              <div key={p.id} className="relative group">
                <Link to={`/projects/${p.id}`}
                  className="flex items-center gap-4 bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 hover:border-slate-300 dark:hover:border-surface-600 hover:shadow-md transition-all p-4 cursor-pointer pr-12">
                  <div className={`w-2.5 h-2.5 rounded-full flex-shrink-0 ${RAG_DOT[p.ragStatus] || 'bg-slate-400'}`}/>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1 flex-wrap">
                      <span className="text-xs font-mono text-slate-400 dark:text-gray-500">{p.code}</span>
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${STATUS_COLORS[p.status] || STATUS_COLORS.ACTIVO}`}>
                        {(p.status||'').replace('_',' ')}
                      </span>
                      {p.methodology && <span className="text-xs text-slate-400 dark:text-gray-500">{p.methodology}</span>}
                    </div>
                    <h3 className="text-sm font-semibold text-slate-900 dark:text-white truncate group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">{p.name}</h3>
                    {p.client && <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5 truncate">{p.client}</p>}
                  </div>
                  <div className="w-36 flex-shrink-0 hidden sm:block">
                    <div className="flex justify-between text-xs mb-1.5">
                      <span className="text-slate-400 dark:text-gray-500">Avance</span>
                      <span className="font-semibold text-slate-700 dark:text-white tabular-nums">{pct}%</span>
                    </div>
                    <div className="h-1.5 bg-slate-100 dark:bg-surface-600 rounded-full overflow-hidden">
                      <div className={`h-full rounded-full ${bar}`} style={{width:`${pct}%`}}/>
                    </div>
                  </div>
                  <svg className="w-4 h-4 text-slate-300 dark:text-gray-600 group-hover:text-blue-500 transition-colors flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"/>
                  </svg>
                </Link>

                {/* Delete button — only for non-mock projects */}
                {!isMock && (
                  <button
                    onClick={e => { e.preventDefault(); setDeleting(p); }}
                    title="Eliminar proyecto"
                    className="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 flex items-center justify-center rounded-lg text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-500/10 transition opacity-0 group-hover:opacity-100 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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                  </button>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Delete modal */}
      {deleting && (
        <DeleteModal
          project={deleting}
          onCancel={() => setDeleting(null)}
          onDeleted={handleDeleted}
        />
      )}
    </div>
  );
}
