// ─────────────────────────────────────────────────────
// GUT-272 — Artículos «kit» (Juanjo: «PÉRGOLA BIOCLIMÁTICA, compuesta por…»).
// Un artículo del catálogo puede llevar una lista de componentes (otros
// artículos) con cantidad por kit (/api/materiales/:id/componentes).
//
//   <KitComponentesEditor kitId={id|null} rows={[…]} onChange={rows => …} catalogo={[…]} />
//     Editor de la ficha del artículo (Catálogo de artículos): añadir con
//     buscador, quitar, reordenar, cantidad por kit y nota.
//   <KitDesplegarModal material={kit} kits={n} onClose onConfirm={(lineas, kits) => …} />
//     Vista previa de las líneas que se crearán al añadir N kits a los
//     materiales de un expediente o proyecto (despliegue recursivo en el
//     servidor, /api/materiales/:id/despliegue). onConfirm crea las líneas.
//   kitObservacion(despliegue, linea, extra) → «Dentro de SUBKIT · nota · extra»
//   kitCampos(despliegue) → { kit_id, kit_nombre, kit_grupo, kit_cantidad } para cada
//     línea creada: INC-009, la tabla de materiales las agrupa bajo «KIT …» plegable.
//     Llamar una vez por despliegue (kit_grupo nuevo = grupo nuevo).
// ─────────────────────────────────────────────────────

const kitFmt = (n) => String(Math.round(Number(n) * 10000) / 10000).replace('.', ',');

// Badge «Kit · N componentes» (lista del catálogo y buscadores).
const KitBadge = ({ n, corto }) => (!n ? null : (
  <span className="pill info" style={{ fontSize: 11, whiteSpace: 'nowrap' }} title={`Artículo compuesto: se despliega en ${n} componente${n === 1 ? '' : 's'} al añadirlo a materiales`}>
    <span className="d" />{corto ? 'Kit' : `Kit · ${n} componente${n === 1 ? '' : 's'}`}
  </span>
));

// Observación de cada línea desplegada: kits intermedios, nota del componente y la observación
// escrita en el alta. INC-009: el kit de origen va en kit_nombre (cabecera del grupo), no aquí.
const kitObservacion = (desp, l, extra) => [
  (l.ruta || []).length ? `Dentro de ${l.ruta.join(' › ')}` : null,
  l.nota, extra && String(extra).trim(),
].filter(Boolean).join(' · ');

// INC-009: origen kit de las líneas de un despliegue (mismo kit_grupo para todas).
const kitGrupoNuevo = () => {
  try { if (window.crypto && crypto.randomUUID) return crypto.randomUUID(); } catch (_) { /* contexto no seguro */ }
  return `k${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
};
const kitCampos = (desp) => ({
  kit_id: desp.kit.id, kit_nombre: desp.kit.nombre, kit_grupo: kitGrupoNuevo(), kit_cantidad: desp.kits,
});

const KitComponentesEditor = ({ kitId, rows, onChange, catalogo }) => {
  // Opciones del buscador: artículos elegibles (no el propio kit), agrupados por categoría.
  const items = React.useMemo(() => (catalogo || [])
    .filter(m => String(m.id) !== String(kitId))
    .map(m => ({ id: m.id, mono: m.referencia || '', label: m.kit_componentes ? `${m.nombre} (kit)` : m.nombre, group: m.categoria_nombre || 'Sin categoría', m })),
  [catalogo, kitId]);
  const add = (it) => { if (it) onChange([...rows, { componente_id: it.m.id, nombre: it.m.nombre, referencia: it.m.referencia, unidad_medida: it.m.unidad_medida, kit_componentes: it.m.kit_componentes, cantidad: '1', nota: '' }]); };
  const upd = (i, k, v) => onChange(rows.map((r, idx) => idx === i ? { ...r, [k]: v } : r));
  const rm = (i) => onChange(rows.filter((_, idx) => idx !== i));
  const mover = (i, d) => {
    const j = i + d; if (j < 0 || j >= rows.length) return;
    const out = rows.slice(); [out[i], out[j]] = [out[j], out[i]]; onChange(out);
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {rows.length === 0 && (
        <div className="muted" style={{ fontSize: 12 }}>Artículo normal. Si añades componentes pasa a ser un kit: al meterlo en los materiales de un expediente o proyecto se crean sus componentes (cantidad × nº de kits).</div>
      )}
      {rows.map((r, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 80px 1fr 64px', gap: 6, alignItems: 'center' }}>
          <div className="truncate" style={{ fontSize: 12.5 }} title={r.nombre}>
            {r.referencia && <code style={{ fontSize: 11.5, marginRight: 6 }}>{r.referencia}</code>}{r.nombre}
            {r.kit_componentes > 0 && <> <KitBadge n={r.kit_componentes} corto /></>}
          </div>
          <div className="field" title={`Cantidad por kit${r.unidad_medida ? ` (${r.unidad_medida})` : ''}`}>
            <input type="number" step="any" min="0" value={r.cantidad} onChange={e => upd(i, 'cantidad', e.target.value)} placeholder={r.unidad_medida || 'Cant.'} />
          </div>
          <div className="field"><input value={r.nota || ''} onChange={e => upd(i, 'nota', e.target.value)} placeholder="Nota (opcional)" /></div>
          <div style={{ display: 'flex', gap: 2 }}>
            <button type="button" className="btn ghost" style={{ padding: '2px 5px' }} disabled={i === 0} onClick={() => mover(i, -1)} title="Subir">↑</button>
            <button type="button" className="btn ghost" style={{ padding: '2px 5px' }} disabled={i === rows.length - 1} onClick={() => mover(i, 1)} title="Bajar">↓</button>
            <button type="button" className="btn ghost" style={{ color: 'var(--err)', padding: '2px 6px' }} onClick={() => rm(i)} title="Quitar">×</button>
          </div>
        </div>
      ))}
      <ComboBuscador value="" items={items} onChange={add} placeholder="+ Añadir componente: escribe código o nombre…" />
    </div>
  );
};

const KitDesplegarModal = ({ material, kits: kitsIni, onClose, onConfirm }) => {
  const [kits, setKits] = React.useState(String(kitsIni || 1));
  const [desp, setDesp] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => {
    const n = Number(String(kits).replace(',', '.'));
    if (!(n > 0)) { setDesp(null); setErr('Indica cuántos kits'); return; }
    let vivo = true;
    setErr('');
    API.get(`/api/materiales/${material.id}/despliegue`, { kits: n })
      .then(d => { if (vivo) setDesp(d); })
      .catch(e => { if (vivo) { setDesp(null); setErr(e.message || 'Error'); } });
    return () => { vivo = false; };
  }, [kits, material.id]);
  const confirmar = async () => {
    if (!desp || !desp.lineas.length) return;
    setBusy(true);
    // onConfirm avisa él mismo del error (toast); aquí solo se deja el modal abierto.
    try { await onConfirm(desp.lineas, desp); onClose(); }
    catch (e) { setErr(e.message || 'Error al crear las líneas'); }
    finally { setBusy(false); }
  };
  return ReactDOM.createPortal(
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.35)', zIndex: 1050, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '40px 20px', overflow: 'auto' }}
      onClick={() => !busy && onClose()}>
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 8, width: 'min(680px,100%)', boxShadow: '0 20px 60px rgba(0,0,0,.18)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
          <h3 style={{ margin: 0, fontSize: 15 }}>Añadir kit: {material.nombre}</h3>
          <button className="icon-btn" onClick={onClose} disabled={busy}><Icon name="x" /></button>
        </div>
        <div style={{ padding: '14px 18px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <label style={{ fontSize: 12.5 }}>Nº de kits</label>
            <input type="number" step="any" min="0" value={kits} onChange={e => setKits(e.target.value)} style={{ width: 80 }} />
            <span className="muted" style={{ fontSize: 12 }}>Se crearán estas líneas (cantidad del componente × nº de kits), agrupadas bajo «KIT {material.nombre}» en la lista.</span>
          </div>
          {err && <div style={{ color: 'var(--err)', fontSize: 12.5, marginBottom: 8 }}>{err}</div>}
          {desp && (
            <div className="tbl-wrap"><div className="tbl-scroll" style={{ maxHeight: 360 }}>
              <table className="tbl tbl-compact">
                <thead><tr><th style={{ width: 90 }}>Ref.</th><th>Componente</th><th style={{ width: 90, textAlign: 'right' }}>Por kit</th><th style={{ width: 110, textAlign: 'right' }}>Cantidad</th></tr></thead>
                <tbody>
                  {desp.lineas.length === 0 && <tr><td colSpan="4" className="muted" style={{ textAlign: 'center' }}>Este kit no tiene componentes.</td></tr>}
                  {desp.lineas.map((l, i) => (
                    <tr key={i}>
                      <td><code style={{ fontSize: 11.5 }}>{l.referencia || '—'}</code></td>
                      <td>
                        {l.nombre}
                        {(l.ruta.length > 0 || l.nota) && <div className="muted" style={{ fontSize: 11 }}>{[l.ruta.length && `dentro de ${l.ruta.join(' › ')}`, l.nota].filter(Boolean).join(' · ')}</div>}
                      </td>
                      <td className="num muted" style={{ textAlign: 'right' }}>{kitFmt(l.cantidad_por_kit)}</td>
                      <td className="num strong" style={{ textAlign: 'right' }}>{kitFmt(l.cantidad)} {l.unidad || ''}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div></div>
          )}
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '12px 18px', borderTop: '1px solid var(--line)', gap: 8 }}>
          <button type="button" className="btn ghost" onClick={onClose} disabled={busy}>Cancelar</button>
          <button type="button" className="btn primary" onClick={confirmar} disabled={busy || !desp || !desp.lineas.length}>
            {busy ? 'Creando…' : `Crear ${desp ? desp.lineas.length : ''} línea${desp && desp.lineas.length === 1 ? '' : 's'}`}
          </button>
        </div>
      </div>
    </div>,
    document.body,
  );
};

window.KitBadge = KitBadge;
window.KitComponentesEditor = KitComponentesEditor;
window.KitDesplegarModal = KitDesplegarModal;
window.kitObservacion = kitObservacion;
window.kitCampos = kitCampos;
