// ─────────────────────────────────────────────────────
// Shared ActionsPanel — used by leads and presupuestos.
// Owns the legacy `acciones` table via /api/records/:leadId/acciones
// and /api/records/presupuesto/:pId/acciones (GUT-23 extended legacy).
// `readOnly` hides the create form and the per-row edit/complete/delete controls.
// ─────────────────────────────────────────────────────

const ACCION_TIPOS_LIST = ['NOTA','LLAMADA','EMAIL','WHATSAPP','REUNION','VISITA','TAREA'];
const ACCION_TIPO_ICONS = {
  NOTA:'📝', LLAMADA:'📞', EMAIL:'✉️', WHATSAPP:'💬',
  REUNION:'🤝', VISITA:'📍', TAREA:'✅',
};

const RECORDATORIO_OPTS = [
  { v: 'en_momento',   label: 'En el momento' },
  { v: '1h_antes',     label: '1h antes' },
  { v: 'dia_anterior', label: 'Día anterior' },
];
const RECORDATORIO_LABEL = RECORDATORIO_OPTS.reduce((a, o) => (a[o.v] = o.label, a), {});

const fmtAccDate = (iso) => {
  if (!iso) return '';
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return '';
  const dd = String(d.getDate()).padStart(2,'0');
  const mm = String(d.getMonth()+1).padStart(2,'0');
  const yyyy = d.getFullYear();
  const hh = String(d.getHours()).padStart(2,'0');
  const mi = String(d.getMinutes()).padStart(2,'0');
  return `${dd}/${mm}/${yyyy} ${hh}:${mi}`;
};
const fmtAccDateOnly = (iso) => {
  if (!iso) return '';
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso));
  if (m) return `${m[3]}/${m[2]}/${m[1]}`;
  return '';
};

const ESTADO_STYLE_ACC = {
  pendiente:     { bg:'#fff4e0', border:'#f0b860', label:'Pendiente',     ink:'#a05a00' },
  completada:    { bg:'#e6f5e6', border:'#7fc88a', label:'Completada',    ink:'#1f6b2b' },
  sin_completar: { bg:'#fde4e4', border:'#e98a8a', label:'Sin completar', ink:'#a51d1d' },
};

// scopeUrl: e.g. `/api/records/${leadId}/acciones` or `/api/records/presupuesto/${pId}/acciones`
// itemUrl(id): e.g. `/api/acciones/${id}`
const ActionsPanel = ({ scopeUrl, itemUrl, readOnly = false, onToast, onChange, title }) => {
  const [items, setItems] = React.useState(null);
  const [tipo, setTipo] = React.useState('NOTA');
  const [desc, setDesc] = React.useState('');
  const [fechaProxima, setFechaProxima] = React.useState('');
  const [recordatorio, setRecordatorio] = React.useState('en_momento');
  const [saving, setSaving] = React.useState(false);
  const [editId, setEditId] = React.useState(null);
  const [editFechaProxima, setEditFechaProxima] = React.useState('');
  const [editRecordatorio, setEditRecordatorio] = React.useState('en_momento');

  const load = React.useCallback(() => {
    if (!scopeUrl) { setItems([]); return; }
    API.get(scopeUrl)
      .then(rows => setItems(rows || []))
      .catch(e => { setItems([]); onToast && onToast(e.message || 'Error al cargar acciones', true); });
  }, [scopeUrl, onToast]);

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

  const add = async () => {
    if (!desc.trim() && !fechaProxima) {
      onToast && onToast('Indica descripción o fecha próxima', true);
      return;
    }
    setSaving(true);
    try {
      await API.post(scopeUrl, {
        tipo,
        descripcion: desc.trim(),
        fecha_proxima: fechaProxima || null,
        tipo_recordatorio: recordatorio,
      });
      setDesc(''); setFechaProxima(''); setTipo('NOTA'); setRecordatorio('en_momento');
      load();
      onChange && onChange();
      onToast && onToast('Acción añadida ✓');
    } catch (e) {
      onToast && onToast(e.message || 'Error al añadir', true);
    } finally { setSaving(false); }
  };

  const del = async (id) => {
    if (!confirm('¿Eliminar esta acción?')) return;
    try {
      await API.del(itemUrl(id));
      load();
      onChange && onChange();
    } catch (e) { onToast && onToast(e.message || 'Error al eliminar', true); }
  };

  const startEdit = (it) => {
    setEditId(it.id);
    setEditFechaProxima(it.fecha_proxima ? String(it.fecha_proxima).slice(0,10) : '');
    setEditRecordatorio(it.tipo_recordatorio || 'en_momento');
  };
  const saveEdit = async () => {
    try {
      await API.put(itemUrl(editId), {
        fecha_proxima: editFechaProxima || null,
        tipo_recordatorio: editRecordatorio,
      });
      setEditId(null);
      load();
      onChange && onChange();
    } catch (e) { onToast && onToast(e.message || 'Error al guardar', true); }
  };
  const markDone = async (it) => {
    try {
      await API.put(itemUrl(it.id), { completada: true });
      load();
      onChange && onChange();
    } catch (e) { onToast && onToast(e.message || 'Error', true); }
  };

  const inputCss = { padding:'6px 8px', border:'1px solid var(--line)', borderRadius:4, background:'var(--surface)', fontSize:12.5 };

  const proximas = (items || []).filter(i => i.estado === 'pendiente');

  return (
    <div>
      {!readOnly && (
        <div style={{border:'1px solid var(--line)', borderRadius:6, padding:10, background:'var(--bg, transparent)'}}>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginBottom:8}}>
            <select value={tipo} onChange={e=>setTipo(e.target.value)} style={{...inputCss, width:'100%'}}>
              {ACCION_TIPOS_LIST.map(t => <option key={t} value={t}>{ACCION_TIPO_ICONS[t]} {t}</option>)}
            </select>
            <input type="date" value={fechaProxima} onChange={e=>setFechaProxima(e.target.value)} placeholder="Próxima acción" style={{...inputCss, width:'100%'}}/>
            <select value={recordatorio} onChange={e=>setRecordatorio(e.target.value)} style={{...inputCss, width:'100%'}} title="Recordatorio">
              {RECORDATORIO_OPTS.map(o => <option key={o.v} value={o.v}>⏰ {o.label}</option>)}
            </select>
          </div>
          <textarea rows="2" value={desc} onChange={e=>setDesc(e.target.value)} placeholder="Descripción de la acción…"
            style={{width:'100%', padding:8, border:'1px solid var(--line)', borderRadius:4, background:'var(--surface)', fontSize:12.5, fontFamily:'inherit'}}/>
          <div style={{display:'flex', justifyContent:'flex-end', marginTop:6}}>
            <button type="button" className="btn primary" onClick={add} disabled={saving}>
              {saving ? 'Añadiendo…' : 'Añadir acción'}
            </button>
          </div>
        </div>
      )}

      {!readOnly && proximas.length > 0 && (
        <div style={{marginTop:12}}>
          <div style={{fontSize:11, fontWeight:600, color:'var(--ink-3)', marginBottom:6, textTransform:'uppercase', letterSpacing:.5}}>Próximas ({proximas.length})</div>
          {proximas.map(it => (
            <div key={`p${it.id}`} style={{display:'flex', alignItems:'center', gap:8, padding:'6px 8px', background:'#fff8e1', border:'1px solid #f0d97e', borderRadius:4, marginBottom:4, fontSize:12.5}}>
              <span>⏰</span>
              <strong>{fmtAccDateOnly(it.fecha_proxima)}</strong>
              <span style={{color:'var(--ink-3)'}}>· {ACCION_TIPO_ICONS[it.tipo] || ''} {it.tipo}</span>
              <span style={{flex:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{it.descripcion || ''}</span>
              <button type="button" className="btn ghost" style={{padding:'2px 6px', fontSize:11}} onClick={()=>markDone(it)}>Hecho</button>
            </div>
          ))}
        </div>
      )}

      <div style={{marginTop:12}}>
        <div style={{fontSize:11, fontWeight:600, color:'var(--ink-3)', marginBottom:6, textTransform:'uppercase', letterSpacing:.5}}>
          {title || 'Histórico'} {items ? `(${items.length})` : ''}
        </div>
        {items === null ? (
          <div style={{color:'var(--ink-3)', fontSize:12.5}}>Cargando…</div>
        ) : items.length === 0 ? (
          <div style={{color:'var(--ink-3)', fontSize:12.5, fontStyle:'italic'}}>Sin acciones registradas.</div>
        ) : (
          <div style={{maxHeight:280, overflowY:'auto', border:'1px solid var(--line)', borderRadius:6}}>
            {items.map((it, idx) => {
              const st = ESTADO_STYLE_ACC[it.estado] || ESTADO_STYLE_ACC.completada;
              const canComplete = !readOnly && (it.estado === 'pendiente' || it.estado === 'sin_completar');
              const recLbl = it.tipo_recordatorio ? RECORDATORIO_LABEL[it.tipo_recordatorio] : '';
              return (
                <div key={it.id} style={{padding:'8px 10px', borderTop: idx === 0 ? 'none' : '1px solid #fff8', fontSize:12.5, background:st.bg, borderLeft:`3px solid ${st.border}`}}>
                  <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:3, flexWrap:'wrap'}}>
                    <span style={{fontSize:13}}>{ACCION_TIPO_ICONS[it.tipo] || '•'}</span>
                    <strong>{it.tipo}</strong>
                    <span style={{padding:'1px 6px', borderRadius:10, background:st.border, color:'#fff', fontSize:10.5, fontWeight:600, textTransform:'uppercase', letterSpacing:.3}}>{st.label}</span>
                    <span style={{color:'var(--ink-3)'}}>{fmtAccDate(it.fecha_accion)}</span>
                    {recLbl && (
                      <span style={{padding:'1px 6px', borderRadius:10, background:'var(--surface)', border:`1px solid ${st.border}`, color:st.ink, fontSize:10.5}} title="Recordatorio">⏰ {recLbl}</span>
                    )}
                    {it.usuario && <span style={{color:'var(--ink-3)'}}>· {it.usuario}</span>}
                    <span style={{flex:1}}/>
                    {canComplete && (
                      <button type="button" className="btn ghost" title="Marcar completada" onClick={()=>markDone(it)} style={{padding:'2px 6px', fontSize:11}}>Completar</button>
                    )}
                    {!readOnly && (
                      <>
                        <button type="button" className="icon-btn" title="Editar próxima" onClick={()=>startEdit(it)} style={{padding:2}}>✎</button>
                        <button type="button" className="icon-btn" title="Eliminar" onClick={()=>del(it.id)} style={{padding:2, color:'var(--err)'}}>✕</button>
                      </>
                    )}
                  </div>
                  {it.descripcion && <div style={{whiteSpace:'pre-wrap', color:'var(--ink-1)'}}>{it.descripcion}</div>}
                  {!readOnly && editId === it.id ? (
                    <div style={{display:'flex', gap:6, alignItems:'center', marginTop:6, flexWrap:'wrap'}}>
                      <span style={{color:'var(--ink-3)'}}>Próxima:</span>
                      <input type="date" value={editFechaProxima} onChange={e=>setEditFechaProxima(e.target.value)} style={inputCss}/>
                      <select value={editRecordatorio} onChange={e=>setEditRecordatorio(e.target.value)} style={inputCss}>
                        {RECORDATORIO_OPTS.map(o => <option key={o.v} value={o.v}>⏰ {o.label}</option>)}
                      </select>
                      <button type="button" className="btn primary" style={{padding:'2px 8px', fontSize:11}} onClick={saveEdit}>Guardar</button>
                      <button type="button" className="btn ghost" style={{padding:'2px 8px', fontSize:11}} onClick={()=>setEditId(null)}>Cancelar</button>
                    </div>
                  ) : it.fecha_proxima ? (
                    <div style={{marginTop:3, color:st.ink, fontSize:11.5}}>
                      ⏰ {it.estado === 'sin_completar' ? 'Vencida' : 'Próxima'}: {fmtAccDateOnly(it.fecha_proxima)}
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

window.ActionsPanel = ActionsPanel;
