import { useState } from "react";
import { useRouter } from "next/router";
import { setCookie } from "cookies-next/client";
import { EngFlag, ItaFlag } from "~/components/svgs";
import LoadingButton from "~/components/custom_ui/loading-button";
import { add } from "date-fns";

export const LangToggle = () => {
  const router = useRouter();
  const locale = router.locale || "it";
  const [busy, setBusy] = useState(false);

  const handleLangChange = async (lang: string) => {
    if (lang === locale) return;
    setBusy(true);
    setCookie("NEXT_LOCALE", lang, {
      expires: add(new Date(), {
        days: 30,
      }),
    });
    await router.push(router.pathname, router.asPath, { locale: lang });
    setBusy(false);
  };

  return (
    <LoadingButton
      aria-label="Change Language"
      loading={busy}
      variant="outline"
      className="text-primary flex w-fit items-center gap-2"
      onClick={() => handleLangChange(locale === "it" ? "en" : "it")}
    >
      {locale === "it" ? (
        <>
          <ItaFlag className="size-5" />
        </>
      ) : (
        <>
          <EngFlag className="size-5" />
        </>
      )}
    </LoadingButton>
  );
};
