// smax-bot-fields.jsx — Zalo/Smax pieces of the bot form + webhook setup panel.
// SmaxBotFields: biz alias + token → "Load pages" → pick our Zalo nick (page_pid).
// SmaxWebhookPanel: the URL / header / body to paste into Smax's webhook settings.

const SmaxBotFields = ({ form, set, setForm, isEdit, botId }) => {
  const toast = useToast();
  const [pages, setPages] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  const loadPages = async () => {
    setLoading(true);
    try {
      // Edit with blank token → let the server use the stored token.
      const body = form.smaxToken ? { bizAlias: form.smaxBizAlias, token: form.smaxToken } : { bot_id: botId };
      const list = await ZaloApi.listSmaxPages(body);
      setPages(list);
      if (!list.length) toast.error("Biz này chưa có nick Zalo nào trên Smax");
    } catch (e) {
      toast.error(e.message);
    } finally {
      setLoading(false);
    }
  };

  const pickPage = (pid) => {
    const page = (pages || []).find((p) => p.pid === pid);
    setForm((f) => ({ ...f, smaxPagePid: pid, name: f.name || (page ? page.name : "") }));
  };

  const canLoad = form.smaxBizAlias && (form.smaxToken || (isEdit && botId));
  return (
    <>
      <div className="field">
        <label className="field-label">Smax biz alias</label>
        <input className="input mono" value={form.smaxBizAlias || ""} onChange={(e) => set("smaxBizAlias", e.target.value)} placeholder="vd: trillion-hubz" />
      </div>
      <div className="field">
        <label className="field-label">Smax API token{isEdit ? " (để trống = giữ token cũ)" : ""}</label>
        <input className="input mono" type="password" autoComplete="off" value={form.smaxToken || ""} onChange={(e) => set("smaxToken", e.target.value)} placeholder="eyJhbGciOi…" />
      </div>
      <div className="field">
        <label className="field-label" style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span>Nick Zalo (page)</span>
          <button className="btn ghost sm" type="button" onClick={loadPages} disabled={!canLoad || loading}>
            {loading ? "Đang tải…" : "Tải danh sách nick"}
          </button>
        </label>
        {pages && pages.length ? (
          <select className="select" value={form.smaxPagePid || ""} onChange={(e) => pickPage(e.target.value)}>
            <option value="">— Chọn nick Zalo —</option>
            {pages.map((p) => (
              <option key={p.pid} value={p.pid}>{p.name} · {p.platform} · {p.pid}</option>
            ))}
          </select>
        ) : (
          <input className="input mono" value={form.smaxPagePid || ""} onChange={(e) => set("smaxPagePid", e.target.value)} placeholder="zlw622494008053814319" />
        )}
      </div>
    </>
  );
};

const CopyRow = ({ label, value }) => {
  const toast = useToast();
  const copy = () => navigator.clipboard?.writeText(value).then(() => toast.info(`Đã copy ${label}`)).catch(() => {});
  return (
    <div className="field">
      <label className="field-label">{label}</label>
      <div style={{ display: "flex", gap: 6 }}>
        <input className="input mono" readOnly value={value} style={{ flex: 1, minWidth: 0 }} />
        <button className="btn ghost sm" type="button" onClick={copy}>Copy</button>
      </div>
    </div>
  );
};

const SmaxWebhookPanel = ({ botId }) => {
  const toast = useToast();
  const [info, setInfo] = React.useState(null);
  React.useEffect(() => {
    if (!botId) return;
    ZaloApi.smaxWebhookInfo(botId).then(setInfo).catch((e) => toast.error(e.message));
  }, [botId]);
  if (!botId || !info) return null;
  const rotate = async () => {
    if (!window.confirm("Tạo secret mới? Secret cũ sẽ ngừng hoạt động — phải cập nhật lại trên Smax.")) return;
    try { setInfo(await ZaloApi.rotateSmaxSecret(botId)); toast.info("Đã tạo secret mới"); } catch (e) { toast.error(e.message); }
  };
  return (
    <div className="card" style={{ padding: 12, marginTop: 8 }}>
      <div style={{ fontWeight: 600, marginBottom: 6 }}>Cài webhook trên Smax (Source Zalo)</div>
      <CopyRow label="URL (POST)" value={info.url} />
      <CopyRow label={`Header ${info.header}`} value={info.secret} />
      <CopyRow label="Body (JSON)" value={info.body} />
      <button className="btn ghost sm" type="button" onClick={rotate}>Tạo secret mới</button>
    </div>
  );
};

Object.assign(window, { SmaxBotFields, SmaxWebhookPanel });
