import { LINKS } from "@/shared/variables/links";
import "./NavMenu.scss";
import NavAuth from "../NavAuth/NavAuth";
import { Link, usePathname } from "@/shared/config/navigation";
import { useEffect, useState, useTransition } from "react";
import { useParams, useRouter } from "next/navigation";
import chevron_down from "./icons/chevron_down.svg";
import Image from "next/image";

interface INavMenuProps {
  setOpenMenu: (boolean: boolean) => void;
}

const NavMenu: React.FC<INavMenuProps> = ({
  setOpenMenu,
}: INavMenuProps) => {
  const [openMenuLanguage, setOpenMenuLanguage] =
    useState<boolean>(false);
  const router = useRouter();
  const pathname = usePathname();
  const { locale } = useParams();

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

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

  const langKeys: Record<string, string> = {
    ru: "Русский",
    kg: "Кыргызча",
    en: "English",
  };

  const languages = [
    { id: 1, language: "Русский", pathname: "ru" as const },
    { id: 2, language: "Кыргызча", pathname: "kg" as const },
    { id: 3, language: "English", pathname: "en" as const },
  ];

  return (
    <nav className="nav-menu">
      {LINKS().map((link) => (
        <Link
          onClick={() => setOpenMenu(false)}
          className={`nav-menu__link${
            pathname === link.pathname ? "_active" : ""
          }`}
          href={`${pathname.slice(1, 3)}/${link.pathname}`}
          key={link.id}
        >
          {link.pagename}
        </Link>
      ))}

      <NavAuth setOpenMenu={setOpenMenu} responsible />

      <div className="nav-menu__language">
        <button onClick={() => setOpenMenuLanguage((prev) => !prev)}>
          {langKeys[currentLanguage as string]}
          <Image src={chevron_down} alt="Chevron Down" />
        </button>

        {openMenuLanguage && (
          <div className="nav-menu__language-wrapper">
            {languages.map((lang) => (
              <Link
                onClick={() => setCurrentLanguage(lang.pathname)}
                className={`${
                  currentLanguage === lang.pathname
                    ? "nav-menu__language_active"
                    : ""
                }`}
                href="#"
                locale={lang.pathname}
                key={lang.id}
              >
                {lang.language}
              </Link>
            ))}
          </div>
        )}
      </div>
    </nav>
  );
};

export default NavMenu;
