"use client";

import { CustomDropdownMenu } from "../dropdown-menu";
import { DropdownMenuItem } from "../ui/dropdown-menu";
import { useParams } from "next/navigation";
import { Locale, useLocale, useTranslations } from "next-intl";
import { useTransition } from "react";
import { ChevronDownIcon } from "lucide-react";
import Image from "next/image";
import { usePathname, useRouter } from "@/i18n/navigation";
import { cn } from "@/utlis";

export const LangDropdown = () => {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const pathname = usePathname();
  const params = useParams();
  const locale = useLocale();
  const t = useTranslations();

  const onSelectChange = (lang: Locale) => {
    startTransition(() => {
      router.replace(
        // @ts-expect-error -- TypeScript will validate that only known params
        // are used in combination with a given pathname. Since the two will
        // always match for the current route, we can skip runtime checks.
        { pathname, params },
        { locale: lang }
      );
    });
  };

  return (
    <CustomDropdownMenu
      dropdownMenuTrigger={
        <>
          <span>{locale === "ar" ? "Ar" : "En"}</span>
          <ChevronDownIcon className="h-4 w-4" />
        </>
      }
      btnClassName="flex items-center justify-start gap-1"
      className="!rounded-xl border bg-bgClr-2 px-2 py-4 bg-white"
    >
      <DropdownMenuItem
        className="flex cursor-pointer items-center justify-start gap-3"
        onClick={() => onSelectChange("ar")}
      >
        <Image src={"/sa-flag.svg"} width={20} height={16} alt={"SA"} />
        <span className={cn("font-medium text-primary-text")}>العربية</span>
      </DropdownMenuItem>

      <DropdownMenuItem
        className="flex cursor-pointer items-center justify-start gap-3"
        onClick={() => onSelectChange("en")}
      >
        <Image src={"/uk-flag.svg"} width={20} height={16} alt={"UK"} />
        <span className={cn("!font-nunito font-medium text-primary-text")}>
          English
        </span>
      </DropdownMenuItem>
    </CustomDropdownMenu>
  );
};
