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

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

function LocaleOption({ locale, label, currentLocale, onClick }: LocaleOptionProps): React.ReactElement {
  const isActive = currentLocale === locale
  return (
    <button
      onClick={() => onClick(locale)}
      className={`px-4 py-2 rounded-lg font-medium transition-colors border ${
        isActive
          ? 'bg-neon-cyan/20 text-neon-cyan border-neon-cyan/50'
          : 'bg-cyber-darker text-cyber-accent hover:text-neon-cyan border-neon-cyan/30 hover:border-neon-cyan/50'
      }`}
    >
      {label}
    </button>
  )
}

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

  useEffect(() => {
    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)
      } finally {
        setLoading(false)
      }
    }
    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)
  }

  if (loading) {
    return (
      <div className="bg-cyber-darker border border-neon-cyan/30 rounded-lg p-6">
        <div>{t('settings.language.loading')}</div>
      </div>
    )
  }

  return (
    <div className="bg-cyber-darker border border-neon-cyan/30 rounded-lg p-6">
      <h2 className="text-2xl font-bold text-neon-cyan mb-4">{t('settings.language.title')}</h2>
      <p className="text-cyber-accent mb-4 text-sm">{t('settings.language.description')}</p>
      <div className="flex items-center gap-3">
        <LocaleOption locale="fr" label={t('settings.language.french')} currentLocale={currentLocale} onClick={onLocaleClick} />
        <LocaleOption locale="en" label={t('settings.language.english')} currentLocale={currentLocale} onClick={onLocaleClick} />
      </div>
    </div>
  )
}
