// ─────────────────────────────────────────────────────
// ARCHIVOS — reusable attachments panel for ERP drawers.
// ─────────────────────────────────────────────────────

const archivoSize = (bytes) => {
  const n = Number(bytes || 0);
  if (!n) return '—';
  if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
};

const archivoIsImage = (f) => String(f.mimetype || '').startsWith('image/');

const ArchivoThumb = ({ file }) => {
  const [src, setSrc] = React.useState('');

  React.useEffect(() => {
    if (!file || !archivoIsImage(file)) { setSrc(''); return; }
    let url = '';
    let alive = true;
    API.request(`/api/archivos/${file.id}/download`).then(async res => {
      if (!res.ok) return;
      const blob = await res.blob();
      if (!alive) return;
      url = URL.createObjectURL(blob);
      setSrc(url);
    }).catch(() => {});
    return () => {
      alive = false;
      if (url) URL.revokeObjectURL(url);
    };
  }, [file && file.id]);

  if (archivoIsImage(file)) {
    return src ? <img src={src} alt=""/> : <Icon name="file" size={18}/>;
  }
  return <span className="archivo-ext">PDF</span>;
};

const ArchivosPanel = ({ entityType, entityId, presupuestoId, categoria, title = 'Archivos', onToast }) => {
  const [files, setFiles] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const [error, setError] = React.useState('');
  const inputRef = React.useRef(null);

  const toast = (msg, isErr) => {
    if (onToast) onToast(msg, isErr);
    else if (isErr) console.error(msg);
  };

  const load = React.useCallback(() => {
    if (!entityType || !entityId) return;
    setLoading(true);
    setError('');
    const params = { entity_type: entityType, entity_id: entityId };
    if (categoria) params.categoria = categoria;
    API.get('/api/archivos', params)
      .then(rows => setFiles(Array.isArray(rows) ? rows : []))
      .catch(e => {
        setError(e.message || 'Error al cargar archivos');
        setFiles([]);
      })
      .finally(() => setLoading(false));
  }, [entityType, entityId, categoria]);

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

  const upload = async (ev) => {
    const selected = Array.from(ev.target.files || []);
    if (!selected.length) return;
    if (selected.length > 5) {
      toast('Máximo 5 archivos a la vez', true);
      if (inputRef.current) inputRef.current.value = '';
      return;
    }
    const fd = new FormData();
    fd.append('entity_type', entityType);
    fd.append('entity_id', String(entityId));
    if (categoria) fd.append('categoria', categoria);
    selected.forEach(f => fd.append('files', f));
    setUploading(true);
    try {
      await API.upload('/api/archivos', fd);
      toast(`${selected.length} archivo${selected.length === 1 ? '' : 's'} subido${selected.length === 1 ? '' : 's'} ✓`);
      load();
    } catch (e) {
      toast(e.message || 'Error al subir archivo', true);
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = '';
    }
  };

  const openFile = async (f) => {
    try {
      const res = await API.request(`/api/archivos/${f.id}/download`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      window.open(url, '_blank');
      setTimeout(() => URL.revokeObjectURL(url), 30000);
    } catch (e) {
      toast(e.message || 'Error al abrir archivo', true);
    }
  };

  const del = async (f) => {
    if (!confirm(`¿Eliminar ${f.original_name || 'este archivo'}?`)) return;
    try {
      await API.del(`/api/archivos/${f.id}`);
      setFiles(rows => rows.filter(x => x.id !== f.id));
      toast('Archivo eliminado');
    } catch (e) {
      toast(e.message || 'Error al eliminar archivo', true);
    }
  };

  const openPresupuestoPdf = () => {
    if (!presupuestoId) return;
    API.download(`/api/presupuestos/${presupuestoId}/pdf`, `presupuesto_${presupuestoId}.pdf`)
      .catch(e => toast(e.message || 'Error al abrir presupuesto', true));
  };

  return (
    <div className="archivos-panel">
      <div className="archivos-head">
        <div>
          <div className="section-title" style={{margin:0,paddingTop:0}}>{title}</div>
          <div className="muted" style={{fontSize:12}}>
            {loading ? 'Cargando adjuntos…' : `${files.length + (presupuestoId ? 1 : 0)} adjunto${files.length + (presupuestoId ? 1 : 0) === 1 ? '' : 's'}`}
          </div>
        </div>
        <label className="btn primary" style={{cursor:'pointer'}}>
          <Icon name="upload" size={12}/> {uploading ? 'Subiendo…' : 'Subir'}
          <input ref={inputRef} type="file" multiple accept=".jpg,.jpeg,.png,.webp,.pdf" style={{display:'none'}} onChange={upload} disabled={uploading}/>
        </label>
      </div>

      {error && <div className="muted" style={{fontSize:12,color:'var(--err)',padding:'8px 0'}}>{error}</div>}
      {!loading && !error && files.length === 0 && !presupuestoId && (
        <div className="muted" style={{fontSize:12,padding:'14px 0'}}>Sin archivos adjuntos.</div>
      )}

      <div className="archivos-grid">
        {presupuestoId && (
          <button type="button" className="archivo-card" onClick={openPresupuestoPdf}>
            <span className="archivo-thumb"><span className="archivo-ext">PDF</span></span>
            <span className="archivo-meta">
              <span className="archivo-name">Presupuesto aceptado</span>
              <span className="archivo-sub">Documento comercial</span>
            </span>
            <span className="archivo-actions"><Icon name="download" size={13}/></span>
          </button>
        )}
        {files.map(f => (
          <div key={f.id} className="archivo-card">
            <button type="button" className="archivo-thumb" onClick={() => openFile(f)} title={f.original_name || ''}>
              <ArchivoThumb file={f}/>
            </button>
            <button type="button" className="archivo-meta" onClick={() => openFile(f)}>
              <span className="archivo-name">{f.original_name || `Archivo ${f.id}`}</span>
              <span className="archivo-sub">{archivoSize(f.size)} · {f.created_at ? new Date(f.created_at).toLocaleDateString('es-ES') : '—'}</span>
            </button>
            <span className="archivo-actions">
              <button className="icon-btn tip" data-tip="Descargar" onClick={() => API.download(`/api/archivos/${f.id}/download`, f.original_name || `archivo_${f.id}`)}>
                <Icon name="download" size={12}/>
              </button>
              <button className="icon-btn tip" data-tip="Eliminar" style={{color:'var(--err)'}} onClick={() => del(f)}>
                <Icon name="trash" size={12}/>
              </button>
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

window.ArchivosPanel = ArchivosPanel;
