import { useState, useMemo, useRef } from 'react';
import { useProject } from '../../context/ProjectContext';
import { MOCK_PROJECTS } from '../../services/mockData';

// Map project id → display label (built from MOCK_PROJECTS so it's always in sync)
const PROJECT_LABEL = Object.fromEntries(
  MOCK_PROJECTS.map(p => [p.id, `${p.code} — ${p.name}`])
);
const PROJECT_CODE_LABEL = Object.fromEntries(
  MOCK_PROJECTS.map(p => [p.id, p.code])
);

// ─── Mock Data ────────────────────────────────────────────────────────────────
// projectId matches MOCK_PROJECTS ids: p1, p2, p3, p4
const MOCK_DOCS_INITIAL = [
  { id:'doc1',  code:'PLN-001', name:'Planta arquitectónica piso 1',              type:'PLANO',         format:'PDF',  version:'Rev.3',
    projectId:'p4', discipline:'Arquitectura',  taskRef:'TSK-001', taskName:'Diseño arquitectónico piso 1',
    uploadedBy:'Álvaro Romero',  uploadedAt:'2026-05-10', size:'4.2 MB', status:'VIGENTE',
    description:'Planta nivel +0.00 con distribución definitiva aprobada por cliente' },
  { id:'doc2',  code:'PLN-002', name:'Planta estructural fundaciones',             type:'PLANO',         format:'PDF',  version:'Rev.2',
    projectId:'p4', discipline:'Estructural',   taskRef:'TSK-003', taskName:'Cimentación bloque A',
    uploadedBy:'Álvaro Romero',  uploadedAt:'2026-04-22', size:'6.8 MB', status:'VIGENTE',    description:'' },
  { id:'doc3',  code:'ESP-001', name:'Especificaciones técnicas generales',        type:'ESPECIFICACION', format:'DOCX', version:'Rev.1',
    projectId:'p4', discipline:'General',       taskRef:null,      taskName:null,
    uploadedBy:'Paula Soto',    uploadedAt:'2026-03-05', size:'1.1 MB', status:'VIGENTE',    description:'' },
  { id:'doc4',  code:'RFI-001', name:'RFI #001 — Detalle junta expansión losa',   type:'RFI',           format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'Estructural',   taskRef:'TSK-003', taskName:'Cimentación bloque A',
    uploadedBy:'Álvaro Romero',  uploadedAt:'2026-05-28', size:'0.8 MB', status:'RESPONDIDO',
    description:'Consulta sobre detalle constructivo en junta de expansión entre ejes C y D' },
  { id:'doc5',  code:'RFI-002', name:'RFI #002 — Impermeabilizante cubierta',     type:'RFI',           format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'Arquitectura',  taskRef:'TSK-007', taskName:'Cubierta piso 20',
    uploadedBy:'Álvaro Romero',  uploadedAt:'2026-06-10', size:'0.5 MB', status:'PENDIENTE',  description:'' },
  { id:'doc6',  code:'MEM-001', name:'Memoria de cálculo estructura',              type:'MEMORIA',       format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'Estructural',   taskRef:'TSK-003', taskName:'Cimentación bloque A',
    uploadedBy:'Álvaro Romero',  uploadedAt:'2026-03-18', size:'3.4 MB', status:'VIGENTE',    description:'' },
  { id:'doc7',  code:'CON-001', name:'Contrato principal CT-2025-047',             type:'CONTRATO',      format:'PDF',  version:'Original',
    projectId:'p4', discipline:'Legal',         taskRef:null,      taskName:null,
    uploadedBy:'Paula Soto',    uploadedAt:'2026-02-28', size:'2.1 MB', status:'VIGENTE',    description:'' },
  { id:'doc8',  code:'PLN-010', name:'Diagrama de red — Módulo financiero',        type:'PLANO',         format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'TI',            taskRef:'TSK-011', taskName:'Diseño arquitectura módulo financiero',
    uploadedBy:'Paula Soto', uploadedAt:'2026-04-15', size:'1.8 MB', status:'VIGENTE',    description:'' },
  { id:'doc9',  code:'ESP-010', name:'Especificaciones funcionales módulo contable',type:'ESPECIFICACION',format:'DOCX', version:'Rev.2',
    projectId:'p4', discipline:'TI',            taskRef:'TSK-012', taskName:'Desarrollo módulo contabilidad',
    uploadedBy:'Ricardo Mora',  uploadedAt:'2026-05-02', size:'0.9 MB', status:'VIGENTE',    description:'' },
  { id:'doc10', code:'ENT-001', name:'Acta entrega parcial Fase 1 ERP',            type:'ENTREGABLE',    format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'General',       taskRef:'TSK-014', taskName:'Entrega Fase 1 al cliente',
    uploadedBy:'Ricardo Mora',  uploadedAt:'2026-06-01', size:'0.6 MB', status:'APROBADO',   description:'' },
  { id:'doc11', code:'RFI-010', name:'RFI #010 — Integración API legado',          type:'RFI',           format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'TI',            taskRef:'TSK-015', taskName:'Integración sistema legado',
    uploadedBy:'Paula Soto', uploadedAt:'2026-06-15', size:'0.4 MB', status:'PENDIENTE',
    description:'Aclaración requerida sobre protocolo de comunicación con sistema AS/400 del cliente' },
  { id:'doc12', code:'PLN-020', name:'Planos set lista instrucciones "Horizontes"', type:'PLANO',        format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'Producción',    taskRef:'TSK-021', taskName:'Grabación pistas base',
    uploadedBy:'Carmen Vidal',  uploadedAt:'2026-04-10', size:'1.1 MB', status:'VIGENTE',    description:'' },
  { id:'doc13', code:'CON-020', name:'Contrato distribución Sony Music Latin',      type:'CONTRATO',      format:'PDF',  version:'Original',
    projectId:'p4', discipline:'Legal',         taskRef:null,      taskName:null,
    uploadedBy:'Carmen Vidal',  uploadedAt:'2026-03-05', size:'2.0 MB', status:'VIGENTE',    description:'' },
  { id:'doc14', code:'ENT-020', name:'Master final álbum "Horizontes"',             type:'ENTREGABLE',    format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'Producción',    taskRef:'TSK-025', taskName:'Masterización final',
    uploadedBy:'Carmen Vidal',  uploadedAt:'2026-05-20', size:'0.8 MB', status:'PENDIENTE',  description:'Pendiente aprobación sello' },
  { id:'doc15', code:'PLN-030', name:'Arquitectura plataforma AR-PM v2.0',          type:'PLANO',         format:'PDF',  version:'Rev.3',
    projectId:'p4', discipline:'TI',            taskRef:'TSK-031', taskName:'Diseño arquitectura sistema',
    uploadedBy:'Jorge Salcedo', uploadedAt:'2026-06-15', size:'3.2 MB', status:'VIGENTE',    description:'' },
  { id:'doc16', code:'ESP-030', name:'Especificaciones API REST módulo proyectos',  type:'ESPECIFICACION', format:'DOCX', version:'Rev.2',
    projectId:'p4', discipline:'TI',            taskRef:'TSK-032', taskName:'Desarrollo API backend',
    uploadedBy:'Jorge Salcedo', uploadedAt:'2026-06-20', size:'1.4 MB', status:'VIGENTE',    description:'' },
  { id:'doc17', code:'RFI-030', name:'RFI #030 — Soporte multi-moneda en EVM',     type:'RFI',           format:'PDF',  version:'Rev.1',
    projectId:'p4', discipline:'TI',            taskRef:'TSK-033', taskName:'Módulo EVM y reportes',
    uploadedBy:'Jorge Salcedo', uploadedAt:'2026-06-25', size:'0.3 MB', status:'PENDIENTE',
    description:'Confirmación requerida sobre alcance del módulo EVM para múltiples divisas' },
];
const DOC_TYPES = ['Todos', 'PLANO', 'ESPECIFICACION', 'RFI', 'MEMORIA', 'CONTRATO', 'ENTREGABLE'];

const TYPE_BADGE = {
  PLANO:        'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300',
  ESPECIFICACION:'bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300',
  RFI:          'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300',
  MEMORIA:      'bg-slate-100 text-slate-700 dark:bg-slate-700/60 dark:text-slate-300',
  CONTRATO:     'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300',
  ENTREGABLE:   'bg-teal-100 text-teal-800 dark:bg-teal-900/40 dark:text-teal-300',
};

const STATUS_BADGE = {
  VIGENTE:    'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300',
  PENDIENTE:  'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300',
  RESPONDIDO: 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300',
  APROBADO:   'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300',
  OBSOLETO:   'bg-gray-100 text-gray-600 dark:bg-gray-700/60 dark:text-gray-400',
  CERRADO:    'bg-gray-100 text-gray-600 dark:bg-gray-700/60 dark:text-gray-400',
};

// ─── Helpers ──────────────────────────────────────────────────────────────────
function daysSince(dateStr) {
  const d = new Date(dateStr);
  const now = new Date('2026-06-26');
  return Math.floor((now - d) / 86400000);
}

function fmtDate(dateStr) {
  const [y, m, d] = dateStr.split('-');
  return `${d}/${m}/${y}`;
}

// ─── Sub-components ───────────────────────────────────────────────────────────
function Badge({ text, colorClass, small = false }) {
  return (
    <span className={`inline-flex items-center rounded-full font-medium ${small ? 'px-2 py-0.5 text-xs' : 'px-2.5 py-0.5 text-xs'} ${colorClass}`}>
      {text}
    </span>
  );
}

function FormatIcon({ format }) {
  const base = 'inline-flex items-center gap-1 text-xs font-semibold rounded px-1.5 py-0.5';
  if (format === 'PDF')
    return <span className={`${base} bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300`}>PDF</span>;
  if (format === 'DOCX')
    return <span className={`${base} bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300`}>DOCX</span>;
  if (format === 'DWG')
    return <span className={`${base} bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300`}>DWG</span>;
  return <span className={`${base} bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300`}>{format}</span>;
}

function ChevronIcon({ open }) {
  return (
    <svg className={`w-4 h-4 transition-transform duration-200 ${open ? 'rotate-90' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
    </svg>
  );
}

function KpiCard({ label, value, color }) {
  const colors = {
    blue:    'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300',
    emerald: 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-700 dark:text-emerald-300',
    amber:   'bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-300',
    teal:    'bg-teal-50 dark:bg-teal-900/20 text-teal-700 dark:text-teal-300',
  };
  return (
    <div className={`rounded-2xl p-4 ${colors[color]} border border-slate-200 dark:border-surface-700`}>
      <p className="text-2xl font-bold">{value}</p>
      <p className="text-xs mt-1 opacity-75">{label}</p>
    </div>
  );
}

// ─── Version history (simulated) ──────────────────────────────────────────────
function buildVersionHistory(doc) {
  const history = [];
  const revNum = parseInt((doc.version.match(/\d+/) || ['1'])[0], 10);
  for (let i = revNum; i >= 1; i--) {
    history.push({
      version: i === revNum ? doc.version : `Rev.${i - 1}`,
      uploadedBy: doc.uploadedBy,
      date: doc.uploadedAt,
      note: i === revNum ? 'Versión actual' : 'Versión anterior',
    });
  }
  return history;
}

// ─── Modal: Ver Documento ──────────────────────────────────────────────────────
function ViewDocModal({ doc, onClose }) {
  const history = buildVersionHistory(doc);
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col border border-slate-200 dark:border-surface-700">
        {/* Header */}
        <div className="flex items-start justify-between p-6 border-b border-slate-200 dark:border-surface-700">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1 flex-wrap">
              <span className="text-xs text-slate-500 dark:text-slate-400 font-mono">{doc.code}</span>
              <Badge text={doc.type} colorClass={TYPE_BADGE[doc.type] || ''} />
              <Badge text={doc.status} colorClass={STATUS_BADGE[doc.status] || ''} />
            </div>
            <h2 className="text-lg font-semibold text-slate-900 dark:text-white leading-tight">{doc.name}</h2>
          </div>
          <button onClick={onClose} className="ml-4 p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors flex-shrink-0">
            <svg className="w-5 h-5" 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>

        {/* Body */}
        <div className="overflow-y-auto flex-1 p-6 space-y-5">
          {/* Fields grid */}
          <div className="grid grid-cols-2 gap-4 text-sm">
            {[
              ['Proyecto', `${doc.project} (${doc.projectCode})`],
              ['Disciplina', doc.discipline],
              ['Versión', doc.version],
              ['Formato', doc.format],
              ['Tamaño', doc.size],
              ['Subido por', doc.uploadedBy],
              ['Fecha de subida', fmtDate(doc.uploadedAt)],
            ].map(([label, val]) => (
              <div key={label}>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-0.5">{label}</p>
                <p className="font-medium text-slate-800 dark:text-slate-200">{val}</p>
              </div>
            ))}
          </div>

          {/* Description */}
          {doc.description && (
            <div>
              <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Descripción</p>
              <p className="text-sm text-slate-700 dark:text-slate-300 bg-slate-50 dark:bg-slate-800 rounded-xl p-3 border border-slate-200 dark:border-surface-700">
                {doc.description}
              </p>
            </div>
          )}

          {/* Version history */}
          <div>
            <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Historial de versiones</p>
            <div className="space-y-2">
              {history.map((h, i) => (
                <div key={i} className="flex items-center justify-between text-sm bg-slate-50 dark:bg-slate-800 rounded-xl px-4 py-2.5 border border-slate-200 dark:border-surface-700">
                  <div className="flex items-center gap-3">
                    <span className="font-mono text-xs bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 px-2 py-0.5 rounded">{h.version}</span>
                    <span className="text-slate-600 dark:text-slate-400">{h.note}</span>
                  </div>
                  <div className="text-right text-xs text-slate-400">
                    <span>{h.uploadedBy}</span>
                    <span className="ml-2">{fmtDate(h.date)}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-6 border-t border-slate-200 dark:border-surface-700">
          <button
            onClick={() => alert(`Descargando: ${doc.name} (${doc.format}, ${doc.size})`)}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium bg-blue-600 hover:bg-blue-700 text-white transition-colors"
          >
            <svg className="w-4 h-4" 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-4l-4 4m0 0l-4-4m4 4V4" />
            </svg>
            Descargar
          </button>
          <button
            onClick={() => { alert('Subir nueva versión del documento'); onClose(); }}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors"
          >
            Nueva versión
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Modal: Subir Documento ───────────────────────────────────────────────────
function UploadDocModal({ onClose, onSave, projectFilter }) {
  const defaultProjectId = projectFilter || MOCK_PROJECTS[0]?.id || 'p4';
  const [form, setForm] = useState({
    code: '',
    name: '',
    type: 'PLANO',
    discipline: '',
    projectId: defaultProjectId,
    taskRef: '',
    taskName: '',
    version: 'Rev.1',
    description: '',
  });
  const [droppedFile, setDroppedFile] = useState(null);
  const [dragOver, setDragOver] = useState(false);
  const fileRef = useRef(null);

  function handleFile(file) {
    if (!file) return;
    setDroppedFile({ name: file.name, size: `${(file.size / 1048576).toFixed(1)} MB` });
  }

  function handleDrop(e) {
    e.preventDefault();
    setDragOver(false);
    const file = e.dataTransfer.files[0];
    handleFile(file);
  }

  function handleSubmit(e) {
    e.preventDefault();
    if (!form.code || !form.name || !form.discipline) {
      alert('Por favor completa los campos obligatorios: Código, Nombre y Disciplina.');
      return;
    }
    const ext = droppedFile ? droppedFile.name.split('.').pop().toUpperCase() : 'PDF';
    const newDoc = {
      id: `doc_${Date.now()}`,
      code: form.code,
      name: form.name,
      type: form.type,
      format: ext,
      version: form.version,
      projectId: form.projectId,
      taskRef: form.taskRef || null,
      taskName: form.taskName || null,
      discipline: form.discipline,
      uploadedBy: 'Usuario actual',
      uploadedAt: new Date().toISOString().slice(0, 10),
      size: droppedFile ? droppedFile.size : '—',
      status: form.type === 'RFI' ? 'PENDIENTE' : 'VIGENTE',
      description: form.description,
    };
    onSave(newDoc);
    onClose();
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl w-full max-w-xl max-h-[90vh] flex flex-col border border-slate-200 dark:border-surface-700">
        <div className="flex items-center justify-between p-6 border-b border-slate-200 dark:border-surface-700">
          <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Subir documento</h2>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400 hover:text-slate-600 transition-colors">
            <svg className="w-5 h-5" 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>

        <form onSubmit={handleSubmit} className="overflow-y-auto flex-1 p-6 space-y-4">
          {/* Code + Name */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Código *</label>
              <input
                value={form.code} onChange={e => setForm(p => ({ ...p, code: e.target.value }))}
                placeholder="PLN-003"
                className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Versión</label>
              <input
                value={form.version} onChange={e => setForm(p => ({ ...p, version: e.target.value }))}
                placeholder="Rev.1"
                className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Nombre del documento *</label>
            <input
              value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))}
              placeholder="Descripción del documento"
              className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Tipo</label>
              <select
                value={form.type} onChange={e => setForm(p => ({ ...p, type: e.target.value }))}
                className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {DOC_TYPES.filter(t => t !== 'Todos').map(t => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Proyecto</label>
              <select
                value={form.projectId} onChange={e => setForm(p => ({ ...p, projectId: e.target.value }))}
                className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {MOCK_PROJECTS.map(p => (
                  <option key={p.id} value={p.id}>{p.code} — {p.name}</option>
                ))}
              </select>
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Disciplina *</label>
            <input
              value={form.discipline} onChange={e => setForm(p => ({ ...p, discipline: e.target.value }))}
              placeholder="Arquitectura, Estructural, TI…"
              className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Tarea de referencia</label>
              <input
                value={form.taskRef} onChange={e => setForm(p => ({ ...p, taskRef: e.target.value }))}
                placeholder="TSK-001"
                className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Nombre de tarea</label>
              <input
                value={form.taskName} onChange={e => setForm(p => ({ ...p, taskName: e.target.value }))}
                placeholder="Nombre de la tarea"
                className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Descripción</label>
            <textarea
              rows={3} value={form.description} onChange={e => setForm(p => ({ ...p, description: e.target.value }))}
              placeholder="Descripción breve del documento…"
              className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
            />
          </div>

          {/* Drop zone */}
          <div>
            <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Archivo</label>
            <div
              onDragOver={e => { e.preventDefault(); setDragOver(true); }}
              onDragLeave={() => setDragOver(false)}
              onDrop={handleDrop}
              onClick={() => fileRef.current?.click()}
              className={`relative cursor-pointer rounded-xl border-2 border-dashed p-6 text-center transition-colors ${
                dragOver
                  ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                  : 'border-slate-300 dark:border-slate-600 hover:border-blue-400 hover:bg-slate-50 dark:hover:bg-slate-800'
              }`}
            >
              <input
                ref={fileRef} type="file" className="hidden"
                onChange={e => handleFile(e.target.files[0])}
              />
              {droppedFile ? (
                <div className="flex items-center justify-center gap-2 text-sm text-slate-700 dark:text-slate-300">
                  <svg className="w-5 h-5 text-green-500" 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>
                  <span className="font-medium">{droppedFile.name}</span>
                  <span className="text-slate-400">({droppedFile.size})</span>
                </div>
              ) : (
                <>
                  <svg className="w-8 h-8 mx-auto text-slate-400 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                  </svg>
                  <p className="text-sm text-slate-500 dark:text-slate-400">Arrastra un archivo aquí o <span className="text-blue-600 dark:text-blue-400 font-medium">selecciona uno</span></p>
                  <p className="text-xs text-slate-400 mt-1">PDF, DOCX, DWG, XLSX…</p>
                </>
              )}
            </div>
          </div>

          <div className="flex items-center justify-end gap-3 pt-2">
            <button type="button" onClick={onClose} className="px-4 py-2 rounded-xl text-sm font-medium border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
              Cancelar
            </button>
            <button type="submit" className="px-4 py-2 rounded-xl text-sm font-medium bg-blue-600 hover:bg-blue-700 text-white transition-colors">
              Subir documento
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ─── Modal: Registrar Respuesta RFI ──────────────────────────────────────────
function RfiResponseModal({ rfi, onClose, onSave }) {
  const [response, setResponse] = useState('');

  function handleSubmit(e) {
    e.preventDefault();
    if (!response.trim()) { alert('Por favor ingresa la respuesta al RFI.'); return; }
    onSave(rfi.id, response);
    onClose();
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl w-full max-w-lg border border-slate-200 dark:border-surface-700">
        <div className="flex items-center justify-between p-6 border-b border-slate-200 dark:border-surface-700">
          <div>
            <h2 className="text-base font-semibold text-slate-900 dark:text-white">Registrar respuesta</h2>
            <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{rfi.code} — {rfi.name}</p>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400 transition-colors">
            <svg className="w-5 h-5" 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>
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Respuesta al RFI *</label>
            <textarea
              rows={5} value={response} onChange={e => setResponse(e.target.value)}
              placeholder="Detalla la resolución técnica o aclaración para este RFI…"
              className="w-full text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
            />
          </div>
          <div className="flex items-center justify-end gap-3">
            <button type="button" onClick={onClose} className="px-4 py-2 rounded-xl text-sm font-medium border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
              Cancelar
            </button>
            <button type="submit" className="px-4 py-2 rounded-xl text-sm font-medium bg-blue-600 hover:bg-blue-700 text-white transition-colors">
              Registrar respuesta
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ─── Discipline Tree Row ──────────────────────────────────────────────────────
function DisciplineGroup({ discipline, docs, onView }) {
  const [open, setOpen] = useState(true);

  return (
    <div className="border border-slate-200 dark:border-surface-700 rounded-2xl overflow-hidden">
      {/* Discipline header */}
      <button
        onClick={() => setOpen(p => !p)}
        className="w-full flex items-center justify-between px-4 py-3 bg-slate-50 dark:bg-slate-800/60 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors text-left"
      >
        <div className="flex items-center gap-2">
          <ChevronIcon open={open} />
          <span className="text-sm font-semibold text-slate-700 dark:text-slate-300">{discipline}</span>
          <span className="text-xs text-slate-400">({docs.length} doc{docs.length !== 1 ? 's' : ''})</span>
        </div>
      </button>

      {/* Table */}
      {open && (
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-t border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900">
                {['Código', 'Nombre', 'Proyecto', 'Tarea ref.', 'Tipo', 'Versión', 'Formato', 'Subido por', 'Fecha', 'Estado', ''].map(h => (
                  <th key={h} className="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {docs.map((doc, i) => (
                <tr key={doc.id} className={`border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors ${i % 2 === 0 ? '' : 'bg-slate-50/50 dark:bg-slate-800/20'}`}>
                  <td className="px-4 py-3 font-mono text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">{doc.code}</td>
                  <td className="px-4 py-3 text-slate-800 dark:text-slate-200 max-w-xs">
                    <span className="line-clamp-1">{doc.name}</span>
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <span className="text-xs font-mono bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 px-1.5 py-0.5 rounded">
                      {PROJECT_CODE_LABEL[doc.projectId] || doc.projectId}
                    </span>
                    <p className="text-xs text-slate-400 dark:text-slate-500 truncate max-w-[120px] mt-0.5">
                      {MOCK_PROJECTS.find(p => p.id === doc.projectId)?.name || ''}
                    </p>
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    {doc.taskRef ? (
                      <div>
                        <span className="text-xs font-mono text-blue-600 dark:text-blue-400">{doc.taskRef}</span>
                        {doc.taskName && <p className="text-xs text-slate-400 dark:text-slate-500 truncate max-w-[140px]">{doc.taskName}</p>}
                      </div>
                    ) : (
                      <span className="text-xs text-slate-300 dark:text-slate-600">—</span>
                    )}
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <Badge text={doc.type} colorClass={TYPE_BADGE[doc.type] || ''} />
                  </td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-400 whitespace-nowrap text-xs font-mono">{doc.version}</td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <FormatIcon format={doc.format} />
                  </td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-400 whitespace-nowrap text-xs">{doc.uploadedBy}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap text-xs">{fmtDate(doc.uploadedAt)}</td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <Badge text={doc.status} colorClass={STATUS_BADGE[doc.status] || ''} />
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <button
                      onClick={() => onView(doc)}
                      className="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium"
                    >
                      Ver
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Tab: Documents ───────────────────────────────────────────────────────────
function DocumentsTab({ docs, onView }) {
  const byDiscipline = useMemo(() => {
    const map = {};
    docs.forEach(d => {
      if (!map[d.discipline]) map[d.discipline] = [];
      map[d.discipline].push(d);
    });
    return Object.entries(map).sort(([a], [b]) => a.localeCompare(b));
  }, [docs]);

  if (docs.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-slate-400">
        <svg className="w-12 h-12 mb-3 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        <p className="text-sm">No hay documentos que coincidan con los filtros.</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {byDiscipline.map(([discipline, disciplineDocs]) => (
        <DisciplineGroup key={discipline} discipline={discipline} docs={disciplineDocs} onView={onView} />
      ))}
    </div>
  );
}

// ─── Tab: RFIs ────────────────────────────────────────────────────────────────
function RFIsTab({ docs, onRespond }) {
  const rfis = useMemo(() => docs.filter(d => d.type === 'RFI'), [docs]);

  if (rfis.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-slate-400">
        <p className="text-sm">No hay RFIs para el proyecto o filtro seleccionado.</p>
      </div>
    );
  }

  return (
    <div className="border border-slate-200 dark:border-surface-700 rounded-2xl overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-slate-800/60">
              {['Código', 'Descripción', 'Disciplina', 'Subido por', 'Fecha', 'Días abierto', 'Estado', 'Acción'].map(h => (
                <th key={h} className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rfis.map((rfi, i) => {
              const days = daysSince(rfi.uploadedAt);
              const isPending = rfi.status === 'PENDIENTE';
              return (
                <tr key={rfi.id} className={`border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors ${i % 2 === 0 ? '' : 'bg-slate-50/50 dark:bg-slate-800/20'}`}>
                  <td className="px-4 py-3 font-mono text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">{rfi.code}</td>
                  <td className="px-4 py-3 text-slate-800 dark:text-slate-200 max-w-xs">
                    <div className="line-clamp-2">{rfi.name}</div>
                    {rfi.description && <p className="text-xs text-slate-400 mt-0.5 line-clamp-1">{rfi.description}</p>}
                  </td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-400 whitespace-nowrap text-xs">{rfi.discipline}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-400 whitespace-nowrap text-xs">{rfi.uploadedBy}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap text-xs">{fmtDate(rfi.uploadedAt)}</td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <span className={`text-xs font-semibold ${days > 14 && isPending ? 'text-red-600 dark:text-red-400' : days > 7 && isPending ? 'text-amber-600 dark:text-amber-400' : 'text-slate-600 dark:text-slate-400'}`}>
                      {days}d
                    </span>
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <Badge text={rfi.status} colorClass={STATUS_BADGE[rfi.status] || ''} />
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    {isPending ? (
                      <button
                        onClick={() => onRespond(rfi)}
                        className="text-xs bg-blue-600 hover:bg-blue-700 text-white px-3 py-1.5 rounded-lg font-medium transition-colors whitespace-nowrap"
                      >
                        Registrar respuesta
                      </button>
                    ) : (
                      <span className="text-xs text-slate-400">—</span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────
export default function DocumentsPage() {
  const { selectedProjectId } = useProject();
  const [docs, setDocs] = useState(MOCK_DOCS_INITIAL);
  const [typeFilter, setTypeFilter] = useState('Todos');
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('documentos'); // 'documentos' | 'rfis'

  const [viewDoc, setViewDoc] = useState(null);
  const [showUpload, setShowUpload] = useState(false);
  const [rfiToRespond, setRfiToRespond] = useState(null);

  // Filter docs — respects global project selector from Navbar
  const filteredDocs = useMemo(() => {
    return docs.filter(d => {
      const matchProject = !selectedProjectId || d.projectId === selectedProjectId;
      const matchType = typeFilter === 'Todos' || d.type === typeFilter;
      const matchSearch = !search || [d.code, d.name, d.uploadedBy, d.discipline, d.taskRef, d.taskName].some(f =>
        f?.toLowerCase().includes(search.toLowerCase())
      );
      return matchProject && matchType && matchSearch;
    });
  }, [docs, selectedProjectId, typeFilter, search]);

  // KPIs — scoped to current project filter
  const kpis = useMemo(() => {
    const scope = selectedProjectId ? docs.filter(d => d.projectId === selectedProjectId) : docs;
    return {
      total: scope.length,
      planosVigentes: scope.filter(d => d.type === 'PLANO' && d.status === 'VIGENTE').length,
      rfisPendientes: scope.filter(d => d.type === 'RFI' && d.status === 'PENDIENTE').length,
      entregablesAprobados: scope.filter(d => d.type === 'ENTREGABLE' && d.status === 'APROBADO').length,
    };
  }, [docs, selectedProjectId]);

  function handleSaveDoc(newDoc) {
    setDocs(p => [newDoc, ...p]);
  }

  function handleRfiResponse(id, _response) {
    setDocs(p => p.map(d => d.id === id ? { ...d, status: 'RESPONDIDO' } : d));
  }

  const tabs = [
    { id: 'documentos', label: 'Documentos' },
    { id: 'rfis', label: `RFIs (${docs.filter(d => d.type === 'RFI').length})` },
  ];

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto space-y-6">

        {/* ── Header ─────────────────────────────────────────────────────────── */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Repositorio de documentos</h1>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">Gestión centralizada de documentos técnicos por proyecto</p>
          </div>
          <button
            onClick={() => setShowUpload(true)}
            className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium bg-blue-600 hover:bg-blue-700 text-white transition-colors shadow-sm flex-shrink-0"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
            </svg>
            Subir documento
          </button>
        </div>

        {/* ── Filters ────────────────────────────────────────────────────────── */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 p-4">
          <div className="flex flex-col sm:flex-row gap-3">
            {/* Search */}
            <div className="relative flex-1">
              <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" 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
                value={search} onChange={e => setSearch(e.target.value)}
                placeholder="Buscar por código, nombre, disciplina…"
                className="w-full pl-9 pr-3 py-2 text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            {/* Type filter */}
            <select
              value={typeFilter} onChange={e => setTypeFilter(e.target.value)}
              className="text-sm rounded-xl border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 min-w-40"
            >
              {DOC_TYPES.map(t => <option key={t}>{t}</option>)}
            </select>
          </div>
        </div>

        {/* ── KPIs ───────────────────────────────────────────────────────────── */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          <KpiCard label="Total documentos" value={kpis.total} color="blue" />
          <KpiCard label="Planos vigentes" value={kpis.planosVigentes} color="emerald" />
          <KpiCard label="RFIs pendientes" value={kpis.rfisPendientes} color="amber" />
          <KpiCard label="Entregables aprobados" value={kpis.entregablesAprobados} color="teal" />
        </div>

        {/* ── Tabs + Content ─────────────────────────────────────────────────── */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden">
          {/* Tab bar */}
          <div className="flex border-b border-slate-200 dark:border-surface-700 px-4">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-3.5 text-sm font-medium border-b-2 transition-colors mr-2 ${
                  activeTab === tab.id
                    ? 'border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400'
                    : 'border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {/* Tab content */}
          <div className="p-4">
            {activeTab === 'documentos' && (
              <DocumentsTab docs={filteredDocs} onView={setViewDoc} />
            )}
            {activeTab === 'rfis' && (
              <RFIsTab docs={filteredDocs} onRespond={setRfiToRespond} />
            )}
          </div>
        </div>
      </div>

      {/* ── Modals ─────────────────────────────────────────────────────────── */}
      {viewDoc && (
        <ViewDocModal doc={viewDoc} onClose={() => setViewDoc(null)} />
      )}
      {showUpload && (
        <UploadDocModal
          onClose={() => setShowUpload(false)}
          onSave={handleSaveDoc}
          projectFilter={selectedProjectId}
        />
      )}
      {rfiToRespond && (
        <RfiResponseModal
          rfi={rfiToRespond}
          onClose={() => setRfiToRespond(null)}
          onSave={handleRfiResponse}
        />
      )}
    </div>
  );
}
