"use client";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { setUserLocale } from "@/services/locale";
import { useLocale } from "next-intl";
import { useTransition } from "react";
import FallbackImage from "./FallbackImage";

export default function LangSwitcher({ languages }) {
  /**
   * language switcher
   *
   * Created by : Ahmed Badran
   * Created at Date : 20-oct-2024
   * Edit By :kerolos nessim
   * Edit at Date : 21-oct-2024
   *
   */
  const locale = useLocale();
  const [isPending, startTransition] = useTransition();

  const toggleLanguage = (value) => {
    const newLocale = value; // Get the selected value
    startTransition(() => {
      setUserLocale(newLocale);
    });
  };

  return (
    <>
      <Select
        dir={locale == "en" ? "ltr" : "rtl"}
        disabled={isPending}
        value={locale}
        onValueChange={toggleLanguage}
      >
        <SelectTrigger className="p-0 truncate border-none text-xs bg-transparent hover:text-main focus:ring-0 focus:ring-transparent focus:ring-offset-0">
          <SelectValue />
        </SelectTrigger>
        <SelectContent className="z-[101] w-20">
          {languages?.map((item) => (
            <SelectItem key={item?.id} value={item?.code}>
              <div className="flex gap-2 items-center my-2">
                <FallbackImage
                  src={item?.flag}
                  width={20}
                  height={20}
                  alt={item?.title}
                  className=""
                />
                <p className="hover:text-main">{item?.title}</p>
              </div>
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </>
  );
}