"use client";

import React from "react";
import { useRouter } from "nextjs-toploader/app";
import { usePathname } from "next/navigation";
import Cookies from "js-cookie";
import { useLocale, useTranslations } from "next-intl";
import { UseMutate } from "@/hooks/UseMutate";
import UseSession from "@/hooks/UseSession";

const LangSwitcher: React.FC = () => {
  const locale = useLocale();
  const session = UseSession();

  const router = useRouter();
  const pathname = usePathname();
  const t = useTranslations();
  const { mutate } = UseMutate({
    endpoint: "client/profile/settings",
    onSuccess() {},
    method: "PUT",
  });
  const setLanguage = async (locale: string) => {
    const lang = locale === "ar" ? "en" : "ar";
    if (session) await mutate({ locale: lang });

    Cookies.set("NEXT_LOCALE", lang);
    const url = new URL(window.location.href);
    const searchParams = url.search;
    let newPathname = pathname;
    if (newPathname.startsWith("/en")) {
      newPathname = `/${lang}/${newPathname.slice(3)}`;
    } else {
      newPathname = `/${lang}${newPathname}`;
    }
    router.push(`${newPathname}${searchParams}`);
  };

  return (
    <button
      className="px-5 py-2.5 text-[13px] font-medium border border-gray-200/30 rounded-lg hover:bg-primary hover:text-white hover:border-primary transition-all duration-200"
      onClick={() => setLanguage(locale)}
    >
      <span className=" inline-flex leading-[1] mx-2">
        {t(`locale.${locale == "ar" ? "en" : "ar"}`)}
      </span>
    </button>
  );
};

export default LangSwitcher;
