import { useSetting } from "@/context/helpers/theme-setting/SettingProvider";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCodeBranch } from "@fortawesome/free-solid-svg-icons";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import { toast } from "react-toastify";
import { useTranslation } from "react-i18next";
import { setCookie, setLargeStorage } from "@/context/utils/cookies";

export default function Branches() {
  const { t } = useTranslation("header");
  const { storeBranches, selectedStoreBranch, setSelectedStoreBranch, locale } =
    useSetting();

  const handleBranchClick = (branch) => {
    if (
      selectedStoreBranch &&
      branch &&
      String(branch.id) === String(selectedStoreBranch.id)
    ) {
      return;
    }

    setSelectedStoreBranch?.(branch);
    setLargeStorage("selectedBranch", JSON.stringify(branch));
    setCookie("branchId", String(branch.id));

    // show success toast
    toast.success(
      t("topbar.selectedSuccessfully", {
        branchName:
          branch?.translations?.find((trans) => trans.locale === locale)
            ?.name || "",
      })
    );

    // Reload the page to apply the branch change
    if (typeof window !== "undefined") {
      window.location.reload();
    }
  };

  // If there are less than 2 branches, don't show the branches component
  if (storeBranches?.length < 2) return null;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          className="flex items-center gap-2 cursor-pointer"
        >
          <FontAwesomeIcon
            icon={faCodeBranch}
            aria-hidden="true"
            className="size-4"
          />
          {selectedStoreBranch?.translations?.find(
            (trans) => trans.locale === locale
          )?.name || ""}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        {storeBranches?.map((branch) => (
          <DropdownMenuItem
            key={branch.id}
            onClick={() => handleBranchClick(branch)}
            aria-label={`Select branch: ${branch?.translations?.find((trans) => trans.locale === locale)?.name}`}
            className={cn(
              "cursor-pointer",
              branch.id === selectedStoreBranch?.id &&
                "bg-gray-100 dark:bg-gray-700"
            )}
          >
            {branch.translations?.find((trans) => trans.locale === locale)
              ?.name || ""}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
