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

const MOCK_PROJECTS = [
  { id: 'p4', code: 'PRY-2026-004', name: 'Construcción AR-ProjectManagement Norte', client: 'Inmobiliaria Del Valle' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement "Horizontes"', client: 'Sony Music Latin' },
  { id: 'p4', code: 'PRY-2026-004', name: 'Implementación AR-ProjectManagement', client: 'Grupo Empresarial XYZ' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement — Plataforma ERP', client: 'AR Electronics' },
];

const TEMPLATES = [
  {
    id: 't1', name: 'Reporte Ejecutivo', description: 'KPIs generales, RAG, avance general del proyecto.',
    formats: ['PDF'], icon: 'chart-bar', color: 'blue',
    sections: ['Resumen Ejecutivo', 'KPIs Principales', 'Estado RAG', 'Avance por Fase'],
  },
  {
    id: 't2', name: 'Informe Financiero', description: 'P&L, flujo de caja y métricas EVM.',
    formats: ['PDF', 'CSV'], icon: 'currency-dollar', color: 'green',
    sections: ['P&L', 'Flujo de Caja', 'EVM (CPI/SPI)', 'Presupuesto vs Real'],
  },
  {
    id: 't3', name: 'Acta de Reunión', description: 'Última acta firmada del proyecto.',
    formats: ['PDF'], icon: 'document-text', color: 'purple',
    sections: ['Asistentes', 'Agenda', 'Acuerdos', 'Compromisos', 'Próxima Reunión'],
  },
  {
    id: 't4', name: 'Cronograma (Gantt)', description: 'Tabla de tareas con fechas y responsables.',
    formats: ['PDF', 'CSV'], icon: 'calendar', color: 'amber',
    sections: ['Lista de Tareas', 'Fechas Inicio/Fin', 'Responsables', 'Estado', 'Dependencias'],
  },
  {
    id: 't5', name: 'Registro de Riesgos', description: 'Matriz de riesgos con impacto y probabilidad.',
    formats: ['PDF', 'CSV'], icon: 'exclamation-triangle', color: 'red',
    sections: ['Riesgos Identificados', 'Matriz Impacto/Probabilidad', 'Plan de Mitigación', 'Responsables'],
  },
  {
    id: 't6', name: 'Reporte de Calidad', description: 'Inspecciones, NCRs y Score QC del proyecto.',
    formats: ['PDF'], icon: 'shield-check', color: 'teal',
    sections: ['Inspecciones Realizadas', 'NCRs Abiertos', 'NCRs Cerrados', 'Score QC', 'Tendencias'],
  },
  {
    id: 't7', name: 'Control de Horas', description: 'Horas registradas por persona y proyecto.',
    formats: ['PDF', 'CSV'], icon: 'clock', color: 'orange',
    sections: ['Horas por Persona', 'Horas por Proyecto', 'Overtime', 'Comparativo Semanas'],
  },
  {
    id: 't8', name: 'Lecciones Aprendidas', description: 'Base de conocimiento exportable del proyecto.',
    formats: ['PDF', 'CSV'], icon: 'book-open', color: 'indigo',
    sections: ['Lecciones Positivas', 'Áreas de Mejora', 'Recomendaciones', 'Categorías'],
  },
];

const ICON_COLORS = {
  blue: 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400',
  green: 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400',
  purple: 'bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400',
  amber: 'bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400',
  red: 'bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400',
  teal: 'bg-teal-100 dark:bg-teal-900/30 text-teal-600 dark:text-teal-400',
  orange: 'bg-orange-100 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400',
  indigo: 'bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400',
};

function TemplateIcon({ type }) {
  const cls = 'w-6 h-6';
  if (type === 'chart-bar') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
    </svg>
  );
  if (type === 'currency-dollar') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );
  if (type === 'document-text') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <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>
  );
  if (type === 'calendar') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
    </svg>
  );
  if (type === 'exclamation-triangle') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
    </svg>
  );
  if (type === 'shield-check') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
    </svg>
  );
  if (type === 'clock') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );
  if (type === 'book-open') return (
    <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
    </svg>
  );
  return null;
}

const FORMAT_BADGE = {
  PDF: 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400',
  CSV: 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400',
};

function generateMockCSV(template, projectName) {
  const headers = {
    't1': ['Indicador', 'Valor', 'Meta', 'Estado'],
    't2': ['Concepto', 'Presupuesto', 'Real', 'Varianza', 'CPI'],
    't3': ['Ítem', 'Detalle', 'Responsable', 'Fecha'],
    't4': ['Tarea', 'Inicio', 'Fin', 'Responsable', 'Estado', '%'],
    't5': ['Riesgo', 'Probabilidad', 'Impacto', 'Score', 'Mitigación'],
    't6': ['Inspección', 'Fecha', 'Inspector', 'NCRs', 'Score'],
    't7': ['Persona', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Total'],
    't8': ['Categoría', 'Lección', 'Tipo', 'Prioridad'],
  };
  const rows = {
    't1': [
      ['Avance General', '67%', '70%', 'AMARILLO'],
      ['CPI', '0.94', '1.00', 'ROJO'],
      ['SPI', '0.98', '1.00', 'VERDE'],
      ['Riesgos Activos', '5', '<3', 'ROJO'],
    ],
    't2': [
      ['Mano de Obra', '$120,000', '$128,500', '-$8,500', '0.93'],
      ['Materiales', '$85,000', '$82,300', '$2,700', '1.03'],
      ['Subcontratos', '$45,000', '$44,200', '$800', '1.02'],
      ['Gastos Generales', '$30,000', '$31,500', '-$1,500', '0.95'],
    ],
    't3': [
      ['Fecha', '2026-06-20', '', ''],
      ['Asistentes', 'Paula Soto, Álvaro Romero, Álvaro Romero', '', ''],
      ['Acuerdo 1', 'Revisar cronograma semana 28', 'Paula Soto', '2026-06-27'],
      ['Acuerdo 2', 'Enviar informe financiero al cliente', 'Admin Sistema', '2026-06-25'],
    ],
    't4': [
      ['Diseño Arquitectónico', '2026-01-15', '2026-03-01', 'Paula Soto', 'COMPLETADA', '100'],
      ['Cimentación', '2026-03-05', '2026-04-20', 'Álvaro Romero', 'COMPLETADA', '100'],
      ['Estructura Pisos 1-5', '2026-04-21', '2026-07-15', 'Álvaro Romero', 'EN_PROCESO', '62'],
      ['Instalaciones MEP', '2026-06-01', '2026-09-30', 'Álvaro Romero', 'EN_PROCESO', '20'],
    ],
    't5': [
      ['Retraso en entrega de acero', 'Alta', 'Alto', '9', 'Proveedor alternativo identificado'],
      ['Incremento de costos materiales', 'Media', 'Alto', '6', 'Contingencia del 10% activada'],
      ['Condiciones climáticas adversas', 'Media', 'Medio', '4', 'Ajuste de calendario previsto'],
    ],
    't6': [
      ['INS-001', '2026-06-10', 'Álvaro Romero', '2', '88'],
      ['INS-002', '2026-06-17', 'Paula Soto', '0', '96'],
      ['INS-003', '2026-06-24', 'Álvaro Romero', '1', '92'],
    ],
    't7': MOCK_TEAM.slice(0, 5).map(m => [
      `${m.firstName} ${m.lastName}`, '8', '8', '7', '8', '8', '39',
    ]),
    't8': [
      ['Planificación', 'Definir alcance con stakeholders antes de iniciar', 'Positiva', 'Alta'],
      ['Comunicación', 'Reuniones semanales mejoran coordinación del equipo', 'Positiva', 'Media'],
      ['Riesgos', 'Identificar riesgos en fase temprana reduce impacto', 'Mejora', 'Alta'],
    ],
  };
  const h = headers[template.id] || ['Col1', 'Col2'];
  const r = rows[template.id] || [];
  const lines = [
    `# ${template.name} — ${projectName}`,
    `# Generado: ${new Date().toLocaleDateString('es-ES')}`,
    '',
    h.join(','),
    ...r.map(row => row.map(cell => `"${cell}"`).join(',')),
  ];
  return lines.join('\n');
}

function downloadCSV(content, filename) {
  const blob = new Blob(['﻿' + content], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function triggerPrint(template, projectName, dateFrom, dateTo) {
  const existing = document.getElementById('arpm-print-overlay');
  if (existing) existing.remove();

  const styleEl = document.createElement('style');
  styleEl.id = 'arpm-print-style';
  styleEl.setAttribute('media', 'print');
  styleEl.textContent = `
    @media print {
      body > *:not(#arpm-print-overlay) { display: none !important; }
      #arpm-print-overlay { display: block !important; position: static !important; }
    }
  `;
  document.head.appendChild(styleEl);

  const div = document.createElement('div');
  div.id = 'arpm-print-overlay';
  div.style.cssText = 'display:none;font-family:Arial,sans-serif;padding:40px;color:#111;';
  div.innerHTML = `
    <div style="display:flex;justify-content:space-between;align-items:center;border-bottom:3px solid #2563eb;padding-bottom:16px;margin-bottom:24px;">
      <div>
        <div style="font-size:22px;font-weight:700;color:#1e40af;">AR Electronics</div>
        <div style="font-size:13px;color:#6b7280;">AR-ProjectManagement Platform</div>
      </div>
      <div style="text-align:right;">
        <div style="font-size:18px;font-weight:600;">${template.name}</div>
        <div style="font-size:12px;color:#6b7280;">Generado: ${new Date().toLocaleDateString('es-ES', { day:'2-digit', month:'long', year:'numeric' })}</div>
      </div>
    </div>
    <table style="width:100%;border-collapse:collapse;margin-bottom:16px;">
      <tr>
        <td style="padding:6px 0;font-size:13px;color:#6b7280;width:120px;">Proyecto:</td>
        <td style="padding:6px 0;font-size:13px;font-weight:600;">${projectName}</td>
        <td style="padding:6px 0;font-size:13px;color:#6b7280;width:100px;">Período:</td>
        <td style="padding:6px 0;font-size:13px;">${dateFrom} — ${dateTo}</td>
      </tr>
    </table>
    <table style="width:100%;border-collapse:collapse;margin-top:24px;">
      <thead>
        <tr style="background:#eff6ff;">
          ${template.sections.map(s => `<th style="text-align:left;padding:10px 12px;font-size:11px;font-weight:700;color:#1e40af;border-bottom:2px solid #bfdbfe;text-transform:uppercase;">${s}</th>`).join('')}
        </tr>
      </thead>
      <tbody>
        ${[1,2,3,4].map((_, i) => `
          <tr style="border-bottom:1px solid #e5e7eb;${i%2===1?'background:#f9fafb;':''}">
            ${template.sections.map(() => `<td style="padding:10px 12px;font-size:12px;color:#374151;">— Dato de muestra —</td>`).join('')}
          </tr>
        `).join('')}
      </tbody>
    </table>
    <div style="margin-top:40px;padding-top:16px;border-top:1px solid #e5e7eb;display:flex;justify-content:space-between;font-size:11px;color:#9ca3af;">
      <span>AR Electronics — Confidencial</span>
      <span>Página 1 de 1</span>
    </div>
  `;
  document.body.appendChild(div);

  setTimeout(() => {
    window.print();
    setTimeout(() => {
      div.remove();
      styleEl.remove();
    }, 1000);
  }, 100);
}

function ConfigModal({ template, onClose, onGenerate }) {
  const [title, setTitle] = useState(template.name);
  const [projectId, setProjectId] = useState('all');
  const [dateFrom, setDateFrom] = useState('2026-01-01');
  const [dateTo, setDateTo] = useState('2026-12-31');
  const [format, setFormat] = useState(template.formats[0]);
  const [sections, setSections] = useState(Object.fromEntries(template.sections.map(s => [s, true])));
  const [preview, setPreview] = useState(false);

  const toggleSection = (s) => setSections(prev => ({ ...prev, [s]: !prev[s] }));
  const projectName = projectId === 'all'
    ? 'Todos los proyectos'
    : MOCK_PROJECTS.find(p => p.id === projectId)?.name || '';

  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 border border-slate-200 dark:border-slate-700 shadow-2xl 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">
          <div className="flex items-center gap-3">
            <div className={`p-2 rounded-xl ${ICON_COLORS[template.color]}`}>
              <TemplateIcon type={template.icon} />
            </div>
            <div>
              <h2 className="text-lg font-bold text-slate-900 dark:text-white">Configurar Reporte</h2>
              <p className="text-sm text-slate-500 dark:text-slate-400">{template.name}</p>
            </div>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200">
            <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>

        <div className="p-6 space-y-5">
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1.5">Título del reporte</label>
            <input
              type="text"
              value={title}
              onChange={e => setTitle(e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white text-sm focus: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.5">Proyecto</label>
            <select
              value={projectId}
              onChange={e => setProjectId(e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">Todos los proyectos</option>
              {MOCK_PROJECTS.map(p => (
                <option key={p.id} value={p.id}>{p.code} — {p.name}</option>
              ))}
            </select>
          </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.5">Desde</label>
              <input
                type="date"
                value={dateFrom}
                onChange={e => setDateFrom(e.target.value)}
                className="w-full px-3 py-2 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white text-sm focus: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.5">Hasta</label>
              <input
                type="date"
                value={dateTo}
                onChange={e => setDateTo(e.target.value)}
                className="w-full px-3 py-2 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          {template.formats.length > 1 && (
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1.5">Formato</label>
              <div className="flex gap-2">
                {['PDF', 'CSV', 'Ambos'].filter(f => {
                  if (f === 'Ambos') return template.formats.length === 2;
                  return template.formats.includes(f);
                }).map(f => (
                  <button
                    key={f}
                    onClick={() => setFormat(f)}
                    className={`px-4 py-2 rounded-xl text-sm font-medium border transition-colors ${
                      format === f
                        ? 'bg-blue-600 text-white border-blue-600'
                        : 'bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 border-slate-200 dark:border-slate-700 hover:border-blue-400'
                    }`}
                  >
                    {f}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Secciones a incluir</label>
            <div className="grid grid-cols-2 gap-2">
              {template.sections.map(s => (
                <label key={s} className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={sections[s]}
                    onChange={() => toggleSection(s)}
                    className="w-4 h-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-slate-700 dark:text-slate-300">{s}</span>
                </label>
              ))}
            </div>
          </div>

          <div>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={preview}
                onChange={e => setPreview(e.target.checked)}
                className="w-4 h-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="text-sm font-medium text-slate-700 dark:text-slate-300">Vista previa</span>
            </label>

            {preview && (
              <div className="mt-3 rounded-xl border-2 border-dashed border-slate-300 dark:border-slate-600 bg-slate-50 dark:bg-slate-800/50 p-6">
                <div className="flex items-center justify-between mb-3 pb-3 border-b border-slate-200 dark:border-slate-700">
                  <div>
                    <div className="text-base font-bold text-blue-700 dark:text-blue-400">AR Electronics</div>
                    <div className="text-xs text-slate-500">AR-ProjectManagement Platform</div>
                  </div>
                  <div className="text-right">
                    <div className="text-sm font-semibold text-slate-800 dark:text-slate-200">{title}</div>
                    <div className="text-xs text-slate-500">{projectName}</div>
                  </div>
                </div>
                <div className="space-y-1.5">
                  {Object.entries(sections).filter(([,v]) => v).map(([s]) => (
                    <div key={s} className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-blue-400 flex-shrink-0" />
                      <div className="h-2.5 bg-slate-200 dark:bg-slate-700 rounded flex-1" style={{ width: `${50 + Math.random()*40}%` }} />
                      <span className="text-xs text-slate-400">{s}</span>
                    </div>
                  ))}
                </div>
                <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-700 text-xs text-slate-400 flex justify-between">
                  <span>Vista previa — datos de muestra</span>
                  <span>{dateFrom} / {dateTo}</span>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="flex items-center justify-end gap-3 p-6 border-t border-slate-200 dark:border-slate-700">
          <button
            onClick={onClose}
            className="px-4 py-2.5 rounded-xl text-sm font-medium text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800"
          >
            Cancelar
          </button>
          <button
            onClick={() => onGenerate({ template, title, projectId, projectName, dateFrom, dateTo, format, sections })}
            className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium flex items-center gap-2"
          >
            <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>
            Generar Reporte
          </button>
        </div>
      </div>
    </div>
  );
}

function ProgressToast({ title, onDone }) {
  const [progress, setProgress] = useState(0);

  useState(() => {
    const interval = setInterval(() => {
      setProgress(p => {
        if (p >= 100) { clearInterval(interval); setTimeout(onDone, 400); return 100; }
        return p + 5;
      });
    }, 100);
    return () => clearInterval(interval);
  });

  return (
    <div className="fixed bottom-6 right-6 z-50 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-2xl shadow-2xl p-5 w-80">
      <div className="flex items-center gap-3 mb-3">
        <div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
          <svg className="w-4 h-4 text-blue-600 dark:text-blue-400 animate-spin" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-sm font-semibold text-slate-900 dark:text-white truncate">{title}</div>
          <div className="text-xs text-slate-500 dark:text-slate-400">Generando reporte...</div>
        </div>
      </div>
      <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-2">
        <div
          className="bg-blue-600 h-2 rounded-full transition-all duration-100"
          style={{ width: `${progress}%` }}
        />
      </div>
      <div className="text-right text-xs text-slate-500 dark:text-slate-400 mt-1">{progress}%</div>
    </div>
  );
}

const STATUS_STYLES = {
  LISTO: 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400',
  GENERANDO: 'bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400',
  ERROR: 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400',
};

export default function PDFExportPage() {
  const { selectedProjectId } = useProject();
  const [activeTemplate, setActiveTemplate] = useState(null);
  const [generating, setGenerating] = useState(null);
  const [exports, setExports] = useState([
    {
      id: 'e0', name: 'Reporte Ejecutivo — Junio 2026', project: 'PRY-2026-004',
      format: 'PDF', generatedBy: 'Admin Sistema',
      date: '2026-06-20', status: 'LISTO',
      template: TEMPLATES[0], projectName: 'AR-ProjectManagement — Plataforma ERP',
      dateFrom: '2026-06-01', dateTo: '2026-06-30',
    },
    {
      id: 'e1', name: 'Informe Financiero Q2', project: 'PRY-2026-004',
      format: 'PDF + CSV', generatedBy: 'Álvaro Romero',
      date: '2026-06-15', status: 'LISTO',
      template: TEMPLATES[1], projectName: 'Construcción AR-ProjectManagement Norte',
      dateFrom: '2026-04-01', dateTo: '2026-06-30',
    },
    {
      id: 'e2', name: 'Registro de Riesgos', project: 'PRY-2026-004',
      format: 'CSV', generatedBy: 'Paula Soto',
      date: '2026-06-10', status: 'ERROR',
      template: TEMPLATES[4], projectName: 'Implementación AR-ProjectManagement',
      dateFrom: '2026-01-01', dateTo: '2026-06-10',
    },
  ]);

  const filteredExports = useMemo(() =>
    !selectedProjectId
      ? exports
      : exports.filter(e =>
          MOCK_PROJECTS.find(p => p.id === selectedProjectId)?.code === e.project
        ),
    [exports, selectedProjectId]
  );

  const handleGenerate = useCallback((config) => {
    setActiveTemplate(null);
    setGenerating(config);
  }, []);

  const handleGenerateDone = useCallback(() => {
    const config = generating;
    setGenerating(null);
    const newExport = {
      id: `e${Date.now()}`,
      name: config.title,
      project: MOCK_PROJECTS.find(p => p.id === config.projectId)?.code || 'Todos',
      format: config.format === 'Ambos' ? 'PDF + CSV' : config.format,
      generatedBy: 'Admin Sistema',
      date: new Date().toISOString().slice(0, 10),
      status: 'LISTO',
      template: config.template,
      projectName: config.projectName,
      dateFrom: config.dateFrom,
      dateTo: config.dateTo,
    };
    setExports(prev => [newExport, ...prev]);
  }, [generating]);

  const handleDownload = useCallback((exp) => {
    const fmt = exp.format;
    const doPDF = fmt === 'PDF' || fmt === 'PDF + CSV';
    const doCSV = fmt === 'CSV' || fmt === 'PDF + CSV';

    if (doPDF) {
      triggerPrint(exp.template, exp.projectName, exp.dateFrom, exp.dateTo);
    }
    if (doCSV) {
      const csv = generateMockCSV(exp.template, exp.projectName);
      const filename = `${exp.name.replace(/[^a-z0-9]/gi, '_')}.csv`;
      downloadCSV(csv, filename);
    }
  }, []);

  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 items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Exportación de Reportes</h1>
            <p className="text-slate-500 dark:text-slate-400 text-sm mt-0.5">Genera y descarga reportes profesionales en PDF y CSV</p>
          </div>
          <div className="flex items-center gap-2 text-sm text-slate-500 dark:text-slate-400">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <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>
            <span>{exports.length} reportes generados</span>
          </div>
        </div>

        {/* Templates Gallery */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
          <h2 className="text-base font-bold text-slate-900 dark:text-white mb-4">Plantillas de Reporte</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {TEMPLATES.map(t => (
              <div
                key={t.id}
                className="flex flex-col border border-slate-200 dark:border-slate-700 rounded-xl p-4 hover:border-blue-400 dark:hover:border-blue-500 hover:shadow-md transition-all group"
              >
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center mb-3 ${ICON_COLORS[t.color]}`}>
                  <TemplateIcon type={t.icon} />
                </div>
                <div className="font-semibold text-slate-900 dark:text-white text-sm mb-1">{t.name}</div>
                <div className="text-xs text-slate-500 dark:text-slate-400 mb-3 flex-1">{t.description}</div>
                <div className="flex items-center gap-1.5 mb-3">
                  {t.formats.map(f => (
                    <span key={f} className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${FORMAT_BADGE[f]}`}>
                      {f}
                    </span>
                  ))}
                </div>
                <button
                  onClick={() => setActiveTemplate(t)}
                  className="w-full bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-3 py-2 text-xs font-medium transition-colors"
                >
                  Configurar y Exportar
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Recent Exports */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
          <h2 className="text-base font-bold text-slate-900 dark:text-white mb-4">Exportaciones Recientes</h2>
          {filteredExports.length === 0 ? (
            <div className="text-center py-10 text-slate-400 dark:text-slate-500">
              <svg className="w-10 h-10 mx-auto mb-3 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 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 exportaciones para el proyecto seleccionado</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-slate-200 dark:border-slate-700">
                    <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Reporte</th>
                    <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Proyecto</th>
                    <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Formato</th>
                    <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Generado por</th>
                    <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Fecha</th>
                    <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Estado</th>
                    <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Acción</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredExports.map(exp => (
                    <tr key={exp.id} className="border-b border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50">
                      <td className="px-4 py-3">
                        <div className="text-sm font-medium text-slate-900 dark:text-white">{exp.name}</div>
                      </td>
                      <td className="px-4 py-3">
                        <span className="text-xs font-mono bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 px-2 py-0.5 rounded">
                          {exp.project}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex gap-1 flex-wrap">
                          {exp.format.split(' + ').map(f => (
                            <span key={f} className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${FORMAT_BADGE[f] || 'bg-slate-100 text-slate-600'}`}>
                              {f}
                            </span>
                          ))}
                        </div>
                      </td>
                      <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-300">{exp.generatedBy}</td>
                      <td className="px-4 py-3 text-sm text-slate-500 dark:text-slate-400">{exp.date}</td>
                      <td className="px-4 py-3">
                        <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_STYLES[exp.status]}`}>
                          {exp.status}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        {exp.status === 'LISTO' ? (
                          <button
                            onClick={() => handleDownload(exp)}
                            className="flex items-center gap-1.5 text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 text-sm font-medium"
                          >
                            <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>
                        ) : exp.status === 'ERROR' ? (
                          <button className="text-red-500 dark:text-red-400 text-sm font-medium hover:underline">Reintentar</button>
                        ) : (
                          <span className="text-slate-400 dark:text-slate-500 text-sm">En proceso...</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {activeTemplate && (
        <ConfigModal
          template={activeTemplate}
          onClose={() => setActiveTemplate(null)}
          onGenerate={handleGenerate}
        />
      )}

      {generating && (
        <ProgressToast
          title={generating.title}
          onDone={handleGenerateDone}
        />
      )}
    </div>
  );
}
