// ─────────────────────────────────────────────────────
// GUT-257: tipo de tarea en Programación (Medición, Dibujo, Fabricación…), orden por
// prioridad del proyecto y export a Excel de la pestaña Tareas. Se carga antes de
// programacion.jsx; usa PgEdit, PG_PRIORIDADES y PG_TIPOS_EVENTO de allí (solo al renderizar).
// ─────────────────────────────────────────────────────

// Lista de tipos compartida por toda la vista: se pide una vez y se avisa a quien la use
// cuando cambia en Configuración.
const pgTiposTareaStore = { list: null, subs: new Set(), pending: null };
const pgRecargarTiposTarea = () => {
  pgTiposTareaStore.pending = API.get('/api/programacion/tipos-tarea')
    .then((l) => { pgTiposTareaStore.list = l; pgTiposTareaStore.subs.forEach((f) => f(l)); return l; })
    .catch(() => pgTiposTareaStore.list || [])
    .finally(() => { pgTiposTareaStore.pending = null; });
  return pgTiposTareaStore.pending;
};
const usePgTiposTarea = () => {
  const [list, setList] = React.useState(pgTiposTareaStore.list || []);
  React.useEffect(() => {
    pgTiposTareaStore.subs.add(setList);
    if (pgTiposTareaStore.list) setList(pgTiposTareaStore.list); // pudo llegar entre el render y este efecto
    else if (!pgTiposTareaStore.pending) pgRecargarTiposTarea();
    return () => { pgTiposTareaStore.subs.delete(setList); };
  }, []);
  return list;
};

// Nombre del cliente sin repetir el nº: "7461. JACINTO…" con nº 22007461 → "JACINTO…".
const pgClienteNombre = (numero, nombre) => {
  const n = String(nombre || '');
  const m = /^(\d+)\s*[.,\-·]?\s*/.exec(n);
  return m && String(numero || '').endsWith(m[1]) && n.length > m[0].length ? n.slice(m[0].length) : n;
};

// Selector de tipo en línea. Los tipos dados de baja solo salen si la tarea ya lo tenía.
const PgTipoTareaSelect = ({ value, tipos, onSave, style }) => {
  const opts = tipos.filter((t) => t.activo || String(t.id) === String(value)).map((t) => [String(t.id), t.nombre + (t.activo ? '' : ' (baja)')]);
  const sel = tipos.find((t) => String(t.id) === String(value));
  return <PgEdit type="select" className="pg-pill" value={value == null ? '' : String(value)} options={opts}
    style={{ ...(sel?.color ? { background: sel.color, color: '#1f2937' } : {}), ...style }}
    onSave={(v) => onSave(v ? Number(v) : null)} />;
};

// Orden: 'fecha' (inicio, sin fecha al final) o 'prioridad' (prioridad del proyecto y luego fecha).
// Con `tipos` se agrupa además por tipo (orden de Configuración; "Sin tipo" al final).
const PG_PRIORIDAD_RANK = { 'MUY ALTA': 0, ALTA: 1, MEDIA: 2, NORMAL: 3, BAJA: 4 };
const pgOrdenTareas = (rows, orden, tipos) => {
  const tipoRank = tipos ? Object.fromEntries(tipos.map((t, i) => [t.id, i])) : null;
  const porFecha = (a, b) => (a.fecha || '9999') < (b.fecha || '9999') ? -1 : (a.fecha || '9999') > (b.fecha || '9999') ? 1
    : String(a.proyecto_numero || '').localeCompare(String(b.proyecto_numero || '')) || a.id - b.id;
  const prio = (r) => PG_PRIORIDAD_RANK[r.proyecto_prioridad] ?? 9;
  return [...rows].sort((a, b) => {
    if (tipoRank) { const d = (tipoRank[a.tipo_id] ?? 999) - (tipoRank[b.tipo_id] ?? 999); if (d) return d; }
    if (orden === 'prioridad') { const d = prio(a) - prio(b); if (d) return d; }
    return porFecha(a, b);
  });
};

// Descarga un Excel con las filas tal cual se ven (el servidor solo lo maqueta).
const pgDescargarExcel = async ({ titulo, hoja, columnas, filas }) => {
  const res = await API.request('/api/programacion/export/excel', { method: 'POST', body: { titulo, hoja, columnas, filas } });
  if (!res.ok) { let m = `HTTP ${res.status}`; try { m = (await res.json()).error || m; } catch {} throw new Error(m); }
  const blob = await res.blob();
  const cd = res.headers.get('Content-Disposition') || '';
  const name = (/filename="?([^";]+)"?/i.exec(cd) || [])[1] || `${titulo || 'listado'}.xlsx`;
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href = url; a.download = name;
  document.body.appendChild(a); a.click(); a.remove();
  URL.revokeObjectURL(url);
};
const PG_EXCEL_COLS = [
  { label: 'Proyecto nº', width: 12 }, { label: 'Cliente', width: 36 }, { label: 'Tipo', width: 22 }, { label: 'Tarea', width: 50 },
  { label: 'Inicio', width: 11 }, { label: 'Fin', width: 11 }, { label: 'Operarios', width: 28 }, { label: 'Estado', width: 11 },
  { label: 'Prioridad', width: 11 }, { label: 'Ubicación', width: 24 },
];
const pgUbic = (r) => [r.ubicacion, r.provincia].filter(Boolean).join(', ');
const PG_TAREA_ESTADO_TXT = { pdte: 'Pendiente', ok: 'OK', ko: 'KO' };
const PG_FECHA_ESTADO_TXT = { programado: 'Programado', hecho: 'Hecho', ko: 'KO' };
const pgExcelTareas = (rows, onToast) => pgDescargarExcel({
  titulo: 'tareas', hoja: 'Tareas', columnas: PG_EXCEL_COLS,
  filas: rows.map((t) => [t.proyecto_numero, pgClienteNombre(t.proyecto_numero, t.proyecto_nombre), t.tipo_nombre || '', t.tarea,
    pgFmtLong(t.fecha).replace('—', ''), pgFmtLong(t.fecha_fin || t.fecha).replace('—', ''), t.operario_nombre || '',
    PG_TAREA_ESTADO_TXT[t.estado] || t.estado, t.proyecto_prioridad || '', pgUbic(t)]),
}).catch((e) => onToast(e.message || 'Error al exportar', true));
const pgExcelFechas = (rows, onToast) => pgDescargarExcel({
  titulo: 'mediciones_y_visitas', hoja: 'Mediciones y visitas', columnas: PG_EXCEL_COLS,
  filas: rows.map((e) => [e.proyecto_numero, pgClienteNombre(e.proyecto_numero, e.proyecto_nombre), PG_TIPOS_EVENTO[e.tipo] || e.tipo, e.nota || '',
    pgFmtLong(e.fecha_inicio).replace('—', ''), pgFmtLong(e.fecha_fin).replace('—', ''), e.instalador_nombre || '',
    PG_FECHA_ESTADO_TXT[e.estado] || e.estado, e.proyecto_prioridad || '', pgUbic(e)]),
}).catch((e) => onToast(e.message || 'Error al exportar', true));

// Programación › Configuración › Tipos de tarea (mismo patrón que Instaladores).
const PgTiposTareaConfig = ({ onToast }) => {
  const tipos = usePgTiposTarea();
  const [nuevo, setNuevo] = React.useState('');
  const err = (e) => onToast(e.message, true);
  const patch = (id, body) => API.patch(`/api/programacion/tipos-tarea/${id}`, body).then(pgRecargarTiposTarea).catch(err);
  const add = () => API.post('/api/programacion/tipos-tarea', { nombre: nuevo.trim(), color: '#e5e7eb' })
    .then(() => { setNuevo(''); pgRecargarTiposTarea(); onToast('Tipo de tarea creado ✓'); }).catch(err);
  const del = (t) => confirm(`¿Eliminar el tipo "${t.nombre}"? Las tareas que lo tengan se quedarán sin tipo. Si solo quieres que no salga, desmarca "Activo".`)
    && API.del(`/api/programacion/tipos-tarea/${t.id}`).then(pgRecargarTiposTarea).catch(err);
  return (
    <>
      <div className="section-title" style={{ marginTop: 24 }}>Tipos de tarea</div>
      <div className="tbl-wrap"><div className="tbl-scroll" style={{ maxHeight: 'none' }}><table className="tbl tbl-compact pg-tbl">
        <thead><tr><th style={{ width: 40 }}>Color</th><th>Nombre</th><th style={{ width: 60 }}>Orden</th><th style={{ width: 55 }}>Activo</th><th /></tr></thead>
        <tbody>
          {tipos.map((t) => (
            <tr key={t.id} className={`pg-row ${t.activo ? '' : 'pg-done'}`}>
              <td><input type="color" className="pg-color" value={t.color || '#e5e7eb'} onChange={(e) => patch(t.id, { color: e.target.value })} /></td>
              <td className="strong"><PgEdit value={t.nombre} onSave={(v) => v && patch(t.id, { nombre: v })} /></td>
              <td><PgEdit type="num" value={t.orden} onSave={(v) => patch(t.id, { orden: v || 0 })} /></td>
              <td style={{ textAlign: 'center' }}><PgEdit type="check" value={t.activo} onSave={(v) => patch(t.id, { activo: v })} /></td>
              <td><button className="icon-btn" onClick={() => del(t)}><Icon name="trash" size={12} /></button></td>
            </tr>
          ))}
        </tbody>
      </table></div></div>
      <div className="pg-addrow" style={{ marginTop: 10 }}>
        <input placeholder="Nuevo tipo (p. ej. Repaso)" value={nuevo} onChange={(e) => setNuevo(e.target.value)} style={{ flex: 1 }} onKeyDown={(e) => e.key === 'Enter' && nuevo.trim() && add()} />
        <button className="btn primary sm" onClick={add} disabled={!nuevo.trim()}><Icon name="plus" /> Añadir</button>
      </div>
      <div className="muted" style={{ fontSize: 11, marginTop: 8 }}>El tipo se elige en cada tarea (ficha › Tareas y Tareas › Tareas de proyecto) y sirve para filtrar, imprimir y sacar el Excel por grupos.</div>
    </>
  );
};
