import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { getLanguage, changeLanguage } from '@/lib/i18n';
import { useTranslation } from 'react-i18next';
import { useEffect, useState } from 'react';

export function LanguageSwitcher() {
  const { i18n } = useTranslation();
  const [currentLang, setCurrentLang] = useState<'en' | 'ja'>(() => {
    return (getLanguage() as 'en' | 'ja') || 'en';
  });

  useEffect(() => {
    const handleLanguageChange = (lng: string) => {
      setCurrentLang(lng as 'en' | 'ja');
    };

    i18n.on('languageChanged', handleLanguageChange);
    return () => {
      i18n.off('languageChanged', handleLanguageChange);
    };
  }, [i18n]);

  const handleLanguageChange = (value: string) => {
    changeLanguage(value as 'en' | 'ja');
  };

  return (
    <Select
      value={currentLang}
      onValueChange={handleLanguageChange}>
      <SelectTrigger className='min-w-[120px]'>
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value='en'>English</SelectItem>
        <SelectItem value='ja'>日本語</SelectItem>
      </SelectContent>
    </Select>
  );
}
