import { useEffect, useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../../auth/AuthContext";
import { AccountAvatar } from "../ui/AccountAvatar";
import { AppIcon } from "../ui/AppIcons";
import { useI18n } from "../../i18n/I18nContext";
import { memberRoleSummary } from "../../lib/memberRole";
import { can, Permission } from "../../lib/permissions";
import { useTheme } from "../../theme/ThemeContext";

/**
 * 頂欄帳號選單：會員資料、設定、主題、登出。
 * 用量與方案改由頂欄 UsagePlanWidget 處理。
 */
export function AccountMenu() {
  const { member, logout } = useAuth();
  const { t } = useI18n();
  const { resolved, toggle } = useTheme();
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function onDoc(e: MouseEvent) {
      if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  const name = member?.display_name || "…";
  const role = memberRoleSummary(member, t);
  const avatarAccount = {
    display_name: name,
    username: member?.email || "user",
    avatar_color: "var(--hb-brand)",
    avatar_url: member?.avatar_url,
  };

  return (
    <div className="hb-account" ref={rootRef}>
      <button
        type="button"
        className={`hb-account__trigger${open ? " is-open" : ""}`}
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        aria-haspopup="menu"
        title={`${member?.email || t("topbar.account")} · ${role.primaryLabel}`}
      >
        <AccountAvatar account={avatarAccount} className="hb-account__avatar" />
        <span className="hb-account__name">{name}</span>
        <span className="hb-account__chev" aria-hidden>
          <AppIcon name="chevron" size={18} />
        </span>
      </button>

      {open ? (
        <div className="hb-account__panel" role="menu">
          <div className="hb-account__meta">
            <div className="hb-account__meta-head">
              <AccountAvatar account={avatarAccount} size="md" />
              <div className="hb-account__meta-text">
                <strong>{name}</strong>
                <span className="text-muted">{member?.email || "—"}</span>
              </div>
            </div>
            <div className="hb-account__badges">
              <span className={`hb-account__role${role.isAdmin ? " is-admin" : ""}`}>
                {role.primaryLabel}
              </span>
              <span
                className={`hb-account__role${member?.email_verified ? " is-verified" : " is-unverified"}`}
              >
                {member?.email_verified ? t("role.verified") : t("role.unverified")}
              </span>
            </div>
          </div>
          <nav className="hb-account__nav">
            {can(member?.roles, Permission.AdminMembersList) ? (
              <Link
                role="menuitem"
                to="/app/users"
                className="hb-account__link"
                onClick={() => setOpen(false)}
              >
                {t("nav.users")}
              </Link>
            ) : null}
            <Link
              role="menuitem"
              to="/app/profile"
              className="hb-account__link"
              onClick={() => setOpen(false)}
            >
              {t("nav.profile")}
            </Link>
            <Link
              role="menuitem"
              to="/app/invite"
              className="hb-account__link"
              onClick={() => setOpen(false)}
            >
              {t("nav.invite")}
            </Link>
            <Link
              role="menuitem"
              to="/app/settings"
              className="hb-account__link"
              onClick={() => setOpen(false)}
            >
              {t("nav.settings")}
            </Link>
            <button
              type="button"
              role="menuitem"
              className="hb-account__link hb-account__link--btn"
              onClick={() => {
                toggle();
              }}
            >
              {resolved === "dark" ? t("settings.themeToLight") : t("settings.themeToDark")}
            </button>
          </nav>
          <button
            type="button"
            role="menuitem"
            className="hb-account__logout"
            onClick={() => {
              setOpen(false);
              void logout().then(() => navigate("/login"));
            }}
          >
            {t("nav.logout")}
          </button>
        </div>
      ) : null}
    </div>
  );
}
