'use client'

import { useState, useEffect } from 'react'
import { SettingsNav, SettingsSection, SettingToggle, SettingSelect } from '@/components/settings'
import { useLanguage } from '@/lib/i18n'
import { updateAISettings, getAISettings } from '@/app/actions/ai-settings'
import { toast } from 'sonner'

export default function GeneralSettingsPage() {
  const { t, setLanguage: setContextLanguage } = useLanguage()
  const [language, setLanguage] = useState('auto')
  const [emailNotifications, setEmailNotifications] = useState(false)
  const [desktopNotifications, setDesktopNotifications] = useState(false)
  const [anonymousAnalytics, setAnonymousAnalytics] = useState(false)

  // Load settings on mount
  useEffect(() => {
    async function loadSettings() {
      try {
        const settings = await getAISettings()
        if (settings.preferredLanguage) setLanguage(settings.preferredLanguage)
        if (settings.emailNotifications !== undefined) setEmailNotifications(settings.emailNotifications)
        if (settings.desktopNotifications !== undefined) setDesktopNotifications(settings.desktopNotifications)
        if (settings.anonymousAnalytics !== undefined) setAnonymousAnalytics(settings.anonymousAnalytics)
      } catch (error) {
        console.error('Error loading settings:', error)
      }
    }
    loadSettings()
  }, [])

  const handleLanguageChange = async (value: string) => {
    setLanguage(value)

    // 1. Update database settings
    await updateAISettings({ preferredLanguage: value as any })

    // 2. Update local storage and application state
    if (value === 'auto') {
      localStorage.removeItem('user-language')
      toast.success("Language set to Auto")
    } else {
      localStorage.setItem('user-language', value)
      setContextLanguage(value as any)
      toast.success(t('profile.languageUpdateSuccess') || "Language updated")
    }

    // 3. Force reload to ensure all components update (server components, metadata, etc.)
    setTimeout(() => window.location.reload(), 500)
  }

  const handleEmailNotificationsChange = async (enabled: boolean) => {
    setEmailNotifications(enabled)
    await updateAISettings({ emailNotifications: enabled })
  }

  const handleDesktopNotificationsChange = async (enabled: boolean) => {
    setDesktopNotifications(enabled)
    await updateAISettings({ desktopNotifications: enabled })
  }

  const handleAnonymousAnalyticsChange = async (enabled: boolean) => {
    setAnonymousAnalytics(enabled)
    await updateAISettings({ anonymousAnalytics: enabled })
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold mb-2">{t('generalSettings.title')}</h1>
        <p className="text-gray-600 dark:text-gray-400">
          {t('generalSettings.description')}
        </p>
      </div>

      <SettingsSection
        title={t('settings.language')}
        icon={<span className="text-2xl">🌍</span>}
        description={t('profile.languagePreferencesDescription')}
      >
        <SettingSelect
          label={t('settings.language')}
          description={t('settings.selectLanguage')}
          value={language}
          options={[
            { value: 'auto', label: t('profile.autoDetect') },
            { value: 'en', label: 'English' },
            { value: 'fr', label: 'Français' },
            { value: 'es', label: 'Español' },
            { value: 'de', label: 'Deutsch' },
            { value: 'fa', label: 'فارسی' },
            { value: 'it', label: 'Italiano' },
            { value: 'pt', label: 'Português' },
            { value: 'ru', label: 'Русский' },
            { value: 'zh', label: '中文' },
            { value: 'ja', label: '日本語' },
            { value: 'ko', label: '한국어' },
            { value: 'ar', label: 'العربية' },
            { value: 'hi', label: 'हिन्दी' },
            { value: 'nl', label: 'Nederlands' },
            { value: 'pl', label: 'Polski' },
          ]}
          onChange={handleLanguageChange}
        />
      </SettingsSection>

      <SettingsSection
        title={t('settings.notifications')}
        icon={<span className="text-2xl">🔔</span>}
        description={t('settings.notifications')}
      >
        <SettingToggle
          label={t('settings.notifications')}
          description={t('settings.notifications')}
          checked={emailNotifications}
          onChange={handleEmailNotificationsChange}
        />
        <SettingToggle
          label={t('settings.notifications')}
          description={t('settings.notifications')}
          checked={desktopNotifications}
          onChange={handleDesktopNotificationsChange}
        />
      </SettingsSection>

      <SettingsSection
        title={t('settings.privacy')}
        icon={<span className="text-2xl">🔒</span>}
        description={t('settings.privacy')}
      >
        <SettingToggle
          label={t('settings.privacy')}
          description={t('settings.privacy')}
          checked={anonymousAnalytics}
          onChange={handleAnonymousAnalyticsChange}
        />
      </SettingsSection>
    </div>
  )
}
