// Bot detail screen: header + tabs (Overview, Settings, Danger zone).
// Uses real BotApi.get(id) — no mock data.

const { useState } = React;

// ─── Detail label/value pair ─────────────────────────────────────────────
const DetailRow = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 11, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 4, fontWeight: 500 }}>{label}</div>
    <div style={{ fontSize: 13 }}>{value || <span className="muted">—</span>}</div>
  </div>
);

// ─── Danger zone row ─────────────────────────────────────────────────────
const DangerRow = ({ title, desc, action }) => (
  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 14px", border: "1px solid var(--border)", borderRadius: 6 }}>
    <div>
      <div style={{ fontWeight: 500, fontSize: 13 }}>{title}</div>
      <div className="muted" style={{ fontSize: 12 }}>{desc}</div>
    </div>
    {action}
  </div>
);

// ─── Overview tab ────────────────────────────────────────────────────────
const BotOverview = ({ bot }) => (
  <div className="stack">
    <div className="kpi-row">
      <Kpi label="Messages processed" value={(bot.messages_processed || 0).toLocaleString()} />
      <Kpi label="Messages forwarded" value={(bot.messages_forwarded || 0).toLocaleString()} />
      <Kpi label="Last active" value={relativeTime(bot.last_active)} />
      <Kpi label="Status" value={<StatusBadge status={bot.status} />} />
    </div>
    <Card title="Connection details">
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
        <DetailRow label="Platform" value={<PlatformChip platform={bot.platform} />} />
        <DetailRow label="Phone" value={<span className="mono">{bot.phone}</span>} />
        <DetailRow label="Proxy" value={<span className="mono">{bot.proxy || "None"}</span>} />
        <DetailRow label="AI enabled" value={bot.ai_enabled ? <span className="badge green"><span className="dot"></span>Yes</span> : <span className="badge">No</span>} />
        <DetailRow label="Auth status" value={<StatusBadge status={bot.status} />} />
        <DetailRow label="Last error" value={bot.last_error ? <span className="muted" style={{ fontSize: 12 }}>{bot.last_error}</span> : "None"} />
      </div>
    </Card>
  </div>
);

// ─── Settings tab ────────────────────────────────────────────────────────
const BotSettings = ({ bot, onSaved }) => {
  const toast = useToast();
  const [form, setForm] = useState({
    _id: bot._id,
    name: bot.name || "",
    phone: bot.phone || "",
    platform: bot.platform || "telegram",
    proxy: bot.proxy || "",
    ai_enabled: bot.ai_enabled || false,
    prompt_persona: bot.prompt_persona || "",
  });
  const [saving, setSaving] = useState(false);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSave = async () => {
    setSaving(true);
    try {
      await BotApi.save(form);
      toast.success("Bot settings saved");
      onSaved();
    } catch (e) {
      toast.error(e.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="grid-2">
      <Card title="General settings">
        <div className="field">
          <label className="field-label">Display name</label>
          <input className="input" value={form.name} onChange={(e) => set("name", e.target.value)} />
        </div>
        <div className="field">
          <label className="field-label">Phone</label>
          <input className="input mono" value={form.phone} onChange={(e) => set("phone", e.target.value)} />
        </div>
        <div className="field">
          <label className="field-label">Proxy <span className="muted">(ip:port:user:pass)</span></label>
          <input className="input mono" value={form.proxy} onChange={(e) => set("proxy", e.target.value)} placeholder="None" />
        </div>
        <div className="field">
          <label className="field-label" style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>AI translation enabled</span>
            <input type="checkbox" checked={form.ai_enabled} onChange={(e) => set("ai_enabled", e.target.checked)} />
          </label>
        </div>
        {form.ai_enabled && (
          <div className="field">
            <label className="field-label">AI persona prompt</label>
            <textarea className="input" style={{ height: 80, padding: "8px 10px" }} value={form.prompt_persona} onChange={(e) => set("prompt_persona", e.target.value)} placeholder="Custom prompt…" />
          </div>
        )}
        <div style={{ marginTop: 8 }}>
          <button className="btn primary" onClick={handleSave} disabled={saving}>
            {saving ? "Saving…" : "Save changes"}
          </button>
        </div>
      </Card>
    </div>
  );
};

// ─── Bot detail page ─────────────────────────────────────────────────────
const BotDetail = ({ botId, onBack }) => {
  const toast = useToast();
  const confirm = useConfirm();
  const [tab, setTab] = useState("overview");
  const { data: bot, loading, error, refetch } = useApi(() => BotApi.get(botId), [botId]);

  const handleLifecycle = async (action) => {
    try {
      if (action === "start") await BotApi.start(botId);
      if (action === "stop") await BotApi.stop(botId);
      if (action === "restart") await BotApi.restart(botId);
      toast.success(`Bot ${action}ed`);
      refetch();
    } catch (e) {
      toast.error(e.message);
    }
  };

  const handleDelete = async () => {
    const ok = await confirm("Delete bot", `Delete "${bot?.name}"? This cannot be undone.`);
    if (!ok) return;
    try {
      await BotApi.delete(botId);
      toast.success("Bot deleted");
      onBack();
    } catch (e) {
      toast.error(e.message);
    }
  };

  if (loading) return (
    <div className="page">
      <div className="muted" style={{ paddingTop: 40, textAlign: "center" }}>Loading bot…</div>
    </div>
  );

  if (error || !bot) return (
    <div className="page">
      <Empty icon={I.AlertTriangle} title="Failed to load bot" sub={error} action={<button className="btn" onClick={refetch}><I.Refresh /> Retry</button>} />
    </div>
  );

  return (
    <div className="page">
      {/* Back nav */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, fontSize: 12 }}>
        <button className="btn ghost sm" onClick={onBack}><I.ChevronLeft /> Bots</button>
        <span className="muted">/</span>
        <span className="mono muted">{bot._id}</span>
      </div>

      {/* Header */}
      <div className="page-head">
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <Avatar name={bot.name} size="lg" />
          <div>
            <h1 className="page-title" style={{ display: "flex", alignItems: "center", gap: 10 }}>
              {bot.name}
              <StatusBadge status={bot.status} />
            </h1>
            <div style={{ display: "flex", gap: 12, alignItems: "center", color: "var(--fg-3)", fontSize: 13 }}>
              <PlatformChip platform={bot.platform} />
              <span className="mono">{bot.phone}</span>
              <span>·</span>
              <span>Last seen {relativeTime(bot.last_active)}</span>
            </div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <button className="btn" onClick={() => handleLifecycle("start")}><I.Play /> Start</button>
          <button className="btn" onClick={() => handleLifecycle("stop")}><I.Pause /> Stop</button>
          <button className="btn" onClick={() => handleLifecycle("restart")}><I.Refresh /> Restart</button>
        </div>
      </div>

      {/* Tabs */}
      <div className="tabs">
        {[{ id: "overview", label: "Overview" }, { id: "settings", label: "Settings" }].map((t) => (
          <button key={t.id} className={`tab ${tab === t.id ? "active" : ""}`} onClick={() => setTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === "overview" && <BotOverview bot={bot} />}
      {tab === "settings" && (
        <div className="stack">
          <BotSettings bot={bot} onSaved={refetch} />
          <Card title="Danger zone">
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <DangerRow
                title="Pause bot"
                desc="Stops receiving and forwarding messages."
                action={<button className="btn" onClick={() => handleLifecycle("stop")}><I.Pause /> Pause</button>}
              />
              <DangerRow
                title="Re-authenticate"
                desc="Force a new OTP + 2FA auth flow."
                action={<button className="btn" onClick={() => window.__navigate("auth", { preselectedBotId: bot._id })}><I.Key /> Re-auth</button>}
              />
              <DangerRow
                title="Delete bot"
                desc="Permanent. Removes session and all data."
                action={<button className="btn danger" onClick={handleDelete}><I.Trash /> Delete</button>}
              />
            </div>
          </Card>
        </div>
      )}
    </div>
  );
};

window.BotDetail = BotDetail;
