"use client";

import { useState } from "react";
import BoldIcon from "@/components/ui/BoldIcon";
import { useAppLanguage } from "@/contexts/LanguageProvider";
import { LANGUAGE_LABELS, type AppLanguage } from "@/lib/i18n/constants";

const languages: Array<{ code: AppLanguage; label: string; flag: string }> = [
  { code: "fa", label: LANGUAGE_LABELS.fa.native, flag: "🇮🇷" },
  { code: "en", label: LANGUAGE_LABELS.en.native, flag: "🇺🇸" },
];

export default function LanguageSwitcher() {
  const [open, setOpen] = useState(false);
  const { language, setLanguage } = useAppLanguage();

  const toggleDropdown = () => setOpen(!open);

  const changeLanguage = async (langCode: AppLanguage) => {
    await setLanguage(langCode);
    setOpen(false);
  };

  const current =
    languages.find((lang) => lang.code === language) || languages[0];

  return (
    <div className="relative inline-block text-left">
      <button
        onClick={toggleDropdown}
        className="inline-flex max-Wide-mobile-s:text-xs rtl:flex-row-reverse items-center px-4 py-2 dark:border-white dark:text-white font-medium border rounded-xl shadow transition-all"
      >
        <BoldIcon name="global" size={18} tinted className="mr-2 text-current" />
        {current.flag} {current.label}
      </button>

      {open && (
        <div className="absolute z-10 mt-2  rounded-md bg-white dark:bg-neutral-800 shadow-lg ring-1 ring-black ring-opacity-5">
          <div className="py-1">
            {languages.map((lang) => (
              <button
                key={lang.code}
                onClick={() => void changeLanguage(lang.code)}
                className="w-full rtl:flex-row-reverse flex items-center px-4 py-2 text-sm text-gray-700 dark:text-white/60 dark:hover:bg-gray-600 hover:bg-gray-100"
              >
                <span className="mr-2 flex">{lang.flag}</span> {lang.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}