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(() => {
    void loadLocaleIntoState({ setCurrentLocale, setLoading })
  }, [])

  const handleLocaleChange = async (locale: Locale): Promise<void> => {
    await applyLocaleChange({ locale, setCurrentLocale })
  }

  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>
  )
}

async function loadLocaleIntoState(params: {
  setCurrentLocale: (locale: Locale) => void
  setLoading: (loading: boolean) => void
}): Promise<void> {
  try {
    await localeStorage.migrateFromLocalStorage()
    const savedLocale = await localeStorage.getLocale()
    if (savedLocale) {
      setLocale(savedLocale)
      params.setCurrentLocale(savedLocale)
    }
  } catch (e) {
    console.error('Error loading locale:', e)
  } finally {
    params.setLoading(false)
  }
}

async function applyLocaleChange(params: { locale: Locale; setCurrentLocale: (locale: Locale) => void }): Promise<void> {
  setLocale(params.locale)
  params.setCurrentLocale(params.locale)
  try {
    await localeStorage.saveLocale(params.locale)
  } catch (e) {
    console.error('Error saving locale:', e)
  }
  window.location.reload()
}
