import { useState, useEffect } from 'react'
import { Settings as SettingsIcon, Play, CheckCircle, Languages, Coins, Upload } from 'lucide-react'
import { api } from '../utils/api'
import { useLanguage } from '../i18n/LanguageContext'
import { CURRENCIES } from '../i18n/LanguageContext'

export default function Settings() {
  const { t, lang, setLang, currency, setCurrency } = useLanguage()
  const [restarting, setRestarting] = useState(false)
  const [success, setSuccess] = useState(false)
  const [maxSizeMB, setMaxSizeMB] = useState(50)
  const [sizeSaving, setSizeSaving] = useState(false)
  const [sizeSaved, setSizeSaved] = useState(false)

  useEffect(() => {
    api.get('/settings/app').then(s => setMaxSizeMB(s.uploadMaxSizeMB || 50)).catch(() => {})
  }, [])

  const handleSaveMaxSize = async () => {
    setSizeSaving(true)
    setSizeSaved(false)
    try {
      const res = await api.patch('/settings/app', { uploadMaxSizeMB: maxSizeMB })
      setMaxSizeMB(res.uploadMaxSizeMB)
      setSizeSaved(true)
      setTimeout(() => setSizeSaved(false), 2000)
    } catch (err) {
      alert(err.message || 'Failed to save')
    } finally {
      setSizeSaving(false)
    }
  }

  const handleRestartTutorial = async () => {
    setRestarting(true)
    setSuccess(false)
    try {
      await api.patch('/users/me/tutorial', { completed: false })
      setSuccess(true)
      setTimeout(() => {
        window.location.reload() // Reload to trigger tutorial
      }, 1500)
    } catch (err) {
      console.error('Failed to restart tutorial:', err)
      alert('Failed to restart tutorial')
    } finally {
      setRestarting(false)
    }
  }

  return (
    <div className="space-y-6 animate-fade-in max-w-3xl">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-text-primary flex items-center gap-3">
          <SettingsIcon className="w-7 h-7 text-brand-primary" />
          {t('settings.title')}
        </h1>
        <p className="text-sm text-text-tertiary mt-1">{t('settings.preferences')}</p>
      </div>

      {/* General Settings */}
      <div className="bg-white rounded-xl border border-border overflow-hidden">
        <div className="px-6 py-4 border-b border-border">
          <h2 className="text-lg font-semibold text-text-primary">{t('settings.general')}</h2>
        </div>
        <div className="p-6 space-y-4">
          {/* Language Selector */}
          <div>
            <label className="block text-sm font-medium text-text-primary mb-2 flex items-center gap-2">
              <Languages className="w-4 h-4" />
              {t('settings.language')}
            </label>
            <select
              value={lang}
              onChange={(e) => setLang(e.target.value)}
              className="w-full max-w-xs px-4 py-2.5 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary bg-white"
            >
              <option value="en">{t('settings.english')}</option>
              <option value="ar">{t('settings.arabic')}</option>
            </select>
          </div>

          {/* Currency Selector */}
          <div>
            <label className="block text-sm font-medium text-text-primary mb-2 flex items-center gap-2">
              <Coins className="w-4 h-4" />
              {t('settings.currency')}
            </label>
            <select
              value={currency}
              onChange={(e) => setCurrency(e.target.value)}
              className="w-full max-w-xs px-4 py-2.5 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary bg-white"
            >
              {CURRENCIES.map(c => (
                <option key={c.code} value={c.code}>
                  {c.symbol} — {lang === 'ar' ? c.labelAr : c.labelEn}
                </option>
              ))}
            </select>
            <p className="text-xs text-text-tertiary mt-1.5">{t('settings.currencyHint')}</p>
          </div>
        </div>
      </div>

      {/* Uploads Section */}
      <div className="bg-white rounded-xl border border-border overflow-hidden">
        <div className="px-6 py-4 border-b border-border">
          <h2 className="text-lg font-semibold text-text-primary flex items-center gap-2">
            <Upload className="w-5 h-5 text-brand-primary" />
            {t('settings.uploads')}
          </h2>
        </div>
        <div className="p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-text-primary mb-2">
              {t('settings.maxFileSize')}
            </label>
            <div className="flex items-center gap-3">
              <input
                type="number"
                min="1"
                max="500"
                value={maxSizeMB}
                onChange={(e) => setMaxSizeMB(Number(e.target.value))}
                className="w-24 px-3 py-2.5 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary bg-white"
              />
              <span className="text-sm text-text-secondary">{t('settings.mb')}</span>
              <button
                onClick={handleSaveMaxSize}
                disabled={sizeSaving}
                className="px-4 py-2.5 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 transition-colors"
              >
                {sizeSaved ? (
                  <span className="flex items-center gap-1.5"><CheckCircle className="w-4 h-4" />{t('settings.saved')}</span>
                ) : sizeSaving ? '...' : t('common.save')}
              </button>
            </div>
            <p className="text-xs text-text-tertiary mt-1.5">{t('settings.maxFileSizeHint')}</p>
          </div>
        </div>
      </div>

      {/* Tutorial Section */}
      <div className="bg-white rounded-xl border border-border overflow-hidden">
        <div className="px-6 py-4 border-b border-border">
          <h2 className="text-lg font-semibold text-text-primary">{t('settings.onboardingTutorial')}</h2>
        </div>
        <div className="p-6 space-y-4">
          <p className="text-sm text-text-secondary">
            {t('settings.tutorialDesc')}
          </p>
          <button
            onClick={handleRestartTutorial}
            disabled={restarting || success}
            className="flex items-center gap-2 px-4 py-2.5 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 disabled:cursor-not-allowed shadow-sm transition-colors"
          >
            {success ? (
              <>
                <CheckCircle className="w-4 h-4" />
                {t('settings.tutorialRestarted')}
              </>
            ) : (
              <>
                <Play className="w-4 h-4" />
                {restarting ? t('settings.restarting') : t('settings.restartTutorial')}
              </>
            )}
          </button>
          {success && (
            <p className="text-xs text-emerald-600 font-medium">
              {t('settings.reloadingPage')}
            </p>
          )}
        </div>
      </div>
    </div>
  )
}
