import { useState, useMemo, useEffect } from 'react';
import { useProject } from '../../context/ProjectContext';

// ─── Mock Data ───────────────────────────────────────────────────────────────

const CLOSURE_PROJECTS = [
  {
    id: 'cp1',
    projectId: 'p4',
    code: 'PRY-2026-004',
    name: 'Construcción AR-ProjectManagement Norte',
    client: 'Inmobiliaria Del Valle',
    type: 'Construcción',
    completion: 72,
    status: 'EN_PROCESO_CIERRE',
    closureStartDate: '2026-06-01',
    estimatedCloseDate: '2026-07-15',
  },
  {
    id: 'cp2',
    projectId: 'p4',
    code: 'PRY-2026-004',
    name: 'AR-ProjectManagement "Horizontes"',
    client: 'Sony Music Latin',
    type: 'Producción Musical',
    completion: 45,
    status: 'INICIANDO_CIERRE',
    closureStartDate: '2026-06-10',
    estimatedCloseDate: '2026-07-30',
  },
  {
    id: 'cp3',
    projectId: 'p4',
    code: 'PRY-2026-004',
    name: 'Implementación AR-ProjectManagement',
    client: 'Grupo Empresarial XYZ',
    type: 'Tecnología',
    completion: 98,
    status: 'PENDIENTE_FIRMA',
    closureStartDate: '2026-05-20',
    estimatedCloseDate: '2026-06-30',
  },
];

const CLOSED_PROJECTS = [
  {
    id: 'cl1',
    projectId: 'p4',
    code: 'PRY-2026-004',
    name: 'AR-ProjectManagement — Plataforma ERP',
    client: 'AR Electronics',
    type: 'Software',
    closureDate: '2026-05-15',
    budgetPlanned: 180000,
    budgetActual: 174500,
    satisfactionScore: 5,
    duration: '8 meses',
    pmName: 'Carlos Mendoza',
    deliverables: [
      'Módulos de gestión completados',
      'Documentación técnica entregada',
      'Capacitación al equipo cliente',
      'Soporte post-implementación activado',
    ],
    notes: 'Proyecto concluido exitosamente. Cliente muy satisfecho con los resultados.',
  },
];

const CHECKLIST_TEMPLATE = [
  {
    section: 'Entregables',
    icon: '📦',
    items: [
      { id: 'e1', label: 'Todos los entregables aprobados por el cliente', role: 'Gerente de Proyecto' },
      { id: 'e2', label: 'Actas de recepción firmadas', role: 'Director' },
      { id: 'e3', label: 'Manuales de usuario entregados', role: 'Líder Técnico' },
      { id: 'e4', label: 'Capacitación al equipo cliente completada', role: 'Gerente de Proyecto' },
    ],
  },
  {
    section: 'Financiero',
    icon: '💰',
    items: [
      { id: 'f1', label: 'Todas las facturas emitidas y pagadas', role: 'Administrador' },
      { id: 'f2', label: 'Retenciones liberadas', role: 'Administrador' },
      { id: 'f3', label: 'Liquidación final aprobada', role: 'Director' },
      { id: 'f4', label: 'Conciliación bancaria completada', role: 'Administrador' },
    ],
  },
  {
    section: 'Contratos',
    icon: '📋',
    items: [
      { id: 'c1', label: 'Contratos formalmente cerrados', role: 'Legal' },
      { id: 'c2', label: 'Garantías activas registradas', role: 'Legal' },
      { id: 'c3', label: 'Finiquitos firmados con proveedores', role: 'Administrador' },
      { id: 'c4', label: 'Pólizas de seguro canceladas', role: 'Legal' },
    ],
  },
  {
    section: 'Documentación',
    icon: '📁',
    items: [
      { id: 'd1', label: 'Expediente técnico completo', role: 'Líder Técnico' },
      { id: 'd2', label: 'Planos as-built entregados', role: 'Líder Técnico' },
      { id: 'd3', label: 'Documentación archivada en repositorio', role: 'Gerente de Proyecto' },
      { id: 'd4', label: 'Lecciones aprendidas documentadas', role: 'Gerente de Proyecto' },
    ],
  },
  {
    section: 'Administrativo',
    icon: '🏢',
    items: [
      { id: 'a1', label: 'Equipo desmovilizado y reasignado', role: 'RRHH' },
      { id: 'a2', label: 'Permisos y licencias devueltos', role: 'Administrador' },
      { id: 'a3', label: 'Evaluación de desempeño del equipo completada', role: 'Gerente de Proyecto' },
      { id: 'a4', label: 'Activos y equipos devueltos o transferidos', role: 'Logística' },
      { id: 'a5', label: 'Oficinas y espacios desocupados', role: 'Administrador' },
    ],
  },
];

// Initial checklist states per project
const INITIAL_CHECKLIST_STATES = {
  cp1: {
    e1: { checked: true, notes: 'Aprobado en reunión del 10/06' },
    e2: { checked: true, notes: '' },
    e3: { checked: false, notes: '' },
    e4: { checked: false, notes: '' },
    f1: { checked: true, notes: 'Facturas 001-005 pagadas' },
    f2: { checked: false, notes: '' },
    f3: { checked: false, notes: '' },
    f4: { checked: false, notes: '' },
    c1: { checked: true, notes: '' },
    c2: { checked: false, notes: '' },
    c3: { checked: false, notes: '' },
    c4: { checked: false, notes: '' },
    d1: { checked: true, notes: '' },
    d2: { checked: false, notes: '' },
    d3: { checked: false, notes: '' },
    d4: { checked: false, notes: '' },
    a1: { checked: false, notes: '' },
    a2: { checked: false, notes: '' },
    a3: { checked: false, notes: '' },
    a4: { checked: false, notes: '' },
    a5: { checked: false, notes: '' },
  },
  cp2: {
    e1: { checked: true, notes: 'Máster aprobado' },
    e2: { checked: false, notes: '' },
    e3: { checked: false, notes: '' },
    e4: { checked: false, notes: '' },
    f1: { checked: false, notes: '' },
    f2: { checked: false, notes: '' },
    f3: { checked: false, notes: '' },
    f4: { checked: false, notes: '' },
    c1: { checked: false, notes: '' },
    c2: { checked: false, notes: '' },
    c3: { checked: false, notes: '' },
    c4: { checked: false, notes: '' },
    d1: { checked: false, notes: '' },
    d2: { checked: false, notes: '' },
    d3: { checked: false, notes: '' },
    d4: { checked: false, notes: '' },
    a1: { checked: false, notes: '' },
    a2: { checked: false, notes: '' },
    a3: { checked: false, notes: '' },
    a4: { checked: false, notes: '' },
    a5: { checked: false, notes: '' },
  },
  cp3: {
    e1: { checked: true, notes: 'Sistema ERP aprobado' },
    e2: { checked: true, notes: '' },
    e3: { checked: true, notes: 'Manuales v2.1 entregados' },
    e4: { checked: true, notes: '' },
    f1: { checked: true, notes: '' },
    f2: { checked: true, notes: '' },
    f3: { checked: true, notes: '' },
    f4: { checked: true, notes: '' },
    c1: { checked: true, notes: '' },
    c2: { checked: true, notes: '' },
    c3: { checked: true, notes: '' },
    c4: { checked: true, notes: '' },
    d1: { checked: true, notes: '' },
    d2: { checked: true, notes: '' },
    d3: { checked: true, notes: '' },
    d4: { checked: true, notes: 'Lecciones documentadas en Confluence' },
    a1: { checked: true, notes: '' },
    a2: { checked: true, notes: '' },
    a3: { checked: true, notes: '' },
    a4: { checked: true, notes: '' },
    a5: { checked: false, notes: 'Pendiente devolución llaves' },
  },
};

// ─── Helpers ─────────────────────────────────────────────────────────────────

const STATUS_CONFIG = {
  INICIANDO_CIERRE: { label: 'Iniciando Cierre', color: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400' },
  EN_PROCESO_CIERRE: { label: 'En Proceso', color: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400' },
  PENDIENTE_FIRMA: { label: 'Pendiente Firma', color: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400' },
  CERRADO: { label: 'Cerrado', color: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400' },
};

function getChecklistProgress(state) {
  const allItems = CHECKLIST_TEMPLATE.flatMap(s => s.items);
  const total = allItems.length;
  const done = allItems.filter(item => state?.[item.id]?.checked).length;
  return { done, total, pct: total > 0 ? Math.round((done / total) * 100) : 0 };
}

function StarRating({ score }) {
  return (
    <div className="flex gap-0.5">
      {[1, 2, 3, 4, 5].map(s => (
        <span key={s} className={s <= score ? 'text-amber-400' : 'text-slate-300 dark:text-slate-600'}>★</span>
      ))}
    </div>
  );
}

function ProgressBar({ pct, size = 'md' }) {
  const h = size === 'sm' ? 'h-1.5' : 'h-2.5';
  const color = pct === 100 ? 'bg-green-500' : pct >= 60 ? 'bg-blue-500' : 'bg-amber-500';
  return (
    <div className={`w-full bg-slate-200 dark:bg-slate-700 rounded-full ${h}`}>
      <div
        className={`${h} rounded-full ${color} transition-all duration-500`}
        style={{ width: `${pct}%` }}
      />
    </div>
  );
}

// ─── Tab 1: Proyectos en Cierre ───────────────────────────────────────────────

function ClosureProjectsTab({ onSelectProject, selectedProjectId }) {
  const { selectedProjectId: globalFilter } = useProject();

  const filtered = useMemo(() => {
    if (!globalFilter) return CLOSURE_PROJECTS;
    return CLOSURE_PROJECTS.filter(p => p.projectId === globalFilter);
  }, [globalFilter]);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Proyectos en Proceso de Cierre</h2>
          <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">{filtered.length} proyecto(s) en cierre activo</p>
        </div>
      </div>

      {filtered.length === 0 && (
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-12 text-center">
          <div className="text-4xl mb-3">📂</div>
          <p className="text-slate-500 dark:text-slate-400">No hay proyectos en cierre para el filtro seleccionado.</p>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
        {filtered.map(project => {
          const checklistState = INITIAL_CHECKLIST_STATES[project.id] || {};
          const { done, total, pct } = getChecklistProgress(checklistState);
          const statusCfg = STATUS_CONFIG[project.status];
          const isSelected = selectedProjectId === project.id;

          return (
            <div
              key={project.id}
              className={`bg-white dark:bg-slate-900 rounded-2xl border transition-all ${
                isSelected
                  ? 'border-blue-500 ring-2 ring-blue-500/20'
                  : 'border-slate-200 dark:border-slate-700 hover:border-slate-300 dark:hover:border-slate-600'
              }`}
            >
              <div className="p-5">
                <div className="flex items-start justify-between gap-3 mb-3">
                  <div className="min-w-0">
                    <p className="text-xs font-mono text-slate-400 dark:text-slate-500 mb-1">{project.code}</p>
                    <h3 className="text-sm font-semibold text-slate-900 dark:text-white leading-snug">{project.name}</h3>
                    <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{project.client}</p>
                  </div>
                  <span className={`shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium ${statusCfg.color}`}>
                    {statusCfg.label}
                  </span>
                </div>

                <div className="flex items-center gap-2 mb-1 mt-4">
                  <span className="text-xs text-slate-500 dark:text-slate-400">Checklist</span>
                  <span className="text-xs font-semibold text-slate-700 dark:text-slate-300 ml-auto">{done}/{total} items</span>
                  <span className="text-xs font-bold text-slate-900 dark:text-white">{pct}%</span>
                </div>
                <ProgressBar pct={pct} size="sm" />

                <div className="flex items-center gap-2 mb-4 mt-3">
                  <span className="text-xs text-slate-500 dark:text-slate-400">Avance general</span>
                  <span className="text-xs font-bold text-slate-900 dark:text-white ml-auto">{project.completion}%</span>
                </div>
                <ProgressBar pct={project.completion} size="sm" />

                <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800 flex items-center justify-between">
                  <div className="text-xs text-slate-500 dark:text-slate-400">
                    <span>Cierre est. </span>
                    <span className="font-medium text-slate-700 dark:text-slate-300">{project.estimatedCloseDate}</span>
                  </div>
                  <button
                    onClick={() => onSelectProject(project.id)}
                    className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2 text-xs font-medium transition-colors"
                  >
                    Gestionar Cierre
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Tab 2: Checklist ────────────────────────────────────────────────────────

function ChecklistTab({ selectedClosureProjectId, onGenerateActa }) {
  const [checklistStates, setChecklistStates] = useState(() => {
    const initial = {};
    Object.keys(INITIAL_CHECKLIST_STATES).forEach(key => {
      initial[key] = {};
      Object.keys(INITIAL_CHECKLIST_STATES[key]).forEach(itemId => {
        initial[key][itemId] = { ...INITIAL_CHECKLIST_STATES[key][itemId] };
      });
    });
    return initial;
  });
  const [expandedNotes, setExpandedNotes] = useState({});

  const project = CLOSURE_PROJECTS.find(p => p.id === selectedClosureProjectId);

  const currentState = useMemo(() => {
    if (!selectedClosureProjectId) return {};
    return checklistStates[selectedClosureProjectId] || {};
  }, [checklistStates, selectedClosureProjectId]);

  const progress = useMemo(() => getChecklistProgress(currentState), [currentState]);

  const toggleItem = (itemId) => {
    setChecklistStates(prev => ({
      ...prev,
      [selectedClosureProjectId]: {
        ...prev[selectedClosureProjectId],
        [itemId]: {
          ...prev[selectedClosureProjectId]?.[itemId],
          checked: !prev[selectedClosureProjectId]?.[itemId]?.checked,
        },
      },
    }));
  };

  const updateNote = (itemId, value) => {
    setChecklistStates(prev => ({
      ...prev,
      [selectedClosureProjectId]: {
        ...prev[selectedClosureProjectId],
        [itemId]: {
          ...prev[selectedClosureProjectId]?.[itemId],
          notes: value,
        },
      },
    }));
  };

  const toggleNoteExpand = (itemId) => {
    setExpandedNotes(prev => ({ ...prev, [itemId]: !prev[itemId] }));
  };

  if (!selectedClosureProjectId || !project) {
    return (
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-12 text-center">
        <div className="text-4xl mb-3">☑️</div>
        <p className="text-slate-700 dark:text-slate-300 font-medium mb-1">Selecciona un proyecto</p>
        <p className="text-slate-500 dark:text-slate-400 text-sm">Ve a la pestaña "Proyectos en Cierre" y haz clic en "Gestionar Cierre".</p>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <p className="text-xs font-mono text-slate-400 dark:text-slate-500">{project.code}</p>
            <h2 className="text-base font-semibold text-slate-900 dark:text-white mt-0.5">{project.name}</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400">{project.client}</p>
          </div>
          <button
            onClick={onGenerateActa}
            disabled={progress.pct < 100}
            className={`shrink-0 rounded-xl px-5 py-2.5 text-sm font-medium transition-all ${
              progress.pct === 100
                ? 'bg-green-600 hover:bg-green-700 text-white cursor-pointer'
                : 'bg-slate-100 dark:bg-slate-800 text-slate-400 dark:text-slate-600 cursor-not-allowed'
            }`}
          >
            {progress.pct === 100 ? '✅ Generar Acta de Cierre' : `⏳ Generar Acta (${progress.pct}% completado)`}
          </button>
        </div>

        <div className="mt-4">
          <div className="flex items-center justify-between text-sm mb-2">
            <span className="text-slate-600 dark:text-slate-300 font-medium">Progreso del checklist</span>
            <span className="font-bold text-slate-900 dark:text-white">{progress.done}/{progress.total} — {progress.pct}%</span>
          </div>
          <ProgressBar pct={progress.pct} />
        </div>
      </div>

      {/* Sections */}
      {CHECKLIST_TEMPLATE.map(section => {
        const sectionItems = section.items;
        const doneSec = sectionItems.filter(i => currentState[i.id]?.checked).length;
        return (
          <div key={section.section} className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
            <div className="flex items-center justify-between px-5 py-3.5 bg-slate-50 dark:bg-slate-800/60 border-b border-slate-200 dark:border-slate-700">
              <div className="flex items-center gap-2">
                <span>{section.icon}</span>
                <span className="text-sm font-semibold text-slate-900 dark:text-white">{section.section}</span>
              </div>
              <span className="text-xs text-slate-500 dark:text-slate-400">{doneSec}/{sectionItems.length}</span>
            </div>
            <div className="divide-y divide-slate-100 dark:divide-slate-800">
              {sectionItems.map(item => {
                const state = currentState[item.id] || { checked: false, notes: '' };
                const noteOpen = expandedNotes[item.id];
                return (
                  <div key={item.id} className="px-5 py-3.5">
                    <div className="flex items-start gap-3">
                      <button
                        onClick={() => toggleItem(item.id)}
                        className={`mt-0.5 w-5 h-5 shrink-0 rounded border-2 flex items-center justify-center transition-colors ${
                          state.checked
                            ? 'bg-green-500 border-green-500 text-white'
                            : 'border-slate-300 dark:border-slate-600 hover:border-green-400'
                        }`}
                      >
                        {state.checked && (
                          <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                          </svg>
                        )}
                      </button>
                      <div className="flex-1 min-w-0">
                        <p className={`text-sm leading-snug ${state.checked ? 'line-through text-slate-400 dark:text-slate-600' : 'text-slate-800 dark:text-slate-200'}`}>
                          {item.label}
                        </p>
                        <div className="flex items-center gap-3 mt-1">
                          <span className="text-xs text-slate-400 dark:text-slate-500">Responsable: <span className="font-medium text-slate-600 dark:text-slate-400">{item.role}</span></span>
                          <button
                            onClick={() => toggleNoteExpand(item.id)}
                            className="text-xs text-blue-500 hover:text-blue-700 transition-colors"
                          >
                            {noteOpen ? 'Ocultar nota' : state.notes ? '📝 Ver nota' : '+ Agregar nota'}
                          </button>
                        </div>
                        {noteOpen && (
                          <textarea
                            value={state.notes}
                            onChange={e => updateNote(item.id, e.target.value)}
                            placeholder="Agregar notas u observaciones..."
                            rows={2}
                            className="mt-2 w-full text-xs rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-700 dark:text-slate-300 placeholder-slate-400 p-2 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500/40"
                          />
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Tab 3: Acta de Cierre ────────────────────────────────────────────────────

function ActaCierreTab({ selectedClosureProjectId }) {
  const [signatures, setSignatures] = useState({ pm: false, director: false, client: false });
  const [showSuccess, setShowSuccess] = useState(false);

  const project = CLOSURE_PROJECTS.find(p => p.id === selectedClosureProjectId);

  const sign = (role) => {
    const next = { ...signatures, [role]: true };
    setSignatures(next);
    if (next.pm && next.director && next.client) {
      setShowSuccess(true);
    }
  };

  const allSigned = signatures.pm && signatures.director && signatures.client;

  if (!selectedClosureProjectId || !project) {
    return (
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-12 text-center">
        <div className="text-4xl mb-3">📄</div>
        <p className="text-slate-700 dark:text-slate-300 font-medium mb-1">Acta no disponible</p>
        <p className="text-slate-500 dark:text-slate-400 text-sm">Completa el checklist de cierre y genera el acta desde la pestaña anterior.</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {showSuccess && (
        <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-2xl p-4 flex items-center gap-3">
          <span className="text-2xl">🎉</span>
          <div>
            <p className="text-sm font-semibold text-green-800 dark:text-green-300">¡Proyecto cerrado oficialmente!</p>
            <p className="text-xs text-green-700 dark:text-green-400 mt-0.5">Todas las firmas han sido obtenidas. El proyecto ha sido marcado como CERRADO.</p>
          </div>
        </div>
      )}

      {/* Acta document */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
        {/* Header */}
        <div className="bg-slate-800 dark:bg-slate-950 px-8 py-6 text-center">
          <div className="text-white text-xs font-mono tracking-widest uppercase mb-2 opacity-60">AR Electronics — Project Management</div>
          <h2 className="text-white text-xl font-bold tracking-tight">ACTA DE CIERRE DE PROYECTO</h2>
          <p className="text-slate-300 text-sm mt-1 opacity-80">Documento Oficial — Registro Nº ACT-2026-{project.id.toUpperCase()}</p>
        </div>

        <div className="p-8 space-y-6">
          {/* Project info */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-3">
            {[
              ['Proyecto', project.name],
              ['Código', project.code],
              ['Cliente', project.client],
              ['Tipo', project.type],
              ['Fecha de Inicio de Cierre', project.closureStartDate],
              ['Fecha Estimada de Cierre', project.estimatedCloseDate],
              ['Estado', STATUS_CONFIG[project.status]?.label],
              ['Fecha del Acta', new Date().toISOString().split('T')[0]],
            ].map(([label, value]) => (
              <div key={label} className="flex flex-col">
                <span className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider">{label}</span>
                <span className="text-sm text-slate-800 dark:text-slate-200 font-medium mt-0.5">{value}</span>
              </div>
            ))}
          </div>

          <hr className="border-slate-200 dark:border-slate-700" />

          {/* Entregables summary */}
          <div>
            <h3 className="text-sm font-semibold text-slate-900 dark:text-white mb-3">Resumen de Entregables</h3>
            <ul className="space-y-1.5">
              {['Entregables técnicos aprobados por el cliente', 'Actas de recepción formalizadas', 'Documentación técnica completa entregada', 'Capacitaciones realizadas al equipo cliente', 'Cierre financiero y liquidación aprobados'].map(item => (
                <li key={item} className="flex items-start gap-2 text-sm text-slate-600 dark:text-slate-400">
                  <span className="text-green-500 font-bold mt-0.5">✓</span>
                  <span>{item}</span>
                </li>
              ))}
            </ul>
          </div>

          <hr className="border-slate-200 dark:border-slate-700" />

          {/* Declaración */}
          <div className="bg-slate-50 dark:bg-slate-800/50 rounded-xl p-4 text-xs text-slate-600 dark:text-slate-400 leading-relaxed">
            Los abajo firmantes declaran que el proyecto <strong className="text-slate-800 dark:text-slate-200">"{project.name}"</strong> ha cumplido con todos los
            objetivos, entregables y criterios de aceptación establecidos en el contrato y en el plan de proyecto.
            Así mismo, se confirma el cierre formal de todas las obligaciones contractuales, financieras y administrativas
            asociadas al presente proyecto, dando por concluida la relación contractual entre las partes.
          </div>

          <hr className="border-slate-200 dark:border-slate-700" />

          {/* Signatures */}
          <div>
            <h3 className="text-sm font-semibold text-slate-900 dark:text-white mb-4">Firmas de Cierre</h3>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {[
                { key: 'pm', role: 'Gerente de Proyecto', name: 'Carlos Mendoza' },
                { key: 'director', role: 'Director General', name: 'María González' },
                { key: 'client', role: 'Cliente', name: project.client },
              ].map(sig => {
                const signed = signatures[sig.key];
                return (
                  <div
                    key={sig.key}
                    className={`rounded-xl border-2 p-4 flex flex-col items-center text-center transition-all ${
                      signed
                        ? 'border-green-300 dark:border-green-700 bg-green-50 dark:bg-green-900/10'
                        : 'border-dashed border-slate-300 dark:border-slate-700'
                    }`}
                  >
                    {signed ? (
                      <>
                        <div className="text-2xl mb-2">✅</div>
                        <p className="text-xs font-bold text-green-700 dark:text-green-400 mb-1">FIRMADO</p>
                        <p className="text-xs font-semibold text-slate-800 dark:text-slate-200">{sig.name}</p>
                        <p className="text-xs text-slate-500 dark:text-slate-400">{sig.role}</p>
                        <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">{new Date().toLocaleDateString('es-ES')}</p>
                      </>
                    ) : (
                      <>
                        <div className="w-12 h-12 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2">
                          <span className="text-xl">✍️</span>
                        </div>
                        <p className="text-xs font-semibold text-slate-700 dark:text-slate-300 mb-0.5">{sig.name}</p>
                        <p className="text-xs text-slate-500 dark:text-slate-400 mb-3">{sig.role}</p>
                        <button
                          onClick={() => sign(sig.key)}
                          className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-1.5 text-xs font-medium transition-colors"
                        >
                          Firmar
                        </button>
                      </>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {allSigned && (
            <div className="text-center pt-2">
              <span className="inline-flex items-center gap-2 bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 rounded-full px-5 py-2 text-sm font-semibold">
                <span>🏆</span> Acta de Cierre Completamente Firmada
              </span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Tab 4: Proyectos Cerrados ────────────────────────────────────────────────

function ClosedProjectsTab() {
  const { selectedProjectId: globalFilter } = useProject();
  const [expedienteProject, setExpedienteProject] = useState(null);

  const filtered = useMemo(() => {
    if (!globalFilter) return CLOSED_PROJECTS;
    return CLOSED_PROJECTS.filter(p => p.projectId === globalFilter);
  }, [globalFilter]);

  const formatCurrency = (n) => new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }).format(n);

  const variance = (planned, actual) => {
    const diff = planned - actual;
    const pct = ((diff / planned) * 100).toFixed(1);
    return { diff, pct, saved: diff >= 0 };
  };

  return (
    <div className="space-y-4">
      {/* Warning banner */}
      <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl px-4 py-3 flex items-center gap-2">
        <span className="text-amber-500">⚠️</span>
        <p className="text-sm text-amber-800 dark:text-amber-300 font-medium">Los proyectos cerrados son de solo lectura. No se pueden realizar modificaciones.</p>
      </div>

      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100 dark:border-slate-800 flex items-center justify-between">
          <h2 className="text-sm font-semibold text-slate-900 dark:text-white">Archivo de Proyectos Cerrados</h2>
          <span className="text-xs text-slate-500 dark:text-slate-400">{filtered.length} registro(s)</span>
        </div>

        {filtered.length === 0 ? (
          <div className="p-12 text-center">
            <div className="text-4xl mb-3">🗄️</div>
            <p className="text-slate-500 dark:text-slate-400 text-sm">No hay proyectos cerrados para el filtro seleccionado.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-slate-50 dark:bg-slate-800/60">
                  {['Proyecto / Cliente', 'Fecha Cierre', 'Presupuesto Planif.', 'Costo Real', 'Variación', 'Satisfacción', 'Acciones'].map(h => (
                    <th key={h} className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-slate-400 whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                {filtered.map(proj => {
                  const { diff, pct, saved } = variance(proj.budgetPlanned, proj.budgetActual);
                  return (
                    <tr key={proj.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-colors">
                      <td className="px-4 py-3">
                        <p className="font-semibold text-slate-900 dark:text-white">{proj.name}</p>
                        <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{proj.client} · {proj.code}</p>
                      </td>
                      <td className="px-4 py-3 whitespace-nowrap text-slate-700 dark:text-slate-300">{proj.closureDate}</td>
                      <td className="px-4 py-3 whitespace-nowrap text-slate-700 dark:text-slate-300 font-mono text-xs">{formatCurrency(proj.budgetPlanned)}</td>
                      <td className="px-4 py-3 whitespace-nowrap text-slate-700 dark:text-slate-300 font-mono text-xs">{formatCurrency(proj.budgetActual)}</td>
                      <td className="px-4 py-3 whitespace-nowrap">
                        <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${saved ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400' : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'}`}>
                          {saved ? '▼' : '▲'} {formatCurrency(Math.abs(diff))} ({Math.abs(pct)}%)
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <StarRating score={proj.satisfactionScore} />
                      </td>
                      <td className="px-4 py-3">
                        <button
                          onClick={() => setExpedienteProject(proj)}
                          className="bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-xl px-3 py-1.5 text-xs font-medium transition-colors whitespace-nowrap"
                        >
                          Ver Expediente
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Expediente Modal */}
      {expedienteProject && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={() => setExpedienteProject(null)} />
          <div className="relative bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-lg max-h-[80vh] overflow-y-auto shadow-2xl">
            <div className="sticky top-0 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-700 px-6 py-4 flex items-center justify-between">
              <div>
                <h3 className="text-base font-semibold text-slate-900 dark:text-white">Expediente de Cierre</h3>
                <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Solo lectura</p>
              </div>
              <button onClick={() => setExpedienteProject(null)} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-xl leading-none transition-colors">&times;</button>
            </div>
            <div className="p-6 space-y-5">
              <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl px-4 py-2.5 text-xs text-amber-700 dark:text-amber-400 font-medium">
                🔒 Expediente en modo de solo lectura
              </div>
              <div className="grid grid-cols-2 gap-4">
                {[
                  ['Proyecto', expedienteProject.name],
                  ['Código', expedienteProject.code],
                  ['Cliente', expedienteProject.client],
                  ['Tipo', expedienteProject.type],
                  ['Fecha de Cierre', expedienteProject.closureDate],
                  ['Duración', expedienteProject.duration],
                  ['Gerente de Proyecto', expedienteProject.pmName],
                  ['Satisfacción Cliente', `${'★'.repeat(expedienteProject.satisfactionScore)}${'☆'.repeat(5 - expedienteProject.satisfactionScore)}`],
                ].map(([label, value]) => (
                  <div key={label}>
                    <span className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider block">{label}</span>
                    <span className="text-sm text-slate-800 dark:text-slate-200 font-medium mt-0.5 block">{value}</span>
                  </div>
                ))}
              </div>
              <div>
                <span className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider block mb-2">Entregables Principales</span>
                <ul className="space-y-1.5">
                  {expedienteProject.deliverables.map(d => (
                    <li key={d} className="flex items-start gap-2 text-sm text-slate-600 dark:text-slate-400">
                      <span className="text-green-500 font-bold">✓</span> {d}
                    </li>
                  ))}
                </ul>
              </div>
              <div>
                <span className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider block mb-2">Resumen Financiero</span>
                <div className="grid grid-cols-3 gap-3">
                  {[
                    ['Presupuesto', new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }).format(expedienteProject.budgetPlanned)],
                    ['Costo Real', new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }).format(expedienteProject.budgetActual)],
                    ['Ahorro', new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }).format(expedienteProject.budgetPlanned - expedienteProject.budgetActual)],
                  ].map(([label, value]) => (
                    <div key={label} className="bg-slate-50 dark:bg-slate-800 rounded-xl p-3 text-center">
                      <p className="text-xs text-slate-500 dark:text-slate-400">{label}</p>
                      <p className="text-sm font-bold text-slate-900 dark:text-white mt-1">{value}</p>
                    </div>
                  ))}
                </div>
              </div>
              {expedienteProject.notes && (
                <div>
                  <span className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider block mb-2">Notas de Cierre</span>
                  <p className="text-sm text-slate-600 dark:text-slate-400 bg-slate-50 dark:bg-slate-800 rounded-xl p-3">{expedienteProject.notes}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

const TABS = [
  { id: 'projects', label: 'Proyectos en Cierre', icon: '🔄' },
  { id: 'checklist', label: 'Checklist de Cierre', icon: '☑️' },
  { id: 'acta', label: 'Acta de Cierre', icon: '📄' },
  { id: 'closed', label: 'Proyectos Cerrados', icon: '🗄️' },
];

export default function ProjectClosurePage() {
  const { selectedProjectId: globalProjectId } = useProject();
  const [activeTab, setActiveTab] = useState('projects');
  const [selectedClosureProjectId, setSelectedClosureProjectId] = useState(null);

  // Sync local closure project selection with the global navbar filter
  useEffect(() => {
    if (globalProjectId) {
      const match = CLOSURE_PROJECTS.find(p => p.projectId === globalProjectId);
      setSelectedClosureProjectId(match ? match.id : null);
    }
  }, [globalProjectId]);

  const handleSelectProject = (id) => {
    setSelectedClosureProjectId(id);
    setActiveTab('checklist');
  };

  const handleGenerateActa = () => {
    setActiveTab('acta');
  };

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      {/* Page header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Cierre de Proyecto</h1>
        <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">Gestión del proceso formal de cierre, checklist y actas de entrega</p>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
        {[
          { label: 'En Proceso', value: CLOSURE_PROJECTS.filter(p => p.status === 'EN_PROCESO_CIERRE').length, color: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-900/20' },
          { label: 'Iniciando Cierre', value: CLOSURE_PROJECTS.filter(p => p.status === 'INICIANDO_CIERRE').length, color: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-50 dark:bg-amber-900/20' },
          { label: 'Pendiente Firma', value: CLOSURE_PROJECTS.filter(p => p.status === 'PENDIENTE_FIRMA').length, color: 'text-purple-600 dark:text-purple-400', bg: 'bg-purple-50 dark:bg-purple-900/20' },
          { label: 'Cerrados', value: CLOSED_PROJECTS.length, color: 'text-green-600 dark:text-green-400', bg: 'bg-green-50 dark:bg-green-900/20' },
        ].map(stat => (
          <div key={stat.label} className={`${stat.bg} rounded-2xl p-4`}>
            <p className={`text-2xl font-bold ${stat.color}`}>{stat.value}</p>
            <p className="text-xs text-slate-600 dark:text-slate-400 mt-0.5">{stat.label}</p>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 mb-5 overflow-hidden">
        <div className="flex overflow-x-auto scrollbar-hide">
          {TABS.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-5 py-4 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-blue-600 text-blue-600 dark:text-blue-400 bg-blue-50/50 dark:bg-blue-900/10'
                  : 'border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800/40'
              }`}
            >
              <span>{tab.icon}</span>
              <span>{tab.label}</span>
              {tab.id === 'checklist' && selectedClosureProjectId && (
                <span className="bg-blue-600 text-white rounded-full w-4 h-4 text-xs flex items-center justify-center font-bold">1</span>
              )}
            </button>
          ))}
        </div>
      </div>

      {/* Tab content */}
      {activeTab === 'projects' && (
        <ClosureProjectsTab
          onSelectProject={handleSelectProject}
          selectedProjectId={selectedClosureProjectId}
        />
      )}
      {activeTab === 'checklist' && (
        <ChecklistTab
          selectedClosureProjectId={selectedClosureProjectId}
          onGenerateActa={handleGenerateActa}
        />
      )}
      {activeTab === 'acta' && (
        <ActaCierreTab selectedClosureProjectId={selectedClosureProjectId} />
      )}
      {activeTab === 'closed' && <ClosedProjectsTab />}
    </div>
  );
}
