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

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

const MEETING_TYPES = {
  SEGUIMIENTO: { label: 'Seguimiento', color: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' },
  KICK_OFF:    { label: 'Kick-Off',    color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' },
  COMITE:      { label: 'Comité',      color: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300' },
  CLIENTE:     { label: 'Cliente',     color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' },
  TECNICA:     { label: 'Técnica',     color: 'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-300' },
};

const STATUS_MEETING = {
  BORRADOR:    { label: 'Borrador',    color: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300' },
  FIRMADA:     { label: 'Firmada',     color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' },
  DISTRIBUIDA: { label: 'Distribuida', color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' },
};

const STATUS_ACTION = {
  PENDIENTE:   { label: 'Pendiente',   color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' },
  EN_PROCESO:  { label: 'En Proceso',  color: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' },
  COMPLETADO:  { label: 'Completado',  color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' },
  VENCIDO:     { label: 'Vencido',     color: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' },
};

const TYPE_DOT_COLORS = {
  SEGUIMIENTO: '#3b82f6',
  KICK_OFF:    '#10b981',
  COMITE:      '#8b5cf6',
  CLIENTE:     '#f59e0b',
  TECNICA:     '#64748b',
};

const INITIAL_MEETINGS = [
  {
    id: 'm1',
    projectId: 'p4',
    title: 'Reunión de Inicio — AR-ProjectManagement Norte',
    type: 'KICK_OFF',
    status: 'DISTRIBUIDA',
    date: '2026-03-10',
    location: 'Sala Principal, Oficina Central',
    attendees: ['Carlos Mendoza', 'Laura Pineda', 'Javier Torres', 'Ana Reyes', 'Roberto Silva'],
    agenda: ['Presentación del equipo', 'Alcance del proyecto', 'Cronograma preliminar', 'Recursos y presupuesto'],
    discussion: [
      'Se presentaron todos los integrantes del equipo. Carlos Mendoza asumirá la dirección técnica.',
      'El alcance incluye 22 pisos con zonas comunes. Se excluyeron los sótanos de la fase 1.',
      'El cronograma preliminar establece 18 meses. Fecha tentativa de entrega: octubre 2027.',
      'Se aprobó el presupuesto inicial. Próxima revisión en 30 días.',
    ],
    actionItems: [
      { id: 'a1', text: 'Elaborar cronograma detallado con hitos', responsible: 'Carlos Mendoza', dueDate: '2026-03-25', status: 'COMPLETADO' },
      { id: 'a2', text: 'Contratar empresa de topografía', responsible: 'Laura Pineda', dueDate: '2026-04-01', status: 'COMPLETADO' },
    ],
  },
  {
    id: 'm2',
    projectId: 'p4',
    title: 'Reunión de Seguimiento — Semana 12',
    type: 'SEGUIMIENTO',
    status: 'FIRMADA',
    date: '2026-06-15',
    location: 'Obra — Sala de Ingeniería',
    attendees: ['Carlos Mendoza', 'Laura Pineda', 'Javier Torres'],
    agenda: ['Avance de obra', 'Incidencias estructurales', 'Revisión de subcontratistas'],
    discussion: [
      'Avance al 34%. Retraso de 3 días en el vaciado de la losa del piso 8.',
      'Se detectó una fisura menor en el pilar P-14. Se ordenó inspección.',
      'Subcontratista de electricidad presenta retraso en entrega de materiales.',
    ],
    actionItems: [
      { id: 'a3', text: 'Inspección estructural pilar P-14 con ingeniero especialista', responsible: 'Javier Torres', dueDate: '2026-06-20', status: 'VENCIDO' },
      { id: 'a4', text: 'Gestionar penalidad a subcontratista eléctrico', responsible: 'Laura Pineda', dueDate: '2026-06-30', status: 'PENDIENTE' },
      { id: 'a5', text: 'Reprogramar vaciado de losa piso 9', responsible: 'Carlos Mendoza', dueDate: '2026-06-28', status: 'EN_PROCESO' },
    ],
  },
  {
    id: 'm3',
    projectId: 'p4',
    title: 'Reunión con Sony — Revisión Tracks "Horizontes"',
    type: 'CLIENTE',
    status: 'DISTRIBUIDA',
    date: '2026-05-20',
    location: 'Zoom — https://zoom.us/j/9988776655',
    attendees: ['Diego Ramírez', 'Sofia Chen', 'Mark Johnson (Sony)', 'Ana Lucia Vega'],
    agenda: ['Escucha de tracks terminados', 'Feedback dirección artística', 'Fechas de masterización'],
    discussion: [
      'Se escucharon los 8 tracks finalizados. Mark Johnson aprobó 6 sin observaciones.',
      'Tracks 3 y 7 requieren ajustes en mezcla de voces. Sony solicitó más presencia en graves.',
      'Masterización programada para julio 2026 con estudio en Miami.',
    ],
    actionItems: [
      { id: 'a6', text: 'Remezclar tracks 3 y 7 con ajustes Sony', responsible: 'Diego Ramírez', dueDate: '2026-06-10', status: 'COMPLETADO' },
      { id: 'a7', text: 'Confirmar fechas con estudio de masterización en Miami', responsible: 'Sofia Chen', dueDate: '2026-06-25', status: 'VENCIDO' },
    ],
  },
  {
    id: 'm4',
    projectId: 'p4',
    title: 'Comité de Dirección ERP — Revisión Q2',
    type: 'COMITE',
    status: 'BORRADOR',
    date: '2026-06-24',
    location: 'Sala de Juntas Piso 10, Grupo Empresarial XYZ',
    attendees: ['María González', 'Pablo Ruiz', 'Carmen López', 'Tomás Herrera', 'Isabel Fernández'],
    agenda: ['Estado de implementación módulos', 'Issues críticos en producción', 'Hoja de ruta Q3'],
    discussion: [
      'Módulos de finanzas y RRHH al 78% de implementación. Inventario al 45%.',
      'Se reportaron 3 issues críticos en el módulo de nómina. Pendiente resolución.',
      'La hoja de ruta Q3 contempla go-live de módulo de compras en septiembre.',
    ],
    actionItems: [
      { id: 'a8', text: 'Resolver issues críticos módulo nómina (tickets #441, #442, #450)', responsible: 'Pablo Ruiz', dueDate: '2026-07-03', status: 'PENDIENTE' },
      { id: 'a9', text: 'Documentar plan de contingencia go-live compras', responsible: 'María González', dueDate: '2026-07-10', status: 'PENDIENTE' },
      { id: 'a10', text: 'Capacitación usuarios módulo inventario — 3 sesiones', responsible: 'Carmen López', dueDate: '2026-07-15', status: 'PENDIENTE' },
    ],
  },
  {
    id: 'm5',
    projectId: 'p4',
    title: 'Revisión Técnica — Sprint 4 AR-ProjectManagement',
    type: 'TECNICA',
    status: 'FIRMADA',
    date: '2026-06-18',
    location: 'AR Electronics — Lab de Desarrollo',
    attendees: ['Álvaro Romero', 'Elena Vargas', 'Luis Castillo'],
    agenda: ['Demo sprint 4', 'Revisión de arquitectura frontend', 'Planificación sprint 5'],
    discussion: [
      'Se demostró el módulo de Recursos y el Dashboard. Ambos aprobados.',
      'Se acordó migrar a Tailwind v4 en sprint 6. Se mantendrá compatibilidad.',
      'Sprint 5 incluirá: Reuniones, Financiero y módulo de Reportes.',
    ],
    actionItems: [
      { id: 'a11', text: 'Crear componente MeetingsPage con todas las funciones especificadas', responsible: 'Álvaro Romero', dueDate: '2026-06-26', status: 'EN_PROCESO' },
      { id: 'a12', text: 'Actualizar CLAUDE.md con convenciones de modales', responsible: 'Elena Vargas', dueDate: '2026-06-28', status: 'PENDIENTE' },
    ],
  },
  {
    id: 'm6',
    projectId: 'p4',
    title: 'Kick-Off Módulo Financiero AR-ERP',
    type: 'KICK_OFF',
    status: 'BORRADOR',
    date: '2026-07-02',
    location: 'AR Electronics — Sala Alpha',
    attendees: ['Álvaro Romero', 'Elena Vargas', 'Luis Castillo', 'Marta Sousa'],
    agenda: ['Definición de alcance financiero', 'Integración con módulos existentes', 'Mockups y UX'],
    discussion: [],
    actionItems: [],
  },
];

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

function today() {
  return new Date().toISOString().split('T')[0];
}

function daysRemaining(dueDate) {
  const diff = Math.ceil((new Date(dueDate) - new Date(today())) / 86400000);
  return diff;
}

function formatDate(dateStr) {
  return new Date(dateStr + 'T12:00:00').toLocaleDateString('es-ES', {
    day: '2-digit', month: 'short', year: 'numeric',
  });
}

function getProjectName(id) {
  const p = MOCK_PROJECTS.find(x => x.id === id);
  return p ? p.name : id;
}

function getProjectCode(id) {
  const p = MOCK_PROJECTS.find(x => x.id === id);
  return p ? p.code : id;
}

// ─── Chip Input ───────────────────────────────────────────────────────────────

function ChipInput({ chips, onChange, placeholder }) {
  const [input, setInput] = useState('');
  function handleKey(e) {
    if ((e.key === 'Enter' || e.key === ',') && input.trim()) {
      e.preventDefault();
      if (!chips.includes(input.trim())) onChange([...chips, input.trim()]);
      setInput('');
    }
  }
  function remove(chip) { onChange(chips.filter(c => c !== chip)); }
  return (
    <div className="flex flex-wrap gap-1.5 border border-slate-300 dark:border-slate-600 rounded-xl p-2 bg-white dark:bg-slate-800 min-h-[44px]">
      {chips.map(c => (
        <span key={c} className="flex items-center gap-1 bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 rounded-full px-2.5 py-0.5 text-xs font-medium">
          {c}
          <button type="button" onClick={() => remove(c)} className="hover:text-red-500 ml-0.5">×</button>
        </span>
      ))}
      <input
        value={input}
        onChange={e => setInput(e.target.value)}
        onKeyDown={handleKey}
        placeholder={chips.length === 0 ? placeholder : ''}
        className="flex-1 min-w-[120px] bg-transparent outline-none text-sm text-slate-800 dark:text-slate-200 placeholder-slate-400"
      />
    </div>
  );
}

// ─── NewMeetingModal ──────────────────────────────────────────────────────────

function NewMeetingModal({ onClose, onSave }) {
  const [form, setForm] = useState({
    title: '', type: 'SEGUIMIENTO', projectId: 'p4',
    date: today(), location: '', attendees: [], agenda: [''],
  });

  function set(key, val) { setForm(f => ({ ...f, [key]: val })); }

  function setAgendaItem(i, val) {
    const a = [...form.agenda]; a[i] = val; set('agenda', a);
  }
  function addAgenda() { set('agenda', [...form.agenda, '']); }
  function removeAgenda(i) { set('agenda', form.agenda.filter((_, idx) => idx !== i)); }

  function handleSave() {
    if (!form.title.trim() || !form.date) return;
    onSave({
      id: 'm' + Date.now(),
      ...form,
      agenda: form.agenda.filter(a => a.trim()),
      status: 'BORRADOR',
      discussion: form.agenda.map(() => ''),
      actionItems: [],
    });
    onClose();
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-6 border-b border-slate-200 dark:border-slate-700">
          <h2 className="text-lg font-bold text-slate-900 dark:text-white">Nueva Reunión</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-xl">×</button>
        </div>
        <div className="p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Título *</label>
            <input value={form.title} onChange={e => set('title', e.target.value)}
              className="w-full border border-slate-300 dark:border-slate-600 rounded-xl px-3 py-2 text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Ej. Reunión de seguimiento semanal" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Tipo</label>
              <select value={form.type} onChange={e => set('type', e.target.value)}
                className="w-full border border-slate-300 dark:border-slate-600 rounded-xl px-3 py-2 text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500">
                {Object.entries(MEETING_TYPES).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Proyecto</label>
              <select value={form.projectId} onChange={e => set('projectId', e.target.value)}
                className="w-full border border-slate-300 dark:border-slate-600 rounded-xl px-3 py-2 text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500">
                {MOCK_PROJECTS.map(p => <option key={p.id} value={p.id}>{p.code}</option>)}
              </select>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Fecha *</label>
              <input type="date" value={form.date} onChange={e => set('date', e.target.value)}
                className="w-full border border-slate-300 dark:border-slate-600 rounded-xl px-3 py-2 text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Lugar / Enlace</label>
              <input value={form.location} onChange={e => set('location', e.target.value)}
                className="w-full border border-slate-300 dark:border-slate-600 rounded-xl px-3 py-2 text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="Sala / URL Zoom / Teams" />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Asistentes <span className="text-xs text-slate-400">(Escribir nombre + Enter)</span></label>
            <ChipInput chips={form.attendees} onChange={v => set('attendees', v)} placeholder="Nombre del asistente..." />
          </div>
          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300">Agenda</label>
              <button type="button" onClick={addAgenda} className="text-xs text-blue-600 dark:text-blue-400 hover:underline">+ Añadir punto</button>
            </div>
            <div className="space-y-2">
              {form.agenda.map((item, i) => (
                <div key={i} className="flex gap-2 items-center">
                  <span className="text-xs text-slate-400 w-5 text-right">{i + 1}.</span>
                  <input value={item} onChange={e => setAgendaItem(i, e.target.value)}
                    className="flex-1 border border-slate-300 dark:border-slate-600 rounded-xl px-3 py-2 text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder={`Punto ${i + 1} de agenda`} />
                  {form.agenda.length > 1 && (
                    <button type="button" onClick={() => removeAgenda(i)} className="text-slate-400 hover:text-red-500 text-lg leading-none">×</button>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="flex justify-end gap-3 p-6 border-t border-slate-200 dark:border-slate-700">
          <button onClick={onClose} className="border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-xl px-4 py-2.5 text-sm">Cancelar</button>
          <button onClick={handleSave} className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors">Guardar como Borrador</button>
        </div>
      </div>
    </div>
  );
}

// ─── MeetingDetailModal ───────────────────────────────────────────────────────

function MeetingDetailModal({ meeting, onClose, onUpdate }) {
  const isReadonly = meeting.status === 'DISTRIBUIDA';
  const [discussion, setDiscussion] = useState(
    meeting.discussion.length > 0 ? meeting.discussion : meeting.agenda.map(() => '')
  );
  const [actionItems, setActionItems] = useState(meeting.actionItems);

  function setDisc(i, val) { const d = [...discussion]; d[i] = val; setDiscussion(d); }

  function addAction() {
    setActionItems(a => [...a, { id: 'a' + Date.now(), text: '', responsible: '', dueDate: today(), status: 'PENDIENTE' }]);
  }
  function setAction(i, key, val) {
    setActionItems(a => a.map((item, idx) => idx === i ? { ...item, [key]: val } : item));
  }
  function removeAction(i) { setActionItems(a => a.filter((_, idx) => idx !== i)); }

  function handleSign() {
    onUpdate({ ...meeting, status: 'DISTRIBUIDA', discussion, actionItems });
    onClose();
  }
  function handleSave() {
    onUpdate({ ...meeting, discussion, actionItems });
    onClose();
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-3xl max-h-[92vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-start justify-between p-6 border-b border-slate-200 dark:border-slate-700">
          <div className="flex-1 pr-4">
            <div className="flex items-center gap-2 mb-2 flex-wrap">
              <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${MEETING_TYPES[meeting.type].color}`}>{MEETING_TYPES[meeting.type].label}</span>
              <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_MEETING[meeting.status].color}`}>{STATUS_MEETING[meeting.status].label}</span>
            </div>
            <h2 className="text-lg font-bold text-slate-900 dark:text-white">{meeting.title}</h2>
            <div className="mt-2 flex flex-wrap gap-4 text-sm text-slate-500 dark:text-slate-400">
              <span>📅 {formatDate(meeting.date)}</span>
              <span>📍 {meeting.location || '—'}</span>
              <span>🏗 {getProjectCode(meeting.projectId)}</span>
              <span>👥 {meeting.attendees.join(', ')}</span>
            </div>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-xl shrink-0">×</button>
        </div>

        <div className="p-6 space-y-6">
          {/* Agenda + Discussion */}
          <div>
            <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-300 uppercase tracking-wide mb-3">Agenda y Discusión</h3>
            <div className="space-y-4">
              {meeting.agenda.map((point, i) => (
                <div key={i} className="rounded-xl border border-slate-200 dark:border-slate-700 p-4">
                  <p className="text-sm font-medium text-slate-800 dark:text-slate-200 mb-2">{i + 1}. {point}</p>
                  {isReadonly ? (
                    <p className="text-sm text-slate-600 dark:text-slate-400 whitespace-pre-wrap">{discussion[i] || '—'}</p>
                  ) : (
                    <textarea
                      value={discussion[i] || ''}
                      onChange={e => setDisc(i, e.target.value)}
                      rows={3}
                      placeholder="Puntos discutidos, acuerdos, observaciones..."
                      className="w-full border border-slate-300 dark:border-slate-600 rounded-xl px-3 py-2 text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                    />
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Action Items */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-300 uppercase tracking-wide">Compromisos</h3>
              {!isReadonly && (
                <button type="button" onClick={addAction} className="text-xs text-blue-600 dark:text-blue-400 hover:underline">+ Añadir compromiso</button>
              )}
            </div>
            {actionItems.length === 0 ? (
              <p className="text-sm text-slate-400 italic">Sin compromisos registrados.</p>
            ) : (
              <div className="space-y-2">
                {isReadonly ? (
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="bg-slate-50 dark:bg-slate-800/60">
                        <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-3 py-2">Compromiso</th>
                        <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-3 py-2">Responsable</th>
                        <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-3 py-2">Fecha límite</th>
                        <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-3 py-2">Estado</th>
                      </tr>
                    </thead>
                    <tbody>
                      {actionItems.map(a => (
                        <tr key={a.id} className="border-t border-slate-100 dark:border-slate-800">
                          <td className="px-3 py-2 text-slate-800 dark:text-slate-200">{a.text}</td>
                          <td className="px-3 py-2 text-slate-600 dark:text-slate-400">{a.responsible}</td>
                          <td className="px-3 py-2 text-slate-600 dark:text-slate-400">{formatDate(a.dueDate)}</td>
                          <td className="px-3 py-2"><span className={`rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_ACTION[a.status].color}`}>{STATUS_ACTION[a.status].label}</span></td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                ) : (
                  actionItems.map((a, i) => (
                    <div key={a.id} className="grid grid-cols-12 gap-2 items-start border border-slate-200 dark:border-slate-700 rounded-xl p-3">
                      <div className="col-span-5">
                        <input value={a.text} onChange={e => setAction(i, 'text', e.target.value)}
                          placeholder="Descripción del compromiso"
                          className="w-full border border-slate-300 dark:border-slate-600 rounded-lg px-2 py-1.5 text-xs bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500" />
                      </div>
                      <div className="col-span-3">
                        <input value={a.responsible} onChange={e => setAction(i, 'responsible', e.target.value)}
                          placeholder="Responsable"
                          className="w-full border border-slate-300 dark:border-slate-600 rounded-lg px-2 py-1.5 text-xs bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500" />
                      </div>
                      <div className="col-span-3">
                        <input type="date" value={a.dueDate} onChange={e => setAction(i, 'dueDate', e.target.value)}
                          className="w-full border border-slate-300 dark:border-slate-600 rounded-lg px-2 py-1.5 text-xs bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500" />
                      </div>
                      <div className="col-span-1 flex justify-end">
                        <button type="button" onClick={() => removeAction(i)} className="text-slate-400 hover:text-red-500 text-lg leading-none">×</button>
                      </div>
                    </div>
                  ))
                )}
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="flex justify-between gap-3 p-6 border-t border-slate-200 dark:border-slate-700">
          <button onClick={onClose} className="border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-xl px-4 py-2.5 text-sm">Cerrar</button>
          {!isReadonly && (
            <div className="flex gap-3">
              <button onClick={handleSave} className="border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-xl px-4 py-2.5 text-sm">Guardar cambios</button>
              <button onClick={handleSign} className="bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors">Firmar y Distribuir</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Tab: Reuniones ───────────────────────────────────────────────────────────

function TabReuniones({ meetings, onNew, onView }) {
  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <button onClick={onNew} className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors">+ Nueva Reunión</button>
      </div>
      {meetings.length === 0 ? (
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-12 text-center">
          <p className="text-slate-500 dark:text-slate-400">No hay reuniones para el proyecto seleccionado.</p>
        </div>
      ) : (
        <div className="grid gap-4">
          {meetings.map(m => {
            const openActions = m.actionItems.filter(a => a.status !== 'COMPLETADO').length;
            const totalActions = m.actionItems.length;
            return (
              <div key={m.id} className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 p-6 flex flex-col md:flex-row md:items-center gap-4">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${MEETING_TYPES[m.type].color}`}>{MEETING_TYPES[m.type].label}</span>
                    <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_MEETING[m.status].color}`}>{STATUS_MEETING[m.status].label}</span>
                  </div>
                  <h3 className="font-semibold text-slate-900 dark:text-white text-base truncate">{m.title}</h3>
                  <div className="mt-1 flex flex-wrap gap-3 text-sm text-slate-500 dark:text-slate-400">
                    <span>{getProjectCode(m.projectId)}</span>
                    <span>·</span>
                    <span>{formatDate(m.date)}</span>
                    <span>·</span>
                    <span>{m.attendees.length} asistentes</span>
                    {totalActions > 0 && (
                      <>
                        <span>·</span>
                        <span className={openActions > 0 ? 'text-amber-600 dark:text-amber-400 font-medium' : ''}>
                          {openActions}/{totalActions} compromisos abiertos
                        </span>
                      </>
                    )}
                  </div>
                  {m.location && <p className="mt-1 text-xs text-slate-400 truncate">{m.location}</p>}
                </div>
                <button onClick={() => onView(m)} className="border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-xl px-4 py-2.5 text-sm whitespace-nowrap shrink-0">Ver Acta</button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── Tab: Compromisos Abiertos ────────────────────────────────────────────────

function TabCompromisos({ meetings, onComplete }) {
  const allOpen = useMemo(() => {
    const rows = [];
    meetings.forEach(m => {
      m.actionItems.forEach(a => {
        if (a.status === 'COMPLETADO') return;
        const days = daysRemaining(a.dueDate);
        const status = days < 0 ? 'VENCIDO' : a.status;
        rows.push({ ...a, status, days, meetingTitle: m.title, meetingId: m.id });
      });
    });
    rows.sort((a, b) => {
      if (a.status === 'VENCIDO' && b.status !== 'VENCIDO') return -1;
      if (b.status === 'VENCIDO' && a.status !== 'VENCIDO') return 1;
      return new Date(a.dueDate) - new Date(b.dueDate);
    });
    return rows;
  }, [meetings]);

  const overdue = allOpen.filter(a => a.status === 'VENCIDO').length;
  const dueThisWeek = allOpen.filter(a => a.days >= 0 && a.days <= 7).length;

  return (
    <div className="space-y-4">
      {/* Summary KPIs */}
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 p-5">
          <p className="text-xs text-slate-500 dark:text-slate-400 uppercase font-semibold tracking-wide mb-1">Compromisos abiertos</p>
          <p className="text-3xl font-bold text-slate-900 dark:text-white">{allOpen.length}</p>
        </div>
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 p-5">
          <p className="text-xs text-slate-500 dark:text-slate-400 uppercase font-semibold tracking-wide mb-1">Vencidos</p>
          <p className="text-3xl font-bold text-red-600 dark:text-red-400">{overdue}</p>
        </div>
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 p-5">
          <p className="text-xs text-slate-500 dark:text-slate-400 uppercase font-semibold tracking-wide mb-1">Vencen esta semana</p>
          <p className="text-3xl font-bold text-amber-600 dark:text-amber-400">{dueThisWeek}</p>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden">
        {allOpen.length === 0 ? (
          <div className="p-12 text-center">
            <p className="text-emerald-600 dark:text-emerald-400 font-medium">Sin compromisos abiertos. ¡Excelente trabajo!</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 dark:bg-slate-800/60">
                <tr>
                  <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">#</th>
                  <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Compromiso</th>
                  <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Responsable</th>
                  <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Reunión origen</th>
                  <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Fecha límite</th>
                  <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Estado</th>
                  <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Días restantes</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody>
                {allOpen.map((a, i) => (
                  <tr key={a.id} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                    <td className="px-4 py-3 text-slate-400">{i + 1}</td>
                    <td className="px-4 py-3 text-slate-800 dark:text-slate-200 max-w-[220px]">
                      <span className="line-clamp-2">{a.text}</span>
                    </td>
                    <td className="px-4 py-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">{a.responsible}</td>
                    <td className="px-4 py-3 text-slate-500 dark:text-slate-400 max-w-[160px]">
                      <span className="line-clamp-1 text-xs">{a.meetingTitle}</span>
                    </td>
                    <td className="px-4 py-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">{formatDate(a.dueDate)}</td>
                    <td className="px-4 py-3">
                      <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_ACTION[a.status].color}`}>{STATUS_ACTION[a.status].label}</span>
                    </td>
                    <td className="px-4 py-3">
                      {a.days < 0
                        ? <span className="text-red-600 dark:text-red-400 font-semibold">{Math.abs(a.days)}d vencido</span>
                        : a.days === 0
                          ? <span className="text-amber-600 dark:text-amber-400 font-semibold">Hoy</span>
                          : <span className="text-slate-600 dark:text-slate-400">{a.days}d</span>
                      }
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => onComplete(a.meetingId, a.id)}
                        className="text-xs text-emerald-600 dark:text-emerald-400 hover:underline whitespace-nowrap">
                        Marcar completado
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Tab: Calendario ──────────────────────────────────────────────────────────

function TabCalendario({ meetings, onNew }) {
  const [current, setCurrent] = useState(() => {
    const d = new Date();
    return { year: d.getFullYear(), month: d.getMonth() };
  });
  const [selectedDay, setSelectedDay] = useState(null);

  const { year, month } = current;
  const monthName = new Date(year, month, 1).toLocaleDateString('es-ES', { month: 'long', year: 'numeric' });

  function prevMonth() {
    setCurrent(c => c.month === 0 ? { year: c.year - 1, month: 11 } : { year: c.year, month: c.month - 1 });
    setSelectedDay(null);
  }
  function nextMonth() {
    setCurrent(c => c.month === 11 ? { year: c.year + 1, month: 0 } : { year: c.year, month: c.month + 1 });
    setSelectedDay(null);
  }

  const firstDow = new Date(year, month, 1).getDay(); // 0=Sun
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const startOffset = (firstDow + 6) % 7; // Monday-based

  const meetingsByDay = useMemo(() => {
    const map = {};
    meetings.forEach(m => {
      const d = new Date(m.date + 'T12:00:00');
      if (d.getFullYear() === year && d.getMonth() === month) {
        const day = d.getDate();
        if (!map[day]) map[day] = [];
        map[day].push(m);
      }
    });
    return map;
  }, [meetings, year, month]);

  const selectedMeetings = selectedDay ? (meetingsByDay[selectedDay] || []) : [];
  const todayDate = new Date();

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <button onClick={onNew} className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors">+ Agendar Reunión</button>
      </div>
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 p-6">
        {/* Nav */}
        <div className="flex items-center justify-between mb-4">
          <button onClick={prevMonth} className="text-slate-500 hover:text-slate-800 dark:hover:text-white px-2 py-1 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-lg">‹</button>
          <h3 className="text-base font-semibold text-slate-900 dark:text-white capitalize">{monthName}</h3>
          <button onClick={nextMonth} className="text-slate-500 hover:text-slate-800 dark:hover:text-white px-2 py-1 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-lg">›</button>
        </div>
        {/* Day headers */}
        <div className="grid grid-cols-7 gap-1 mb-1">
          {['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'].map(d => (
            <div key={d} className="text-center text-xs font-semibold text-slate-500 dark:text-slate-400 py-2">{d}</div>
          ))}
        </div>
        {/* Grid */}
        <div className="grid grid-cols-7 gap-1">
          {Array.from({ length: startOffset }).map((_, i) => <div key={'e' + i} />)}
          {Array.from({ length: daysInMonth }).map((_, i) => {
            const day = i + 1;
            const isToday = todayDate.getFullYear() === year && todayDate.getMonth() === month && todayDate.getDate() === day;
            const hasMeetings = meetingsByDay[day];
            const isSelected = selectedDay === day;
            return (
              <button
                key={day}
                onClick={() => setSelectedDay(isSelected ? null : day)}
                className={`relative rounded-xl p-2 min-h-[52px] flex flex-col items-center text-sm transition-colors
                  ${isSelected ? 'bg-blue-600 text-white' : isToday ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 font-bold' : 'hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-300'}
                `}
              >
                <span className={`font-medium ${isToday && !isSelected ? 'ring-2 ring-blue-500 rounded-full w-6 h-6 flex items-center justify-center' : ''}`}>{day}</span>
                {hasMeetings && (
                  <div className="flex gap-0.5 mt-1 flex-wrap justify-center">
                    {hasMeetings.slice(0, 3).map(m => (
                      <span key={m.id} className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: isSelected ? 'white' : TYPE_DOT_COLORS[m.type] }} />
                    ))}
                  </div>
                )}
              </button>
            );
          })}
        </div>

        {/* Legend */}
        <div className="flex flex-wrap gap-3 mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
          {Object.entries(MEETING_TYPES).map(([k, v]) => (
            <span key={k} className="flex items-center gap-1.5 text-xs text-slate-500 dark:text-slate-400">
              <span className="w-2 h-2 rounded-full" style={{ backgroundColor: TYPE_DOT_COLORS[k] }} />
              {v.label}
            </span>
          ))}
        </div>
      </div>

      {/* Selected day meetings */}
      {selectedDay && (
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-surface-700 p-6">
          <h3 className="font-semibold text-slate-900 dark:text-white mb-3">
            Reuniones del {selectedDay} de {new Date(year, month).toLocaleDateString('es-ES', { month: 'long' })}
          </h3>
          {selectedMeetings.length === 0 ? (
            <p className="text-sm text-slate-400">Sin reuniones este día.</p>
          ) : (
            <div className="space-y-2">
              {selectedMeetings.map(m => (
                <div key={m.id} className="flex items-center gap-3 p-3 rounded-xl border border-slate-100 dark:border-slate-800">
                  <span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ backgroundColor: TYPE_DOT_COLORS[m.type] }} />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate">{m.title}</p>
                    <p className="text-xs text-slate-500 dark:text-slate-400">{getProjectCode(m.projectId)} · {m.attendees.length} asistentes</p>
                  </div>
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_MEETING[m.status].color}`}>{STATUS_MEETING[m.status].label}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

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

const TABS = ['Reuniones', 'Compromisos Abiertos', 'Calendario'];

export default function MeetingsPage() {
  const { selectedProjectId } = useProject();
  const [meetings, setMeetings] = useState(INITIAL_MEETINGS);
  const [activeTab, setActiveTab] = useState(0);
  const [showNewModal, setShowNewModal] = useState(false);
  const [detailMeeting, setDetailMeeting] = useState(null);

  const filteredMeetings = useMemo(
    () => meetings.filter(m => !selectedProjectId || m.projectId === selectedProjectId),
    [meetings, selectedProjectId]
  );

  function handleSaveNew(m) {
    setMeetings(prev => [m, ...prev]);
  }

  function handleUpdateMeeting(updated) {
    setMeetings(prev => prev.map(m => m.id === updated.id ? updated : m));
  }

  function handleComplete(meetingId, actionId) {
    setMeetings(prev => prev.map(m => {
      if (m.id !== meetingId) return m;
      return { ...m, actionItems: m.actionItems.map(a => a.id === actionId ? { ...a, status: 'COMPLETADO' } : a) };
    }));
  }

  const openCount = useMemo(() => {
    return filteredMeetings.reduce((acc, m) => acc + m.actionItems.filter(a => a.status !== 'COMPLETADO').length, 0);
  }, [filteredMeetings]);

  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">
        {/* Page header */}
        <div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Actas de Reunión</h1>
          <p className="text-slate-500 dark:text-slate-400 mt-1 text-sm">
            {filteredMeetings.length} reuniones · {openCount} compromisos abiertos
            {selectedProjectId && ` · ${getProjectName(selectedProjectId)}`}
          </p>
        </div>

        {/* Tabs */}
        <div className="border-b border-slate-200 dark:border-slate-700">
          <nav className="flex gap-6">
            {TABS.map((tab, i) => (
              <button
                key={tab}
                onClick={() => setActiveTab(i)}
                className={`pb-3 text-sm font-medium transition-colors ${
                  activeTab === i
                    ? 'border-b-2 border-blue-600 text-blue-600 dark:text-blue-400'
                    : 'border-b-2 border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
                }`}
              >
                {tab}
                {tab === 'Compromisos Abiertos' && openCount > 0 && (
                  <span className="ml-2 bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 rounded-full px-1.5 py-0.5 text-xs font-semibold">{openCount}</span>
                )}
              </button>
            ))}
          </nav>
        </div>

        {/* Tab content */}
        {activeTab === 0 && (
          <TabReuniones
            meetings={filteredMeetings}
            onNew={() => setShowNewModal(true)}
            onView={m => setDetailMeeting(m)}
          />
        )}
        {activeTab === 1 && (
          <TabCompromisos
            meetings={filteredMeetings}
            onComplete={handleComplete}
          />
        )}
        {activeTab === 2 && (
          <TabCalendario
            meetings={filteredMeetings}
            onNew={() => setShowNewModal(true)}
          />
        )}
      </div>

      {/* Modals */}
      {showNewModal && (
        <NewMeetingModal
          onClose={() => setShowNewModal(false)}
          onSave={handleSaveNew}
        />
      )}
      {detailMeeting && (
        <MeetingDetailModal
          meeting={meetings.find(m => m.id === detailMeeting.id) || detailMeeting}
          onClose={() => setDetailMeeting(null)}
          onUpdate={handleUpdateMeeting}
        />
      )}
    </div>
  );
}
