"use client";

import Link from "next/link";
import { UserPlus } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";

import { accountLabel } from "@/features/auth/accountLabel";
import AccountRow from "./AccountRow";
import { useAuthStore } from "@/store/authStore";

/**
 * BE-129 — the sessions this device holds, and a way into a new one.
 *
 * Switching is local. Each account's token stays valid when another signs in —
 * the backend scopes them independently, which is the whole reason this can
 * exist without an endpoint — so all this decides is which token the request
 * interceptor sends. Nothing is fetched to build the list; there is no "my
 * accounts" API, and these are simply the sessions this browser happens to
 * hold.
 *
 * Reaching the sign-in form while already signed in takes a deliberate
 * signal: `RedirectIfLoggedIn` bounces a signed-in visitor off `/login`, so
 * "add another account" sets `addingAccount` first. See the note on that field
 * in `authStore` for why it is a store flag and not `?add=1`.
 */
export default function AccountSwitcher({ close }: { close: () => void }) {
  const { t } = useTranslation();
  const user = useAuthStore((state) => state.user);
  const accounts = useAuthStore((state) => state.accounts);
  const switchAccount = useAuthStore((state) => state.switchAccount);
  const setAddingAccount = useAuthStore((state) => state.setAddingAccount);

  const onSwitch = (id: number, name: string) => {
    switchAccount(id);
    toast.success(t("COMMON.TOAST.ACCOUNT_SWITCHED", { name }));
    close();
    // Load home as a fresh document so no previous account's query cache survives.
    window.location.assign("/");
  };

  if (!user) return null;

  return (
    <>
      {accounts.length > 0 && (
        <li className="mx-2 px-4 pb-1 pt-3 text-xs font-bold uppercase text-secondary-102">
          {t("COMMON.SWITCH_ACCOUNTS")}
        </li>
      )}
      {accounts.map((account) => (
        <AccountRow
          key={account.id}
          account={account}
          profilePic={account.profile_pic}
          onSelect={() => onSwitch(account.id, accountLabel(account))}
        />
      ))}

      <li className="mx-2 rounded-xl hover:bg-[#F5F5F5]">
        <Link
          href="/login"
          onClick={() => {
            setAddingAccount(true);
            close();
          }}
          className="flex h-12 items-center gap-3 px-4 py-2 text-base font-bold text-secondary-101"
        >
          <UserPlus className="h-5 w-5 shrink-0 text-primary-5" aria-hidden="true" />
          {t("COMMON.ADD_ANOTHER_ACCOUNT")}
        </Link>
      </li>

      <li className="mx-4 my-2 border-t border-black/10" aria-hidden="true" />
    </>
  );
}
