import { useRef, useState } from "react";
import { useOutsideDismiss } from "../../shared/hooks/useOutsideDismiss.js";
import { useBackLayer } from "../../app/useBackLayer.js";
import { accountDisplayName, accountStatusLabel, visibleAccountOptions } from "../accounts/account-display.js";
import { AccountIdentity } from "../accounts/AccountIdentity.jsx";
import { NotificationCenter } from "../notifications/NotificationCenter.jsx";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { ResetCreditDialog } from "../../shared/ResetCreditDialog.jsx";
import { CloseIcon } from "../../shared/ActionIcons.jsx";
import { accountSwitchAllowed, chatProgressLabel, lastChatProjectLabel } from "./context-state.js";
import { MessageCopyButton } from "../conversation/MessageCopyButton.jsx";
import { runtimeChannel } from "../../platform/runtime-channel.js";

const noop = () => {};

export function ContextBar({ account, project, session, accounts = [], accountId, accountMosaic = false, accountSwitchLocked = false, accountSwitchAccountId = "", notifications = [], sessions = [], currentSession, threads = [], notificationError, notificationRefreshErrors = [], usageStatus, onAccountChange, onChatOpen, onSettingsOpen, onPopupOpen, onNotificationOpen, onNotificationDismiss, onActiveSessionOpen, onNotificationsClear, onUseResetCredit, manager }) {
  const { t } = useI18n();
  const [menuOpen, setMenuOpen] = useState(false);
  const [resetAccountName, setResetAccountName] = useState("");
  const accountMenuRef = useRef(null);
  const accountButtonRef = useRef(null);
  const visibleAccounts = visibleAccountOptions(accounts, accountId);
  const lockedAccountId = accountSwitchLocked ? accountSwitchAccountId || accountId : "";
  const closeAccountMenu = useBackLayer(menuOpen, () => setMenuOpen(false), "account-menu");
  const closeLogin = useBackLayer(Boolean(manager.login), manager.dismissLogin, "account-login");
  useOutsideDismiss(accountMenuRef, closeAccountMenu, menuOpen, { returnFocusRef: accountButtonRef });

  async function selectAccount(accountOption) {
    if (accountOption.entitlementLocked || !accountSwitchAllowed(accountOption.id, accountId, lockedAccountId)) return;
    closeAccountMenu(async () => {
      onAccountChange(accountOption.id);
      if (accountOption.status !== "logged_in") await manager.connect(accountOption.id);
    });
  }

  function openSettings() {
    closeAccountMenu(() => onSettingsOpen?.());
  }

  function toggleAccountMenu() {
    if (menuOpen) {
      closeAccountMenu();
      return;
    }
    const openAccountMenu = () => setMenuOpen(true);
    if (onPopupOpen) onPopupOpen(openAccountMenu);
    else openAccountMenu();
  }

  function openResetCredit(accountOption) {
    closeAccountMenu(() => setResetAccountName(accountDisplayName(accountOption, accounts)));
  }

  return <header className="context-bar">
    <div className="context-account" ref={accountMenuRef}>
      <button className="context-account-button" type="button" ref={accountButtonRef} title={account ? t("context.manageAccount") : t("context.signIn")} onClick={toggleAccountMenu} aria-expanded={menuOpen} aria-haspopup="menu">
        <strong><AccountIdentity account={account} accounts={accounts} mosaic={accountMosaic} /></strong><span className="context-account-meta"><span>{accountStatusLabel(account)}</span>{runtimeChannel === "development" && <span className="context-runtime-badge context-runtime-badge--development">{t("runtime.development")}</span>}</span>
      </button>
      {menuOpen && <div className="context-account-menu" role="menu">
        <div className="context-account-menu-title">{t("context.accounts")}</div>
        {accountSwitchLocked && <span className="context-account-lock">{t("context.switchLocked")}</span>}
        {visibleAccounts.map((accountOption) => <div key={accountOption.id} className={`context-account-option${accountOption.id === accountId ? " active" : ""}`}>
          <button type="button" role="menuitem" disabled={accountOption.entitlementLocked || !accountSwitchAllowed(accountOption.id, accountId, lockedAccountId)} onClick={() => selectAccount(accountOption)}>
            <strong><AccountIdentity account={accountOption} accounts={accounts} mosaic={accountMosaic} />{accountOption.entitlementLocked && " 🔒 Pro"}</strong><span>{accountStatusLabel(accountOption)}</span>
          </button>
          {accountOption.id === accountId && accountOption.status === "logged_in" && <div className="context-reset-credit">
            <span>{t("context.resetCredits", { count: Number.isSafeInteger(usageStatus?.usage?.resetCreditsAvailable) ? usageStatus.usage.resetCreditsAvailable : t("context.unavailable") })}</span>
            {(usageStatus?.usage?.resetCreditsAvailable ?? 0) > 0 && <button type="button" disabled={usageStatus.resetPending} onClick={() => openResetCredit(accountOption)}>{usageStatus.resetPending ? t("context.using") : t("context.use")}</button>}
          </div>}
        </div>)}
        <button className="context-manage-accounts" type="button" role="menuitem" onClick={openSettings}>{t("context.settings")}</button>
      </div>}
    </div>
    <div className="context-project"><button className="context-project-button context-project-title" type="button" onClick={onChatOpen} disabled={!session} aria-label={t("context.openLastChat")}><strong>{lastChatProjectLabel(session, project, t)}</strong></button>
      <NotificationCenter notifications={notifications} accounts={accounts} currentStatus={chatProgressLabel(session, t)} statusDisabled={!session} sessions={sessions} currentSession={currentSession} threads={threads} notificationError={notificationError} refreshErrors={notificationRefreshErrors} onPopupOpen={onPopupOpen} onStatusOpen={onChatOpen} onOpen={onNotificationOpen} onDismiss={onNotificationDismiss} onActiveSessionOpen={onActiveSessionOpen} onClear={onNotificationsClear} />
    </div>
    {manager.login && <div className="settings-overlay" role="presentation">
      <section className="account-login-dialog" role="dialog" aria-modal="true" aria-labelledby="account-login-title">
        <header><h2 id="account-login-title">{t("context.connect")}</h2><button className="settings-close" type="button" aria-label={t("context.close")} onClick={closeLogin}><CloseIcon /></button></header>
        {!manager.login.userCode && <button className="account-login-check" type="button" disabled={manager.pending} onClick={manager.requestLoginCode}>{manager.pending ? t("context.requestingCode") : t("context.getLoginCode")}</button>}
        {manager.login.userCode && <>
          <p>{t("context.deviceCode")}</p>
          <div className="account-login-code-row">
            <code className="account-login-code">{manager.login.userCode}</code>
            <div className="account-login-copy-action"><MessageCopyButton text={manager.login.userCode} active onDismiss={noop} standalone /></div>
          </div>
          <a className="account-login-open" href={manager.login.verificationUrl} target="_blank" rel="noreferrer">{t("context.openChatGpt")}</a>
          <button className="account-login-check" type="button" disabled={manager.pending} onClick={manager.checkConnection}>{manager.pending ? t("context.checking") : t("context.checkConnection")}</button>
        </>}
      </section>
    </div>}
    <ResetCreditDialog open={Boolean(resetAccountName)} accountName={resetAccountName} onClose={() => setResetAccountName("")} onUse={onUseResetCredit} />
  </header>;
}
