// ============================================================
// Publicar BD — exportación real CSV, XLSX y SQL
// ============================================================
const Publicacion = () => {
  const [data, setData] = useState({ status: 'loading', stats: {}, preview: {}, error: '' });
  const [formats, setFormats] = useState({ finished_books: 'xlsx', user_participation: 'xlsx' });
  const [downloading, setDownloading] = useState('');
  const [message, setMessage] = useState(null);

  const baseUrl = window.APP_CONFIG.API_BASE_URL.replace(/\/$/, '');

  const load = async () => {
    setData(previous => ({ ...previous, status: 'loading', error: '' }));
    try {
      const response = await apiRequest('publication/dashboard.php');
      setData({
        status: 'loaded',
        stats: response.data?.stats || {},
        preview: response.data?.preview || {},
        error: '',
      });
    } catch (error) {
      setData(previous => ({ ...previous, status: 'error', error: error.message || 'No fue posible cargar Publicar BD.' }));
    }
  };

  useEffect(() => { load(); }, []);

  const fileNameFromHeader = (header, fallback) => {
    const utf8 = header.match(/filename\*=UTF-8''([^;]+)/i);
    if (utf8) return decodeURIComponent(utf8[1]);
    const simple = header.match(/filename="?([^";]+)"?/i);
    return simple ? simple[1] : fallback;
  };

  const download = async (report) => {
    const format = formats[report];
    const key = `${report}-${format}`;
    setDownloading(key);
    setMessage(null);
    try {
      const response = await fetch(`${baseUrl}/publication/export.php?report=${encodeURIComponent(report)}&format=${encodeURIComponent(format)}`, {
        method: 'GET',
        credentials: 'include',
        cache: 'no-store',
      });
      if (!response.ok) {
        let text = `No fue posible generar el archivo. HTTP ${response.status}`;
        try {
          const payload = await response.json();
          text = payload.message || text;
          if (payload.errors?.[0]?.message) text += ` ${payload.errors[0].message}`;
        } catch (error) {}
        throw new Error(text);
      }
      const blob = await response.blob();
      const fallback = `${report}_${new Date().toISOString().slice(0,19).replaceAll(':','-')}.${format}`;
      const fileName = fileNameFromHeader(response.headers.get('content-disposition') || '', fallback);
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = fileName;
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1500);
      setMessage({ tone: 'success', text: `Exportación generada: ${fileName}` });
    } catch (error) {
      setMessage({ tone: 'error', text: error.message || 'No fue posible descargar la exportación.' });
    } finally {
      setDownloading('');
    }
  };

  const formatSelector = (report) => (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
      {['csv','xlsx','sql'].map(format => (
        <button
          key={format}
          type="button"
          className={`check ${formats[report] === format ? 'checked' : ''}`}
          style={{ justifyContent: 'center', padding: '12px 6px' }}
          onClick={() => setFormats(previous => ({ ...previous, [report]: format }))}
        >
          <strong>{format.toUpperCase()}</strong>
        </button>
      ))}
    </div>
  );

  const booksPreview = data.preview.finished_books || [];
  const usersPreview = data.preview.user_participation || [];

  return <div className="stack">
    {message && <div role="alert" style={{ padding: 12, borderRadius: 8, background: message.tone === 'success' ? '#f0fdf4' : '#fef2f2', color: message.tone === 'success' ? '#166534' : '#991b1b' }}>{message.text}</div>}
    {data.error && <div role="alert" style={{ padding: 12, borderRadius: 8, background: '#fef2f2', color: '#991b1b' }}>{data.error}</div>}

    <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
      <KPI label="Libros registrados" value={Number(data.stats.total_books || 0)} sub="Total en MySQL" tone="primary" />
      <KPI label="Libros terminados" value={Number(data.stats.finished_books || 0)} sub="Finalizados y publicados" tone="success" />
      <KPI label="Participaciones" value={Number(data.stats.participations || 0)} sub="Asignaciones de usuarios" tone="amber" />
    </div>

    <div className="stat-grid grid-2">
      <div className="card">
        <div className="card-header">
          <Icon name="library" size={17} />
          <div><div className="card-title">Libros terminados</div><div className="card-subtitle">Todos los campos, rutas y cantidades reales de archivos</div></div>
        </div>
        <div className="card-body">
          <div className="detail-section" style={{ marginBottom: 16 }}>
            <div className="detail-grid">
              <div><div className="detail-label">Registros</div><div className="detail-value text-serif" style={{ fontSize: 28 }}>{Number(data.stats.finished_books || 0)}</div></div>
              <div><div className="detail-label">Criterio</div><div className="detail-value">Estado completed · etapa published</div></div>
            </div>
          </div>
          <div className="field-label mb-8">Formato de salida</div>
          {formatSelector('finished_books')}
          <div className="field-help mt-12">Incluye campos de books, proyecto, rutas de Digitalización, Edición y FINALIZADO, conteos registrados y conteos físicos reales.</div>
          <button className="btn btn-primary btn-lg mt-16" style={{ width: '100%', justifyContent: 'center' }} disabled={downloading !== '' || Number(data.stats.finished_books || 0) < 1} onClick={() => download('finished_books')}>
            {downloading.startsWith('finished_books') ? 'Generando archivo…' : `Exportar libros terminados en ${formats.finished_books.toUpperCase()}`}
          </button>
        </div>
      </div>

      <div className="card">
        <div className="card-header">
          <Icon name="users" size={17} />
          <div><div className="card-title">Usuarios participantes</div><div className="card-subtitle">Libros y usuarios que intervinieron en cada proceso</div></div>
        </div>
        <div className="card-body">
          <div className="detail-section" style={{ marginBottom: 16 }}>
            <div className="detail-grid">
              <div><div className="detail-label">Participaciones</div><div className="detail-value text-serif" style={{ fontSize: 28 }}>{Number(data.stats.participations || 0)}</div></div>
              <div><div className="detail-label">Procesos</div><div className="detail-value">Digitalización · Edición · Calidad · Conversión</div></div>
            </div>
          </div>
          <div className="field-label mb-8">Formato de salida</div>
          {formatSelector('user_participation')}
          <div className="field-help mt-12">Incluye libro, proceso, usuario, perfiles, asignación, inicio, conclusión, estado y observaciones.</div>
          <button className="btn btn-primary btn-lg mt-16" style={{ width: '100%', justifyContent: 'center' }} disabled={downloading !== '' || Number(data.stats.participations || 0) < 1} onClick={() => download('user_participation')}>
            {downloading.startsWith('user_participation') ? 'Generando archivo…' : `Exportar participación en ${formats.user_participation.toUpperCase()}`}
          </button>
        </div>
      </div>
    </div>

    <div className="card">
      <div className="card-header"><Icon name="check_shield" size={16}/><div><div className="card-title">Vista previa · libros terminados</div><div className="card-subtitle">Primeros cinco registros encontrados</div></div></div>
      <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}><table className="data"><thead><tr><th>Inventario</th><th>Título</th><th>Serie</th><th>Ruta final</th><th style={{textAlign:'right'}}>Digitalizadas</th><th style={{textAlign:'right'}}>Editadas</th><th style={{textAlign:'right'}}>Archivos finales</th></tr></thead><tbody>
        {booksPreview.map(row => <tr key={row.id}><td className="text-mono">{row.inventory_number}</td><td><strong>{row.title}</strong><div className="text-xs text-3">{row.author || '—'}</div></td><td>{row.series_collection || '—'}</td><td className="text-xs text-mono" style={{maxWidth:340,whiteSpace:'normal'}}>{row.final_path || '—'}</td><td style={{textAlign:'right'}}>{Number(row.digitalization_real_images || 0)}</td><td style={{textAlign:'right'}}>{Number(row.editing_real_images || 0)}</td><td style={{textAlign:'right'}}>{Number(row.real_final_total_files || 0)}</td></tr>)}
        {!booksPreview.length && <tr><td colSpan="7"><Empty icon="library" title="Sin libros terminados" subtitle="Los libros con estado completed y etapa published aparecerán aquí"/></td></tr>}
      </tbody></table></div>
    </div>

    <div className="card">
      <div className="card-header"><Icon name="users" size={16}/><div><div className="card-title">Vista previa · participación de usuarios</div><div className="card-subtitle">Primeras ocho participaciones</div></div></div>
      <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}><table className="data"><thead><tr><th>Libro</th><th>Proceso</th><th>Usuario</th><th>Perfil</th><th>Inicio</th><th>Conclusión</th><th>Estado</th></tr></thead><tbody>
        {usersPreview.map(row => <tr key={row.assignment_id}><td><span className="text-mono">#{row.inventory_number}</span><div className="text-xs text-3">{row.title}</div></td><td>{row.process_stage}</td><td><strong>{row.user_name}</strong><div className="text-xs text-3">@{row.username}</div></td><td>{row.user_roles || '—'}</td><td>{row.started_at || row.assigned_at || '—'}</td><td>{row.completed_at || '—'}</td><td>{row.assignment_status}</td></tr>)}
        {!usersPreview.length && <tr><td colSpan="7"><Empty icon="users" title="Sin participaciones" subtitle="No existen asignaciones relacionadas con libros terminados"/></td></tr>}
      </tbody></table></div>
    </div>
  </div>;
};

Object.assign(window, { Publicacion });
