"use client";

import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import clsx from "clsx";
import { motion, AnimatePresence } from "framer-motion";

import triangle from "@/public/assets/icons/drop-icon.svg";
import { useLocale } from "next-intl";
import { useRouter, usePathname } from "@/i18n/navigation";
import { locales } from "@/i18n/config";

const langNames: Record<string, string> = {
  ru: "Русский",
  en: "English",
  tm: "Türkmen",
};

export const LangMenu = () => {
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const [active, setActive] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  const switchLocale = (newLocale: string) => {
    router.replace(pathname, { locale: newLocale });
    setActive(false);
  };

  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setActive(false);
      }
    };

    document.addEventListener("click", handleClick);

    return () => document.removeEventListener("click", handleClick);
  }, []);

  return (
    <div
      ref={menuRef}
      className="relative w-[90px] cursor-pointer  flex items-center gap-x-5"
      onClick={() => {
        setActive(!active);
      }}
    >
      <div className="flex items-center px-[12px]">
        <p>{langNames[locale]}</p>
        <Image
          src={triangle}
          alt="arrow"
          className={clsx("transition-rotate duration-300 img-auto", {
            "rotate-180": active,
          })}
        />
      </div>
      <AnimatePresence>
        {active && (
          <motion.div
            initial={{
              opacity: 0,
            }}
            animate={{
              opacity: 1,
            }}
            exit={{
              opacity: 0,
            }}
            transition={{
              duration: 0.2,
            }}
            className="absolute rounded-[4px] w-[112px] overflow-hidden custom-shadow z-10 flex flex-col top-[27px] bg-[#EEF1F0] transition-all duration-300"
          >
            {locales
              .filter((l) => l !== locale)
              .map((l, i) => (
                <div
                  key={i}
                  onClick={() => switchLocale(l)}
                  className="p-3 pr-[22px] py-4 text-extraSm transition-all hover:bg-ON_SECONDARY_CONTAINER/[8%]"
                >
                  {langNames[l]}
                </div>
              ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};
