/* bots.jsx - My Bots: list all agents owned by the signed-in user */

function toActiveAgent(bot) {
  return {
    modelId: bot.slug || bot.id || bot.modelId,
    name: bot.name,
    ownerAddress: bot.ownerAddress,
    systemPrompt: bot.systemPrompt,
    openingMessage: bot.openingMessage,
    voicePreset: bot.voicePreset,
    setupCustomized: bot.setupCustomized === true,
  };
}

function DeleteBotDialog({ bot, busy, onCancel, onConfirm }) {
  if (!bot) return null;
  const name = bot.name || "Untitled bot";
  return (
    <div className="scrim" role="presentation" onMouseDown={(e) => { if (e.target === e.currentTarget && !busy) onCancel(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="delete-bot-title" style={{ maxWidth: 480 }}>
        <div className="card-hd between" style={{ gap: 16 }}>
          <div className="row" style={{ gap: 12, minWidth: 0 }}>
            <div style={{ width: 38, height: 38, borderRadius: "var(--r-sm)", background: "var(--bad-bg)", color: "var(--bad)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
              {I("alert", { style: { width: 19, height: 19 } })}
            </div>
            <div style={{ minWidth: 0 }}>
              <div id="delete-bot-title" className="h3">Delete bot</div>
              <div className="caption" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</div>
            </div>
          </div>
          <button className="icon-btn" disabled={busy} onClick={onCancel} style={{ width: 32, height: 32 }}>{I("x", { style: { width: 15, height: 15 } })}</button>
        </div>
        <div className="card-pad stack" style={{ gap: 14 }}>
          <div style={{ fontSize: 13.5, lineHeight: 1.55, color: "var(--ink-2)" }}>
            This permanently removes this bot and its saved knowledge, conversations, and evaluation data.
          </div>
          <div className="stack" style={{ gap: 8, padding: 12, border: "1px solid var(--border)", borderRadius: "var(--r-sm)", background: "var(--surface-2)" }}>
            {["All previously uploaded PDFs", "Parsed chunks and embeddings", "Saved chat history", "Evaluation results and deployment settings"].map(item => (
              <div key={item} className="row" style={{ gap: 8, fontSize: 12.5, color: "var(--ink-2)" }}>
                {I("check", { style: { width: 13, height: 13, color: "var(--bad)" } })}
                <span>{item}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="row" style={{ justifyContent: "flex-end", gap: 10, padding: "14px 18px", borderTop: "1px solid var(--border)", background: "var(--surface-2)" }}>
          <button className="btn btn-secondary" disabled={busy} onClick={onCancel}>Cancel</button>
          <button className="btn btn-primary" disabled={busy} onClick={onConfirm} style={{ background: "var(--bad)", color: "white", borderColor: "var(--bad)" }}>
            {busy ? "Deleting..." : "Delete bot"}
          </button>
        </div>
      </div>
    </div>
  );
}
function CreateBotDialog({ open, name, busy, error, onNameChange, onCancel, onConfirm }) {
  if (!open) return null;
  const suggestions = ["Support assistant", "Sales assistant", "Policy helper"];
  const canCreate = name.trim().length > 0 && !busy;
  return (
    <div className="scrim" role="presentation" onMouseDown={(e) => { if (e.target === e.currentTarget && !busy) onCancel(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="create-bot-title" style={{ maxWidth: 500 }}>
        <div className="card-hd between" style={{ gap: 16 }}>
          <div className="row" style={{ gap: 12, minWidth: 0 }}>
            <div style={{ width: 38, height: 38, borderRadius: "var(--r-sm)", background: "var(--primary-soft)", color: "var(--ink)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
              {I("bot", { style: { width: 19, height: 19 } })}
            </div>
            <div style={{ minWidth: 0 }}>
              <div id="create-bot-title" className="h3">New bot</div>
              <div className="caption">Create a dedicated RAG chatbot.</div>
            </div>
          </div>
          <button className="icon-btn" disabled={busy} onClick={onCancel} style={{ width: 32, height: 32 }}>{I("x", { style: { width: 15, height: 15 } })}</button>
        </div>
        <div className="card-pad stack" style={{ gap: 14 }}>
          <label>
            <span className="field-label">Bot name</span>
            <input
              className="input"
              autoFocus
              value={name}
              placeholder="Support assistant"
              onChange={(e) => onNameChange(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && canCreate) onConfirm();
                if (e.key === "Escape" && !busy) onCancel();
              }}
            />
          </label>
          <div className="row wrap" style={{ gap: 8 }}>
            {suggestions.map(item => (
              <button key={item} type="button" className="chip" onClick={() => onNameChange(item)} disabled={busy}>
                {item}
              </button>
            ))}
          </div>
          {error && (
            <div className="row" style={{ gap: 8, padding: "10px 12px", background: "var(--bad-bg)", borderRadius: "var(--r-sm)", border: "1px solid var(--bad-border)", color: "var(--bad)" }}>
              {I("alert", { style: { width: 15, height: 15, flex: "none" } })}
              <span style={{ fontSize: 12.5, fontWeight: 500 }}>{error}</span>
            </div>
          )}
        </div>
        <div className="row" style={{ justifyContent: "flex-end", gap: 10, padding: "14px 18px", borderTop: "1px solid var(--border)", background: "var(--surface-2)" }}>
          <button className="btn btn-secondary" disabled={busy} onClick={onCancel}>Cancel</button>
          <button className="btn btn-primary" disabled={!canCreate} onClick={onConfirm}>
            {busy ? "Creating..." : "Create bot"}
          </button>
        </div>
      </div>
    </div>
  );
}
const DEMO_BOTS = [
  {
    id: "demo-flo",
    modelId: "demo-flo",
    slug: "demo-flo",
    name: "Flo",
    ownerAddress: "demo-florence",
    createdAt: "2026-07-12T12:00:00.000Z",
    accessCount: 0,
  },
];

function BotCard({ bot, active, deleting, onSelect, onDelete }) {
  const created = bot.createdAt
    ? new Date(bot.createdAt).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" })
    : "-";
  return (
    <div className={cx("card card-pad", active && "card-active")} onClick={onSelect}
      style={{ display: "flex", flexDirection: "column", gap: 8, cursor: "pointer", transition: "border-color .15s, box-shadow .15s",
        borderColor: active ? "var(--primary)" : undefined, boxShadow: active ? "0 0 0 2px var(--primary-bg)" : undefined }}>
      <div className="between" style={{ gap: 12 }}>
        <div className="row" style={{ gap: 10, minWidth: 0 }}>
          <div style={{ width: 34, height: 34, borderRadius: "var(--r-sm)", background: active ? "var(--primary)" : "var(--primary-bg)", color: active ? "var(--primary-ink)" : "var(--primary)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none", transition: "background .15s, color .15s" }}>
            {I("bot", { style: { width: 17, height: 17 } })}
          </div>
          <div style={{ minWidth: 0 }}>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ fontSize: 13.5, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{bot.name || "Untitled bot"}</span>
              {active && <span className="badge badge-good" style={{ fontSize: 10, padding: "1px 6px" }}>Active</span>}
            </div>
            <div className="caption">{created}</div>
          </div>
        </div>
        <div className="row" style={{ gap: 8, flex: "none" }}>
          {bot.accessCount != null && (
            <span className="caption tnum" style={{ flex: "none" }}>{bot.accessCount} queries</span>
          )}
          <button className="icon-btn" title="Delete bot" disabled={deleting} onClick={(e) => { e.stopPropagation(); onDelete?.(); }} style={{ width: 30, height: 30, color: "var(--bad)" }}>
            {deleting ? <span className="spin" style={{ display: "inline-flex" }}>{I("refresh", { style: { width: 14, height: 14 } })}</span> : I("x", { style: { width: 14, height: 14 } })}
          </button>
        </div>
      </div>
      <div className="caption" style={{ fontSize: 12, opacity: 0.75, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
        Ready for Playground and Deploy
      </div>
    </div>
  );
}

function BotsView({ ctx }) {
  const { user: authUser, loading: authLoading, signIn } = useFirebaseAuth();
  const [bots, setBots] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [switched, setSwitched] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [deleting, setDeleting] = React.useState(null);
  const [deleteTarget, setDeleteTarget] = React.useState(null);
  const [createOpen, setCreateOpen] = React.useState(false);
  const [createName, setCreateName] = React.useState("");
  const [createError, setCreateError] = React.useState(null);

  React.useEffect(() => {
    if (authLoading) return;
    if (!authUser) { setLoading(false); setBots([]); return; }
    if (authUser.isDemo) { setBots(DEMO_BOTS); setLoading(false); return; }
    let cancelled = false;
    setLoading(true);
    window.ModelOSIntegrations.listAgents(authUser).then(agents => {
      if (cancelled) return;
      setBots(agents);
      setLoading(false);
    });
    return () => { cancelled = true; };
  }, [authUser, authLoading]);

  const handleSelect = (bot) => {
    const agent = toActiveAgent(bot);
    window.ModelOSIntegrations.save({ activeAgent: agent });
    ctx.setActiveAgent(agent);
    setSwitched(bot.name || "Untitled bot");
    setTimeout(() => setSwitched(null), 2000);
  };


  const handleDelete = async (bot) => {
    const modelId = bot.slug || bot.id || bot.modelId;
    if (!modelId || deleting) return;
    setDeleteTarget(bot);
  };

  const confirmDelete = async () => {
    const bot = deleteTarget;
    const modelId = bot?.slug || bot?.id || bot?.modelId;
    if (!modelId || deleting) return;
    setDeleting(modelId);
    try {
      await window.ModelOSIntegrations.deleteAgent(modelId, authUser);
      setBots(prev => prev.filter(item => (item.slug || item.id || item.modelId) !== modelId));
      if (ctx.activeAgent?.modelId === modelId) {
        ctx.setActiveAgent(null);
        window.ModelOSIntegrations.save({ activeAgent: null });
        window.ModelOSUserStorage.remove(authUser.uid, "activeAgent");
        window.ModelOSUserStorage.remove(authUser.uid, "knowledgeSources");
        window.ModelOSUserStorage.remove(authUser.uid, `knowledgeSources:${modelId}`);
        window.ModelOSUserStorage.remove(authUser.uid, "playgroundMsgs");
      }
      setDeleteTarget(null);
      setSwitched(`${bot.name || "Bot"} deleted`);
      setTimeout(() => setSwitched(null), 2200);
    } catch (err) {
      setError("Failed to delete bot: " + (err.message || "Unknown error"));
    } finally {
      setDeleting(null);
    }
  };
  const handleCreate = async () => {
    if (authUser?.isDemo) {
      await signIn();
      return;
    }
    setCreateName("");
    setCreateError(null);
    setCreateOpen(true);
  };

  const confirmCreate = async () => {
    const cleanName = createName.trim();
    if (!cleanName) {
      setCreateError("Add a name before creating your bot.");
      return;
    }
    setCreating(true);
    setCreateError(null);
    try {
      const agent = await window.ModelOSIntegrations.createAgent(cleanName, authUser);
      ctx.setActiveAgent(agent);
      setBots(prev => [{ ...agent, id: agent.modelId, createdAt: new Date().toISOString() }, ...prev]);
      setCreateOpen(false);
      setCreateName("");
      ctx.setView("knowledge");
    } catch (err) {
      setCreateError("Failed to create bot: " + (err.message || "Unknown error"));
    } finally {
      setCreating(false);
    }
  };
  const activeModelId = ctx.activeAgent?.modelId;

  if (authLoading || loading) {
    return (
      <div className="page">
        <PageHead eyebrow="Manage" title="My Bots" sub="View all chatbots you have created." />
        <div className="caption" style={{ padding: 32, textAlign: "center" }}>Loading bots...</div>
      </div>
    );
  }

  if (!authUser) {
    return (
      <div className="page">
        <PageHead eyebrow="Manage" title="My Bots" sub="View all chatbots you have created." />
        <Empty icon="lock" title="Sign in required" sub="Sign in with Google to view your bots." />
      </div>
    );
  }

  return (
    <>
      <CreateBotDialog
        open={createOpen}
        name={createName}
        busy={creating}
        error={createError}
        onNameChange={(value) => { setCreateName(value); if (createError) setCreateError(null); }}
        onCancel={() => { if (!creating) { setCreateOpen(false); setCreateError(null); } }}
        onConfirm={confirmCreate}
      />
      <DeleteBotDialog bot={deleteTarget} busy={Boolean(deleting)} onCancel={() => !deleting && setDeleteTarget(null)} onConfirm={confirmDelete} />
      <div className="page">
      <PageHead eyebrow="Manage" title="My Bots"
        sub="View all chatbots you have created. Each bot has its own knowledge base built from your uploaded PDFs.">
        <button className="btn btn-primary" disabled={creating} onClick={handleCreate}>
          {I("plus", { style: { width: 15, height: 15 } })} {creating ? "Creating..." : "New Bot"}
        </button>
      </PageHead>


      {error && (
        <div className="row" style={{ gap: 8, marginBottom: 16, padding: "10px 14px", background: "var(--bad-bg)", borderRadius: "var(--r-md)", border: "1px solid var(--bad-border)", color: "var(--bad)" }}>
          {I("alert", { style: { width: 16, height: 16 } })}
          <span style={{ fontSize: 13, fontWeight: 500 }}>{error}</span>
          <button className="icon-btn" onClick={() => setError(null)} style={{ width: 24, height: 24, marginLeft: "auto", color: "var(--bad)" }}>{I("x", { style: { width: 13, height: 13 } })}</button>
        </div>
      )}
      {switched && (
        <div className="row" style={{ gap: 8, marginBottom: 16, padding: "10px 14px", background: "var(--good-bg)", borderRadius: "var(--r-md)", border: "1px solid var(--good-border)" }}>
          {I("checkCircle", { style: { width: 16, height: 16, color: "var(--good-strong)" } })}
          <span style={{ fontSize: 13, color: "var(--good-strong)", fontWeight: 500 }}>Switched to {switched}</span>
        </div>
      )}

      {bots.length === 0 ? (
        <Empty icon="bot" title="No bots yet"
          sub="Upload a PDF in Knowledge base to create your first bot." />
      ) : (
        <div className="stack" style={{ gap: 12, maxWidth: 640 }}>
          {bots.map(bot => {
            const botModelId = bot.slug || bot.id || bot.modelId;
            return (
              <BotCard key={botModelId} bot={bot}
                active={activeModelId === botModelId}
                deleting={deleting === botModelId}
                onSelect={() => handleSelect(bot)}
                onDelete={() => handleDelete(bot)} />
            );
          })}
        </div>
      )}
      </div>
    </>
  );
}

window.BotsView = BotsView;
