"use client";
import {useState, useRef} from "react";
import {useRouter} from "next/router";
import {useTranslation} from "next-i18next";

export default function LanguageSwitcher() {
  const router = useRouter();
  const {i18n} = useTranslation();
  const [lang, setLang] = useState(false);
  const langDropdownRef = useRef(null);

  const changeLanguage = (lng) => {
    setLang(false);
    router.push(router.pathname, router.asPath, {locale: lng});
  };

  return (
    <div className="relative flex flex-row items-center justify-end">
      <button onClick={() => setLang(!lang)} className="flex flex-row items-center gap-1 rounded-lg bg-slate-100 px-3 py-2 text-sm font-medium">
        <span>{i18n.language === "id" ? "Bahasa Indonesia" : "English"}</span>
        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24" className={`size-4 shrink-0 transition-transform ${lang ? "rotate-180" : ""}`}>
          <path d="M18.71 8.21a1 1 0 0 0-1.42 0l-4.58 4.58a1.001 1.001 0 0 1-1.42 0L6.71 8.21a1 1 0 1 0-1.42 1.41l4.59 4.59a3 3 0 0 0 4.24 0l4.59-4.59a1 1 0 0 0 0-1.41Z" />
        </svg>
      </button>
      {lang && (
        <div ref={langDropdownRef} className="absolute left-0 top-12 z-40 w-44 rounded-lg border border-slate-300 bg-white p-3 shadow-lg">
          <button onClick={() => changeLanguage("en")} className={`block w-full rounded-md px-4 py-2 text-left text-sm ${i18n.language === "en" ? "bg-vgreen text-white" : "hover:bg-slate-100"}`}>
            English
          </button>
          <button onClick={() => changeLanguage("id")} className={`mt-2 block w-full rounded-md px-4 py-2 text-left text-sm ${i18n.language === "id" ? "bg-vgreen text-white" : "hover:bg-slate-100"}`}>
            Bahasa Indonesia
          </button>
        </div>
      )}
    </div>
  );
}
