import { useState } from "react";
import type { CfAccount } from "../types";
import { useDomainflare } from "../context/DomainflareContext";

/** 侧边栏：账号列表与添加 */
export function AccountsSection() {
  const {
    accounts,
    activeAccountId,
    selectAccount,
    deleteAccount,
    addAccount,
    toast,
  } = useDomainflare();
  const [name, setName] = useState("");
  const [token, setToken] = useState("");

  async function onAdd() {
    const t = token.trim();
    if (!t) {
      toast("请填写 API Token", true);
      return;
    }
    try {
      await addAccount(name.trim(), t);
      setName("");
      setToken("");
    } catch (e) {
      toast(e instanceof Error ? e.message : String(e), true);
    }
  }

  async function onDelete(a: CfAccount) {
    try {
      await deleteAccount(a);
    } catch (e) {
      toast(e instanceof Error ? e.message : String(e), true);
    }
  }

  return (
    <section className="panel">
      <h3>Cloudflare 账号</h3>
      <div id="account-list" className="stack">
        {accounts.map((a) => (
          <div
            key={a.id}
            className={`account-item${a.id === activeAccountId ? " active" : ""}`}
          >
            <span>{a.name || "未命名"}</span>
            <span>
              <button
                type="button"
                className="btn ghost tiny"
                disabled={a.id === activeAccountId}
                onClick={() => selectAccount(a.id)}
              >
                {a.id === activeAccountId ? "当前" : "切换"}
              </button>
              <button
                type="button"
                className="btn ghost tiny danger"
                onClick={() => void onDelete(a)}
              >
                删除
              </button>
            </span>
          </div>
        ))}
      </div>
      {!accounts.length ? <p className="muted small">尚未添加账号。</p> : null}

      <details className="details">
        <summary>添加账号</summary>
        <label className="field">
          <span>显示名称</span>
          <input
            id="acct-name"
            type="text"
            placeholder="例如：个人 / 公司"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </label>
        <label className="field">
          <span>API Token</span>
          <input
            id="acct-token"
            type="password"
            autoComplete="off"
            placeholder="Zone DNS Edit 或更广权限"
            value={token}
            onChange={(e) => setToken(e.target.value)}
          />
        </label>
        <button type="button" id="acct-add" className="btn secondary small" onClick={() => void onAdd()}>
          保存账号
        </button>
      </details>
    </section>
  );
}
