import { ChevronDown, LanguagesIcon } from "lucide-react";
import { useState, useEffect } from "react";
import Cookies from "js-cookie";
import { useNavStore } from "../store";

const getPath = (lang: string, path: string) =>
  lang === "en" ? path : "/" + path;

export function LanguageDropdown({
  isMobile,
  path,
}: {
  isMobile: boolean;
  path: string;
}) {
  const [langOpen, setLangOpen] = useState(false);
  const { selectedLang, setLanguage } = useNavStore();

  const languages = [
    { code: "en", name: "English" },
    { code: "ar", name: "العربية" },
    { code: "de", name: "Deutsch" },
    { code: "fr", name: "Français" },
    { code: "id", name: "Indonesia" },
    { code: "ru", name: "Русский" },
    { code: "zh", name: "中文" },
    { code: "bn", name: "বাংলা" },
    { code: "es", name: "Español" },
    { code: "hi", name: "हिन्दी" },
    { code: "pt", name: "Português" },
  ];

  return (
    <div className="relative w-auto">
      <button
        onClick={() => setLangOpen(!langOpen)}
        className="flex cursor-pointer items-center gap-2 px-3 py-3 rounded-lg hover:bg-gray-50 transition-colors"
      >
        <LanguagesIcon className="w-4 h-4 text-gray-700" />
        <span className="text-xs font-medium text-gray-700">
          {selectedLang?.code.toUpperCase()}
        </span>
        <ChevronDown
          className={`w-4 h-4 text-gray-500 transition-transform ${
            langOpen ? "rotate-180" : ""
          }`}
        />
      </button>

      {langOpen && (
        <div
          className="fixed inset-0 z-10"
          onClick={() => setLangOpen(false)}
        />
      )}
      <div
        className={`${isMobile ? "sticky" : "absolute"} ${
          selectedLang?.code === "ar" && isMobile ? "right-0" : "-left-full"
        } w-48 bg-white rounded-lg shadow-lg border border-gray-100 z-20 overflow-y-auto transition-all duration-200 ease-out ${
          langOpen
            ? "opacity-100 scale-100"
            : "opacity-0 scale-95 pointer-events-none"
        }`}
      >
        {languages.map((lang) => (
          <a
            key={lang.code}
            href={`/${lang.code === "en" ? "" : lang.code}${
              path ? getPath(lang.code, path) : ""
            }`}
            onClick={() => {
              setLanguage(lang);
              Cookies.set("languageToken", lang.code === "en" ? "" : lang.code);
              setLangOpen(false);
            }}
            className={`w-full flex items-center gap-3 px-4 py-2 hover:bg-gray-50 transition-colors ${
              selectedLang?.code === lang.code ? "bg-gray-50" : ""
            }`}
          >
            <span className="text-sm font-medium text-gray-700">
              {lang.name}
            </span>
          </a>
        ))}
      </div>
    </div>
  );
}
