import { useState, useEffect } from 'react'
import { Button } from './ui'
import { setLocale, getLocale, type Locale } from '@/lib/i18n'
import { localeStorage } from '@/lib/localeStorage'

interface LocaleButtonProps {
  locale: Locale
  label: string
  currentLocale: Locale
  onClick: (locale: Locale) => void
}

function LocaleButton({ locale, label, currentLocale, onClick }: LocaleButtonProps): React.ReactElement {
  const isActive = currentLocale === locale
  return (
    <Button
      type="button"
      variant={isActive ? 'primary' : 'ghost'}
      size="small"
      onClick={() => onClick(locale)}
      className="px-2 py-1 text-xs"
    >
      {label}
    </Button>
  )
}

export function LanguageSelector(): React.ReactElement {
  const [currentLocale, setCurrentLocale] = useState<Locale>(getLocale())

  useEffect(() => {
    // Load saved locale from IndexedDB
    const loadLocale = async (): Promise<void> => {
      try {
        // Migrate from localStorage if needed
        await localeStorage.migrateFromLocalStorage()

        // Load from IndexedDB
        const savedLocale = await localeStorage.getLocale()
        if (savedLocale) {
          setLocale(savedLocale)
          setCurrentLocale(savedLocale)
        }
      } catch (e) {
        console.error('Error loading locale:', e)
      }
    }
    void loadLocale()
  }, [])

  const handleLocaleChange = async (locale: Locale): Promise<void> => {
    setLocale(locale)
    setCurrentLocale(locale)
    try {
      await localeStorage.saveLocale(locale)
    } catch (e) {
      console.error('Error saving locale:', e)
    }
    // Force page reload to update all translations
    window.location.reload()
  }

  const onLocaleClick = (locale: Locale): void => {
    void handleLocaleChange(locale)
  }

  return (
    <div className="flex items-center gap-2">
      <LocaleButton locale="fr" label="FR" currentLocale={currentLocale} onClick={onLocaleClick} />
      <LocaleButton locale="en" label="EN" currentLocale={currentLocale} onClick={onLocaleClick} />
    </div>
  )
}
