// agent-config.jsx — Configuración de instrucciones por agente (vista admin)
const { useState: useStateAC, useEffect: useEffectAC } = React;

// Circular bolt-style icon badge (línea visual MDP)
function IconRing({ Icon, size = 38, t, active }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      border: `1.5px solid ${active ? t.accent : t.accent + "55"}`,
      background: active ? t.accent + "1c" : "transparent",
      display: "flex", alignItems: "center", justifyContent: "center",
      color: t.accent, flexShrink: 0,
    }}>
      <Icon size={size * 0.46} />
    </div>
  );
}

// Mapa de modelos: etiqueta visible ↔ id real que entiende la API
const MODEL_LABELS = {
  "claude-sonnet-4-5": "Claude · Sonnet",
  "claude-opus-4-1":   "Claude · Opus",
  "claude-haiku-4-5":  "Claude · Haiku",
};
const MODEL_IDS = Object.keys(MODEL_LABELS);

function AgentConfigView({ t, p }) {
  const isMobile = window.useIsMobile();
  const [serverCfg, setServerCfg] = useStateAC({}); // id -> { instrucciones, bienvenida, modelo, temperatura, activo }
  const [loadingCfg, setLoadingCfg] = useStateAC(true);
  const [selectedId, setSelectedId] = useStateAC(ALL_AGENTS[0].id);
  const [draft, setDraft] = useStateAC(null);
  const [saved, setSaved] = useStateAC(false);
  const [saving, setSaving] = useStateAC(false);

  const agent = ALL_AGENTS.find(a => a.id === selectedId);

  // Cargar la config real de los agentes desde el backend
  useEffectAC(() => {
    MDP_API.adminAgentes().then(rows => {
      const map = {};
      rows.forEach(r => {
        map[r.id] = {
          instrucciones: r.instrucciones || "",
          bienvenida: r.bienvenida || "",
          modelo: MODEL_IDS.includes(r.modelo) ? r.modelo : "claude-sonnet-4-5",
          temperatura: Number(r.temperatura),
          activo: !!r.activo,
        };
      });
      setServerCfg(map);
      setLoadingCfg(false);
    }).catch(() => setLoadingCfg(false));
  }, []);

  const baseFor = (id) => {
    const s = serverCfg[id] || {};
    return {
      instructions: s.instrucciones ?? "",
      welcome: s.bienvenida || `Hola, soy ${agent.name}. ${agent.desc} ¿Por dónde querés empezar hoy?`,
      model: s.modelo ?? "claude-sonnet-4-5",
      temperature: s.temperatura ?? 0.7,
      enabled: s.activo ?? true,
    };
  };

  // Cargar el borrador cuando cambia el agente o llega la config
  useEffectAC(() => {
    if (loadingCfg) return;
    setDraft(baseFor(selectedId));
    setSaved(false);
  }, [selectedId, loadingCfg, serverCfg]);

  const isModified = (() => {
    if (!draft) return false;
    return JSON.stringify(baseFor(selectedId)) !== JSON.stringify(draft);
  })();

  const save = async () => {
    if (saving) return;
    setSaving(true);
    try {
      await MDP_API.adminUpdateAgente(selectedId, {
        instrucciones: draft.instructions,
        bienvenida: draft.welcome,
        modelo: draft.model,
        temperatura: draft.temperature,
        activo: draft.enabled,
      });
      setServerCfg(prev => ({
        ...prev,
        [selectedId]: {
          instrucciones: draft.instructions,
          bienvenida: draft.welcome,
          modelo: draft.model,
          temperatura: draft.temperature,
          activo: draft.enabled,
        },
      }));
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    } catch (e) {
      alert("No se pudo guardar: " + (e.message || "error"));
    } finally {
      setSaving(false);
    }
  };

  const resetToDefault = () => {
    setDraft(d => ({ ...d, instructions: INSTRUCTIONS[selectedId] ?? d.instructions }));
  };

  if (loadingCfg || !draft) return (
    <div style={{ padding: 40, color: p.textMuted, fontFamily: "'Geist', sans-serif" }}>
      Cargando configuración de agentes…
    </div>
  );

  const labelStyle = {
    display: "block",
    fontFamily: "'Geist', sans-serif", fontSize: 11,
    color: p.textMuted, letterSpacing: "0.14em",
    textTransform: "uppercase", marginBottom: 9, fontWeight: 600,
  };
  const inputStyle = {
    width: "100%", boxSizing: "border-box",
    background: p.bg2, border: `1px solid ${p.border}`,
    borderRadius: 10, padding: "12px 14px",
    color: p.text, fontSize: 14,
    fontFamily: "'Geist', sans-serif", outline: "none",
  };

  return (
    <div style={{ display: "flex", flexDirection: isMobile ? "column" : "row", height: "100%", minHeight: 0 }}>
      {/* Agent list (solo desktop) */}
      {!isMobile && (
      <div style={{
        width: 280, flexShrink: 0,
        borderRight: `1px solid ${p.border}`,
        overflowY: "auto", padding: "20px 12px",
        background: p.sidebarBg,
      }}>
        <div style={{
          padding: "0 8px 14px",
          fontFamily: "'Geist', sans-serif", fontSize: 11,
          color: p.textMuted, letterSpacing: "0.18em",
          textTransform: "uppercase", fontWeight: 600,
        }}>Elige un agente</div>
        {LEVELS.map(level => (
          <div key={level.n} style={{ marginBottom: 14 }}>
            <div style={{
              padding: "6px 8px",
              fontFamily: "'Geist', sans-serif", fontSize: 10,
              color: p.textDim, letterSpacing: "0.2em",
              textTransform: "uppercase", fontWeight: 600,
            }}>Nivel {level.n} · {level.name}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {level.agents.map(a => {
                const cfg = serverCfg[a.id] || {};
                const customized = cfg.instrucciones !== undefined && cfg.instrucciones !== INSTRUCTIONS[a.id];
                const active = selectedId === a.id;
                return (
                  <div key={a.id} onClick={() => setSelectedId(a.id)} style={{
                    display: "flex", alignItems: "center", gap: 11,
                    padding: "9px 10px", borderRadius: 9, cursor: "default",
                    background: active ? t.accent + "14" : "transparent",
                    border: `1px solid ${active ? t.accent + "55" : "transparent"}`,
                  }}>
                    <IconRing Icon={a.icon} size={32} t={t} active={active} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{
                        fontFamily: "'Geist', sans-serif", fontSize: 13, fontWeight: 500,
                        color: p.text, whiteSpace: "nowrap", overflow: "hidden",
                        textOverflow: "ellipsis",
                      }}>{a.name}</div>
                    </div>
                    {customized && (
                      <span title="Personalizado" style={{
                        width: 6, height: 6, borderRadius: 999, background: t.accent,
                        flexShrink: 0,
                      }}/>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
      )}

      {/* Editor */}
      <div style={{ flex: 1, minWidth: 0, overflowY: "auto", padding: isMobile ? "20px 16px 64px" : "32px 40px 80px" }}>
        <div style={{ maxWidth: 720, margin: "0 auto" }}>
          {isMobile && (
            <select value={selectedId} onChange={(e) => setSelectedId(e.target.value)}
              style={{ ...inputStyle, marginBottom: 22, cursor: "default" }}>
              {LEVELS.map(level => (
                <optgroup key={level.n} label={`Nivel ${level.n} · ${level.name}`}>
                  {level.agents.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
                </optgroup>
              ))}
            </select>
          )}
          {/* Header */}
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 28 }}>
            <IconRing Icon={agent.icon} size={52} t={t} active />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: "'Geist', sans-serif", fontSize: 11,
                color: p.textMuted, letterSpacing: "0.18em", textTransform: "uppercase",
                marginBottom: 5, fontWeight: 600,
              }}>Nivel {agent.level} · {agent.levelName}</div>
              <h2 style={{
                fontFamily: "'Montserrat', sans-serif", fontWeight: 800,
                fontSize: 30, color: p.text, margin: 0, letterSpacing: "-0.02em",
                lineHeight: 1.05,
              }}>{agent.name}</h2>
            </div>
            <label style={{
              display: "flex", alignItems: "center", gap: 9, cursor: "default",
              flexShrink: 0,
            }}>
              <span style={{
                fontFamily: "'Geist', sans-serif", fontSize: 13,
                color: draft.enabled ? p.text : p.textMuted,
              }}>{draft.enabled ? "Visible" : "Oculto"}</span>
              <button onClick={() => setDraft(d => ({ ...d, enabled: !d.enabled }))}
                      style={{
                        width: 42, height: 24, borderRadius: 999, padding: 2,
                        background: draft.enabled ? t.accent : p.border,
                        border: 0, cursor: "default", transition: "background .15s",
                        display: "flex", justifyContent: draft.enabled ? "flex-end" : "flex-start",
                      }}>
                <span style={{
                  width: 20, height: 20, borderRadius: 999,
                  background: "#fff", display: "block",
                }}/>
              </button>
            </label>
          </div>

          {/* Instructions */}
          <div style={{ marginBottom: 26 }}>
            <div style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              marginBottom: 9,
            }}>
              <label style={{ ...labelStyle, marginBottom: 0 }}>Instrucciones del agente</label>
              <button onClick={resetToDefault} style={{
                background: "transparent", border: 0, padding: 0,
                color: p.textMuted, cursor: "default",
                fontFamily: "'Geist', sans-serif", fontSize: 12,
                textDecoration: "underline", textUnderlineOffset: 2,
              }}>Restaurar original</button>
            </div>
            <textarea
              value={draft.instructions}
              onChange={(e) => setDraft(d => ({ ...d, instructions: e.target.value }))}
              rows={14}
              style={{ ...inputStyle, lineHeight: 1.6, resize: "vertical",
                       fontFamily: "ui-monospace, 'Geist', monospace", fontSize: 13 }}
              onFocus={(e) => e.target.style.borderColor = t.accent + "70"}
              onBlur={(e) => e.target.style.borderColor = p.border}
            />
            <div style={{
              fontFamily: "'Geist', sans-serif", fontSize: 12,
              color: p.textDim, marginTop: 8, lineHeight: 1.5,
            }}>
              Define la personalidad, el tono y el proceso que sigue el agente.
              Es el "system prompt" que recibe Claude antes de cada conversación.
            </div>
          </div>

          {/* Welcome message */}
          <div style={{ marginBottom: 26 }}>
            <label style={labelStyle}>Mensaje de bienvenida</label>
            <textarea
              value={draft.welcome}
              onChange={(e) => setDraft(d => ({ ...d, welcome: e.target.value }))}
              rows={3}
              style={{ ...inputStyle, lineHeight: 1.55, resize: "vertical" }}
              onFocus={(e) => e.target.style.borderColor = t.accent + "70"}
              onBlur={(e) => e.target.style.borderColor = p.border}
            />
          </div>

          {/* Model + temperature */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 30 }}>
            <div>
              <label style={labelStyle}>Modelo</label>
              <select
                value={draft.model}
                onChange={(e) => setDraft(d => ({ ...d, model: e.target.value }))}
                style={{ ...inputStyle, cursor: "default" }}>
                {MODEL_IDS.map(id => (
                  <option key={id} value={id}>{MODEL_LABELS[id]}</option>
                ))}
              </select>
            </div>
            <div>
              <label style={labelStyle}>Creatividad · {draft.temperature.toFixed(1)}</label>
              <div style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "13px 14px",
                background: p.bg2, border: `1px solid ${p.border}`, borderRadius: 10,
              }}>
                <span style={{ fontFamily: "'Geist', sans-serif", fontSize: 11, color: p.textDim }}>Preciso</span>
                <input type="range" min="0" max="1" step="0.1"
                       value={draft.temperature}
                       onChange={(e) => setDraft(d => ({ ...d, temperature: parseFloat(e.target.value) }))}
                       style={{ flex: 1, accentColor: t.accent }} />
                <span style={{ fontFamily: "'Geist', sans-serif", fontSize: 11, color: p.textDim }}>Creativo</span>
              </div>
            </div>
          </div>

          {/* Save bar */}
          <div style={{
            display: "flex", alignItems: "center", gap: 14,
            paddingTop: 22, borderTop: `1px solid ${p.borderSoft}`,
          }}>
            <button onClick={save} disabled={!isModified && !saved}
                    style={{
                      padding: "11px 22px",
                      background: isModified ? t.accent : p.bg2,
                      border: `1px solid ${isModified ? t.accent : p.border}`,
                      borderRadius: 9,
                      color: isModified ? "#0A0A0A" : p.textMuted,
                      fontFamily: "'Geist', sans-serif", fontSize: 13.5, fontWeight: 600,
                      cursor: "default", display: "flex", alignItems: "center", gap: 8,
                    }}>
              {saved ? (
                <>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                       stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="m5 12 5 5L20 7"/>
                  </svg>
                  Guardado
                </>
              ) : "Guardar cambios"}
            </button>
            {isModified && (
              <span style={{
                fontFamily: "'Geist', sans-serif", fontSize: 12.5,
                color: p.textMuted,
              }}>Tenés cambios sin guardar</span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.AgentConfigView = AgentConfigView;
