import "./NavLanguage.scss";
import Image from "next/image";
import { useEffect, useRef, useState, useTransition } from "react";
import chevron from "./icons/chevron-down.svg";
import check from "./icons/check.svg";
import { useParams, useRouter } from "next/navigation";
import { LANGUAGES } from "./variables";
import { usePathname } from "@/shared/config/navigation";

const NavLanguage = () => {
  const [openMenu, setOpenMenu] = useState<boolean>(false);
  const menuRef: React.RefObject<HTMLDivElement> = useRef(null);

  const router = useRouter();
  const pathname = usePathname();
  const { locale } = useParams();

  const [_, startTransition] = useTransition();
  const [language, setLanguage] = useState<string>(locale as string);

  useEffect(() => {
    const params = window.location.search || "";
    startTransition(() => {
      router.replace(`/${language}${pathname}${params}`, {
        scroll: false,
      });
    });
  }, [language]);

  useEffect(() => {
    function handleClickOutside(event: any) {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setOpenMenu(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [menuRef]);

  return (
    <div ref={menuRef} className="nav-language">
      {/* <button
        onClick={() => setOpenMenu((prev) => !prev)}
        className="nav-language__btn"
      > */}
      {/* <Image src={globus} alt="globus icon" /> */}
      <button
        onClick={() => setOpenMenu((prev) => !prev)}
        className="nav-language__btn"
      >
        {language === "ru" && <span>Рус</span>}
        {language === "kg" && <span>Кырг</span>}
        {language === "en" && <span>Eng</span>}
        <Image src={chevron} alt="chevron icon" />
      </button>
      {openMenu && (
        <div className="nav-language__select">
          {LANGUAGES.map((lang) => (
            <button
              className={`nav-language__option${
                language === lang.index ? "_active" : ""
              }`}
              onClick={() => {
                setLanguage(lang.index);
                setOpenMenu(false);
              }}
              key={lang.id}
            >
              {lang.language}
              {lang.index === language ? (
                <Image src={check} alt="check icon" />
              ) : null}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

export default NavLanguage;
