"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Building2, Check, ChevronsUpDown, Loader2 } from "lucide-react";
import { useAuthStore } from "@/lib/stores/auth.store";
import { switchBranch } from "@/lib/api/branch-roles";
import { isCafeOwner } from "@/lib/auth-permissions";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

/**
 * Active-branch session switcher. Calls /auth/switch-branch which re-issues a
 * token scoped to the chosen branch (and the role held there). Owners may also
 * pick "all branches" (café-wide). Hidden when the employee has a single branch
 * and is not the owner.
 */
export function BranchSwitcher() {
  const t = useTranslations("branchSwitcher");
  const user = useAuthStore((s) => s.user);
  const setAuth = useAuthStore((s) => s.setAuth);
  const [pending, setPending] = useState(false);

  const branches = user?.branches ?? [];
  const owner = isCafeOwner(user?.role);

  // Owners always get the switcher (to scope into a branch); other staff only
  // when they actually belong to more than one branch.
  if (!user || (!owner && branches.length <= 1)) return null;

  const activeLabel = user.isCafeWide
    ? t("allBranches")
    : user.branchName ?? t("selectBranch");

  async function choose(branchId: string | null) {
    if (pending) return;
    // No-op when re-selecting the current scope.
    if (branchId === (user!.branchId ?? null)) return;
    setPending(true);
    try {
      const next = await switchBranch(branchId);
      setAuth(next);
      // Active branch changes nearly every scoped query + nav — full reload is safest.
      if (typeof window !== "undefined") window.location.reload();
    } finally {
      setPending(false);
    }
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="h-8 max-w-[160px] gap-1.5 px-2.5 text-xs cursor-pointer"
          disabled={pending}
          title={t("title")}
        >
          {pending ? (
            <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-hidden />
          ) : (
            <Building2 className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
          )}
          <span className="truncate">{activeLabel}</span>
          <ChevronsUpDown className="h-3 w-3 shrink-0 text-muted-foreground/60" aria-hidden />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="min-w-[200px]">
        <p className="px-2 py-1.5 text-xs font-medium text-muted-foreground">{t("title")}</p>
        <div className="my-1 h-px bg-border" />
        {owner && (
          <DropdownMenuItem
            onClick={() => choose(null)}
            className="cursor-pointer gap-2"
          >
            <Check
              className={`h-3.5 w-3.5 shrink-0 ${user.isCafeWide ? "opacity-100" : "opacity-0"}`}
              aria-hidden
            />
            {t("allBranches")}
          </DropdownMenuItem>
        )}
        {branches.map((b) => (
          <DropdownMenuItem
            key={b.branchId}
            onClick={() => choose(b.branchId)}
            className="cursor-pointer gap-2"
          >
            <Check
              className={`h-3.5 w-3.5 shrink-0 ${
                !user.isCafeWide && user.branchId === b.branchId ? "opacity-100" : "opacity-0"
              }`}
              aria-hidden
            />
            <span className="truncate">{b.branchName}</span>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
