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

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"
			className="flex h-8 w-fit items-center gap-2 px-3 text-primary"
			loading={busy}
			onClick={() => handleLangChange(locale === "it" ? "en" : "it")}
			variant="outline"
		>
			{locale === "it" ? (
				<>
					<ItaFlag className="size-4" />
				</>
			) : (
				<>
					<EngFlag className="size-4" />
				</>
			)}
		</LoadingButton>
	);
};
