import { GetServerSidePropsContext } from "next";
import { Button } from "@mantine/core";
import Link from "next/link";
import LangIcon from "../../icons/LangIcon";
import { useTranslation } from "react-i18next";
import { parseCookies, setCookie } from "nookies";
import { useEffect } from "react";

export async function getServerSideProps(context: GetServerSidePropsContext) {
  const cookies = parseCookies(context);

  const savedLanguage = cookies.i18next || "ar";

  return {
    props: {
      initialLanguage: savedLanguage,
    },
  };
}

const NavLanguageAndContact = ({
  initialLanguage,
}: {
  initialLanguage?: string;
}) => {
  const { i18n, t } = useTranslation();

  const handleLang = async () => {
    const currentLanguage = i18n.language;
    const newLanguage = currentLanguage === "en" ? "ar" : "en";
    await i18n.changeLanguage(newLanguage);
    document.documentElement.lang = newLanguage;
    setCookie(null, "i18next", newLanguage, {
      path: "/",
    });
    localStorage.setItem("language", newLanguage);
    window.location.reload();
  };
  

  useEffect(() => {
    if (initialLanguage !== i18n.language) {
      i18n.changeLanguage(initialLanguage);
      //@ts-ignore
      document.documentElement.lang = initialLanguage;
    }
  }, [initialLanguage, i18n]);

  return (
    <div className="flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-[10px] items-center mt-5 md:mt-0">
      <Button
        component={Link}
        href="/#contact-us"
        variant="outline"
        className="hover:bg-gray-200 hover:text-black border-white text-white rounded-[25px] duration-200 font-cairo text-base font-normal"
      >
        {t("navbar.contact")}
      </Button>
      <Button
        variant="outline"
        className="flex items-center space-x-2 text-gray-800 border-none hover:bg-inherit"
        onClick={handleLang}
      >
        <LangIcon />
        <span className="ps-[10px] text-white">
          {i18n.language === "en" ? "Ar" : "En"}
        </span>
      </Button>
    </div>
  );
};

export default NavLanguageAndContact;
