// ─────────────────────────────────────────────────────
// GUT-68 — ExpedienteDocumentos: gestión documental del expediente.
// Replica la estructura de carpetas de disco por expediente:
// 6 secciones fijas (cada una un ArchivosPanel filtrado por su
// categoria) + diario/notas fechadas (timeline).
//
// Lo consume la vista de expediente (GUT-63) vía window.ExpedienteDocumentos.
// expedienteId = pedidos.id. entity_type fijo = 'expedientes'.
// ─────────────────────────────────────────────────────

// Secciones documentales fijas (las claves SON la `categoria`).
const EXPEDIENTE_SECCIONES = [
  '01 INFO',
  'MEDICIONES',
  '03 LISTA DE MATERIALES',
  '04 FABRICACION',
  '05 PRESUPUESTO',
  '06 PEDIDO',
];

function fmtFechaNota(val) {
  if (!val) return '';
  try {
    // `fecha` es DATE (YYYY-MM-DD); evitar shift de zona horaria.
    const s = String(val).slice(0, 10);
    const [y, m, d] = s.split('-');
    if (y && m && d) return `${d}/${m}/${y}`;
    return new Date(val).toLocaleDateString('es-ES');
  } catch (_) {
    return String(val);
  }
}

const ExpedienteNotas = ({ expedienteId, onToast }) => {
  const [items, setItems] = React.useState(null);
  const [texto, setTexto] = React.useState('');
  const [fecha, setFecha] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  const load = React.useCallback(() => {
    if (!expedienteId) return;
    setItems(null);
    API.get('/api/expediente-notas', { pedido_id: expedienteId })
      .then(rows => setItems(Array.isArray(rows) ? rows : []))
      .catch(e => {
        setItems([]);
        onToast && onToast(e.message || 'Error al cargar notas', true);
      });
  }, [expedienteId]);

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

  const add = async () => {
    const txt = texto.trim();
    if (!txt) { onToast && onToast('Escribe el texto de la nota', true); return; }
    setSaving(true);
    try {
      const body = { pedido_id: expedienteId, texto: txt };
      if (fecha) body.fecha = fecha;
      await API.post('/api/expediente-notas', body);
      setTexto('');
      setFecha('');
      onToast && onToast('Nota añadida ✓');
      load();
    } catch (e) {
      onToast && onToast(e.message || 'Error al guardar nota', true);
    } finally {
      setSaving(false);
    }
  };

  const del = async (n) => {
    if (!confirm('¿Eliminar esta nota?')) return;
    try {
      await API.del(`/api/expediente-notas/${n.id}`);
      setItems(rows => (rows || []).filter(x => x.id !== n.id));
      onToast && onToast('Nota eliminada');
    } catch (e) {
      onToast && onToast(e.message || 'Error al eliminar nota', true);
    }
  };

  return (
    <div>
      <div className="section-title">Notas / diario del expediente</div>

      <div style={{display:'flex',gap:8,alignItems:'flex-start',marginBottom:14,flexWrap:'wrap'}}>
        <input
          type="date"
          value={fecha}
          onChange={e => setFecha(e.target.value)}
          style={{flex:'0 0 150px',background:'var(--surface)',border:'1px solid var(--line)',borderRadius:'var(--r-md, 6px)',padding:'6px 10px',color:'var(--ink)',fontSize:12.5}}
          title="Fecha de la entrada (por defecto hoy)"
        />
        <textarea
          value={texto}
          onChange={e => setTexto(e.target.value)}
          placeholder="Ej.: Llegaron los ángulos"
          rows={2}
          style={{flex:'1 1 220px',minWidth:180,resize:'vertical',background:'var(--surface)',border:'1px solid var(--line)',borderRadius:'var(--r-md, 6px)',padding:'6px 10px',color:'var(--ink)',fontSize:12.5,fontFamily:'inherit'}}
        />
        <button type="button" className="btn primary" onClick={add} disabled={saving}>
          <Icon name="plus" size={12}/> {saving ? 'Guardando…' : 'Añadir'}
        </button>
      </div>

      {items === null && <p className="muted" style={{fontSize:12}}>Cargando…</p>}
      {items && items.length === 0 && (
        <p className="muted" style={{fontSize:12}}>Sin notas todavía.</p>
      )}
      {items && items.length > 0 && (
        <div className="tl">
          {items.map(n => (
            <div key={n.id} className="tl-item">
              <div className="tl-dot"/>
              <div className="tl-content">
                <div className="t" style={{display:'flex',alignItems:'center',gap:6,justifyContent:'space-between'}}>
                  <span style={{whiteSpace:'pre-wrap'}}>{n.texto}</span>
                  <button
                    className="icon-btn tip"
                    data-tip="Eliminar"
                    style={{color:'var(--err)',flex:'0 0 auto'}}
                    onClick={() => del(n)}
                  >
                    <Icon name="trash" size={12}/>
                  </button>
                </div>
                <time>
                  {fmtFechaNota(n.fecha)}
                  {n.autor ? ` · ${n.autor}` : ''}
                </time>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const ExpedienteDocumentos = ({ expedienteId, onToast }) => {
  if (!expedienteId) {
    return <p className="muted" style={{fontSize:12}}>Expediente no disponible.</p>;
  }
  return (
    <div className="expediente-docs">
      {EXPEDIENTE_SECCIONES.map(seccion => (
        <div key={seccion} style={{marginBottom:18}}>
          <ArchivosPanel
            entityType="expedientes"
            entityId={expedienteId}
            categoria={seccion}
            title={seccion}
            onToast={onToast}
          />
        </div>
      ))}
      <ExpedienteNotas expedienteId={expedienteId} onToast={onToast}/>
    </div>
  );
};

window.EXPEDIENTE_SECCIONES = EXPEDIENTE_SECCIONES;
window.ExpedienteDocumentos = ExpedienteDocumentos;
