import { useState, useEffect } from 'react'
import {
  Save,
  RefreshCw,
  CheckCircle,
  AlertCircle,
  Sparkles,
  Shield,
  RotateCcw,
  Coins,
  Globe,
  ShieldCheck,
} from 'lucide-react'
import { Header } from '../components/layout/Header'
import { Card, CardContent, Button, HelpTooltip } from '../components/common'
import { endpoints, getErrorMessage } from '../api/client'
import { t, setLocale, getCurrentLocale } from '../lib/i18n'
import { useOnboarding } from '../hooks/useOnboarding'
import { PingDot } from '../components/onboarding/PingDot'

interface SettingsData {
  sample_count: number
  title_cache_limit: number
  language_detection: string
  default_language: string
  default_posts_count: number
  auto_publish: boolean
  debug_mode: boolean
  admin_language: string
  data_language: string
  enable_smart_linking: boolean
  low_credits_threshold: number
  copyscape_enabled: boolean
  copyscape_threshold: number
  copyscape_auto_rewrite: boolean
}

const defaultSettings: SettingsData = {
  sample_count: 10,
  title_cache_limit: 200,
  language_detection: 'auto',
  default_language: 'he',
  default_posts_count: 10,
  auto_publish: false,
  debug_mode: false,
  admin_language: getCurrentLocale(),
  data_language: window.bmaiSettings?.dataLanguage || 'he',
  enable_smart_linking: true,
  low_credits_threshold: 100,
  copyscape_enabled: true,
  copyscape_threshold: 5,
  copyscape_auto_rewrite: true,
}

export default function SettingsPage() {
  const [settings, setSettings] = useState<SettingsData>(defaultSettings)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [resetting, setResetting] = useState(false)
  const [loadSuccess, setLoadSuccess] = useState(false)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [saveMessage, setSaveMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)
  const [hasChanges, setHasChanges] = useState(false)
  const [savedSettings, setSavedSettings] = useState<SettingsData>(defaultSettings)
  const { state: onboardingState, markSeen } = useOnboarding()

  useEffect(() => {
    if (!onboardingState.settingsSeen) {
      void markSeen('settingsSeen')
    }
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await endpoints.getSettings()
        if (response.data) {
          const merged = { ...defaultSettings, ...(response.data as Partial<SettingsData>) }
          setSettings(merged)
          setSavedSettings(merged)
        }
        setLoadSuccess(true)
        setLoadError(null)
      } catch (err) {
        setLoadSuccess(false)
        setLoadError(getErrorMessage(err, t('Failed to load settings. Save is disabled to prevent data loss.')))
      }
      setLoading(false)
    }
    fetchSettings()
  }, [])

  const update = (key: keyof SettingsData, value: unknown) => {
    setSettings(prev => {
      const next = { ...prev, [key]: value }
      setHasChanges(JSON.stringify(next) !== JSON.stringify(savedSettings))
      return next
    })
  }

  const handleSave = async () => {
    if (saving || !loadSuccess) return
    setSaving(true)
    setSaveMessage(null)
    const languageChanged = settings.admin_language !== getCurrentLocale()
    const dataLanguageChanged = settings.data_language !== (window.bmaiSettings?.dataLanguage || 'he')
    try {
      await endpoints.updateSettings(settings)
      setSavedSettings(settings)
      setHasChanges(false)
      if (window.bmaiSettings) {
        window.bmaiSettings.dataLanguage = settings.data_language
      }
      if (languageChanged || dataLanguageChanged) {
        setLocale(settings.admin_language)
        window.location.reload()
        return
      }
      setSaveMessage({ type: 'success', text: t('Settings saved successfully') })
      setTimeout(() => setSaveMessage(null), 4000)
    } catch {
      setSaveMessage({ type: 'error', text: t('Error saving settings') })
    } finally {
      setSaving(false)
    }
  }

  const handleReset = async () => {
    if (resetting || !loadSuccess) return
    if (!confirm(t('Reset all settings to defaults?'))) return
    setResetting(true)
    try {
      await endpoints.resetSettings()
      setSettings(defaultSettings)
      setSavedSettings(defaultSettings)
      setHasChanges(false)
      setSaveMessage({ type: 'success', text: t('Settings reset successfully') })
      setTimeout(() => setSaveMessage(null), 4000)
    } catch {
      setSaveMessage({ type: 'error', text: t('Error resetting settings') })
    } finally {
      setResetting(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center p-12">
        <RefreshCw className="w-6 h-6 animate-spin text-bc-primary" />
        <span className="ms-3 text-bc-gray-600">{t('Loading settings...')}</span>
      </div>
    )
  }

  return (
    <div className="min-h-screen">
      <Header
        title={t('Settings')}
        subtitle={t('Plugin settings and preferences')}
        helpContent={[
          t('Configure global plugin settings.'),
          t('Default working language: Sets the default language for new reporters and content.'),
          t('Auto-publish: Automatically publish generated content without manual review.'),
          t('Smart linking: Enable AI to insert relevant internal links into generated articles.'),
          t('Sample count: Number of existing posts the AI analyzes for style matching.'),
          t('Copyscape: Enable plagiarism checking before publishing (costs ~2 BoostCoins per article).'),
        ]}
      />

      <div className="p-6">
        <div className="space-y-6">

          {loadError && (
            <div className="p-4 rounded-bc bg-red-50 border border-red-200">
              <p className="text-sm text-red-600 font-medium">
                {t('Failed to load settings. Save is disabled to prevent data loss.')}
              </p>
              <button
                onClick={() => window.location.reload()}
                className="mt-2 text-sm text-red-700 underline"
              >
                {t('Reload page')}
              </button>
            </div>
          )}

          {/* Content Generation */}
          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-5">
                <div className="w-9 h-9 rounded-bc bg-bc-primary-light flex items-center justify-center">
                  <Sparkles className="w-5 h-5 text-bc-primary" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-bc-gray-800">{t('Content Creation')}</h2>
                  <p className="text-xs text-bc-gray-500">{t('Default settings for AI content creation')}</p>
                </div>
              </div>
              <div className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-bc-gray-700 mb-1 flex items-center gap-1">
                      {t('Number of samples to analyze')}
                      <HelpTooltip text={t('How many existing posts are analyzed before creating new content. More samples = more accurate style, but more BoostCoins consumed.')} />
                    </label>
                    <input
                      type="number"
                      min={1}
                      max={20}
                      value={settings.sample_count}
                      onChange={e => update('sample_count', parseInt(e.target.value) || 5)}
                      className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                    />
                    <p className="text-xs text-bc-gray-400 mt-1">{t('How many existing posts will be analyzed before creation')}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-bc-gray-700 mb-1">{t('Default post count')}</label>
                    <select
                      value={settings.default_posts_count}
                      onChange={e => update('default_posts_count', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                    >
                      <option value={1}>{t('1 post')}</option>
                      <option value={3}>{t('3 posts')}</option>
                      <option value={5}>{t('5 posts')}</option>
                      <option value={10}>{t('10 posts')}</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-bc-gray-700 mb-1">{t('Content language')}</label>
                  <select
                    value={settings.language_detection}
                    onChange={e => update('language_detection', e.target.value)}
                    className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                  >
                    <option value="auto">{t('Auto detect (Polylang / WPML)')}</option>
                    <option value="he">{t('Hebrew')}</option>
                    <option value="en">English</option>
                    <option value="ar">العربية</option>
                    <option value="ru">Русский</option>
                    <option value="fr">Français</option>
                    <option value="es">Español</option>
                    <option value="de">Deutsch</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-bc-gray-700 mb-1 flex items-center gap-1.5">
                    <Coins className="w-4 h-4 text-bc-gray-400" />
                    {t('Title cache limit for duplicate checking')}
                    <HelpTooltip text={t('Number of recent titles stored to prevent duplicates. Higher value prevents duplicates better but costs more BoostCoins per generation.')} />
                  </label>
                  <input
                    type="number"
                    min={10}
                    max={1000}
                    value={settings.title_cache_limit}
                    onChange={e => update('title_cache_limit', parseInt(e.target.value) || 200)}
                    className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                  />
                  <p className="text-xs text-bc-gray-400 mt-1">
                    {t('Higher value prevents duplicates better but uses more BoostCoins')}
                  </p>
                </div>

                {/* Note: 'Auto publish' global setting removed in 2.1.15.
                    Publishing behavior is controlled per-plan via the
                    publishing_schedule field (immediate / draft / drip-daily / drip-weekly)
                    set when creating/editing a content plan. */}

                <label
                  className="flex items-center gap-3 p-3 rounded-bc bg-bc-gray-50 cursor-pointer hover:bg-bc-gray-100 transition-colors"
                  onMouseEnter={() => {
                    if (!onboardingState.smartLinkingSeen) void markSeen('smartLinkingSeen')
                  }}
                >
                  <input
                    type="checkbox"
                    checked={settings.enable_smart_linking}
                    onChange={e => update('enable_smart_linking', e.target.checked)}
                    className="rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary"
                  />
                  <div>
                    <span className="text-sm text-bc-gray-700 font-medium flex items-center gap-1">
                      {t('Enable smart linking')}
                      <PingDot visible={!onboardingState.smartLinkingSeen && !onboardingState.setupComplete} size="sm" />
                      <HelpTooltip text={t('When enabled, AI will naturally weave internal and external links from your Links library into generated content. Manage your link library in the Links page.')} />
                    </span>
                    <p className="text-xs text-bc-gray-400">{t('Include links from your library in AI-generated content')}</p>
                  </div>
                </label>

                <div>
                  <label className="block text-sm font-medium text-bc-gray-700 mb-1 flex items-center gap-1">
                    <Coins className="w-4 h-4 text-bc-gray-400" />
                    {t('Low credits alert threshold')}
                    <HelpTooltip text={t('Show an alert banner when your BoostCoins balance drops below this number. Set to 0 to disable the alert.')} />
                  </label>
                  <input
                    type="number"
                    min={0}
                    max={10000}
                    value={settings.low_credits_threshold}
                    onChange={e => update('low_credits_threshold', parseInt(e.target.value) || 0)}
                    className="w-full max-w-xs px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                  />
                  <p className="text-xs text-bc-gray-400 mt-1">
                    {t('Show a warning banner when BoostCoins balance drops below this number')}
                  </p>
                </div>

                {/* Rich HTML templates toggle — disabled until backend template parsing is complete
                <label className="flex items-center gap-3 p-3 rounded-bc bg-bc-gray-50 cursor-pointer hover:bg-bc-gray-100 transition-colors">
                  <input
                    type="checkbox"
                    checked={(settings as any).enable_rich_templates ?? false}
                    onChange={e => update('enable_rich_templates' as any, e.target.checked)}
                    className="rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary"
                  />
                  <div>
                    <span className="text-sm text-bc-gray-700 font-medium flex items-center gap-1">
                      {t('Rich HTML templates')}
                      <HelpTooltip text={t('When enabled, AI will add rich elements like FAQ sections, comparison tables, and pros/cons boxes where they naturally fit the content.')} />
                    </span>
                    <p className="text-xs text-bc-gray-400">{t('Allow rich HTML templates in generated content (tables, FAQ, pros/cons, etc.)')}</p>
                  </div>
                </label>
                */}
              </div>
            </CardContent>
          </Card>

          {/* Admin UI Language */}
          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-5">
                <div className="w-9 h-9 rounded-bc bg-indigo-50 flex items-center justify-center">
                  <Globe className="w-5 h-5 text-indigo-600" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-bc-gray-800">{t('Admin UI Language')}</h2>
                  <p className="text-xs text-bc-gray-500">{t('Changes the admin interface language (does not affect generated content)')}</p>
                </div>
              </div>
              <div>
                <select
                  value={settings.admin_language}
                  onChange={e => {
                    const lang = e.target.value
                    update('admin_language', lang)
                  }}
                  className="w-full max-w-xs px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                >
                  <option value="he">עברית</option>
                  <option value="en">English</option>
                </select>
                <p className="text-xs text-bc-gray-400 mt-2">
                  {settings.admin_language !== getCurrentLocale()
                    ? t('Save settings and reload the page to apply the language change.')
                    : ''
                  }
                </p>
              </div>
            </CardContent>
          </Card>

          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-5">
                <div className="w-9 h-9 rounded-bc bg-sky-50 flex items-center justify-center">
                  <Globe className="w-5 h-5 text-sky-600" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-bc-gray-800">{t('Default working language')}</h2>
                  <p className="text-xs text-bc-gray-500">{t('Sets the default language for new reporters and content creation. Can be overridden per reporter.')}</p>
                </div>
              </div>
              <div>
                <select
                  value={settings.data_language}
                  onChange={e => update('data_language', e.target.value)}
                  className="w-full max-w-xs px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                >
                  <option value="he">{t('Hebrew Data')}</option>
                  <option value="en">{t('English Data')}</option>
                </select>
              </div>
            </CardContent>
          </Card>

          {/* Copyscape — Plagiarism Check */}
          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-5">
                <div className="w-9 h-9 rounded-bc bg-emerald-50 flex items-center justify-center">
                  <ShieldCheck className="w-5 h-5 text-emerald-600" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-bc-gray-800">{t('Copyscape — Plagiarism Check')}</h2>
                  <p className="text-xs text-bc-gray-500">{t('Check generated content for plagiarism before publishing')}</p>
                </div>
              </div>
              <div className="space-y-4">
                <label className="flex items-center gap-3 p-3 rounded-bc bg-bc-gray-50 cursor-pointer hover:bg-bc-gray-100 transition-colors">
                  <input
                    type="checkbox"
                    checked={settings.copyscape_enabled}
                    onChange={e => update('copyscape_enabled', e.target.checked)}
                    className="rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary"
                  />
                  <div>
                    <span className="text-sm text-bc-gray-700 font-medium">{t('Enable Copyscape plagiarism checking')}</span>
                    <p className="text-xs text-bc-gray-400">{t('Check generated content for plagiarism before publishing')}</p>
                  </div>
                </label>

                {settings.copyscape_enabled && (
                  <>
                    <div>
                      <label className="block text-sm font-medium text-bc-gray-700 mb-1">{t('Match Threshold')}</label>
                      <div className="flex items-center gap-2">
                        <input
                          type="number"
                          min={1}
                          max={50}
                          value={settings.copyscape_threshold}
                          onChange={e => update('copyscape_threshold', parseInt(e.target.value) || 5)}
                          className="w-24 px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
                        />
                        <span className="text-sm text-bc-gray-500">%</span>
                      </div>
                      <p className="text-xs text-bc-gray-400 mt-1">{t('Content below this threshold is considered original')}</p>
                    </div>

                    <label className="flex items-center gap-3 p-3 rounded-bc bg-bc-gray-50 cursor-pointer hover:bg-bc-gray-100 transition-colors">
                      <input
                        type="checkbox"
                        checked={settings.copyscape_auto_rewrite}
                        onChange={e => update('copyscape_auto_rewrite', e.target.checked)}
                        className="rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary"
                      />
                      <div>
                        <span className="text-sm text-bc-gray-700 font-medium">{t('Auto-rewrite matched sections')}</span>
                        <p className="text-xs text-bc-gray-400">{t('Matched sections will be sent to AI for targeted rewriting')}</p>
                      </div>
                    </label>

                    <div className="p-3 rounded-bc bg-bc-gray-50 text-xs text-bc-gray-500">
                      <span className="font-medium">📊 {t('Estimated cost')}:</span>{' '}
                      {t('Estimated Copyscape cost: ~2 BoostCoins per article')}
                    </div>
                  </>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Advanced */}
          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-5">
                <div className="w-9 h-9 rounded-bc bg-bc-gray-100 flex items-center justify-center">
                  <Shield className="w-5 h-5 text-bc-gray-500" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-bc-gray-800">{t('Advanced')}</h2>
                  <p className="text-xs text-bc-gray-500">{t('Debug and reset settings')}</p>
                </div>
              </div>
              <div className="space-y-4">
                <label className="flex items-center gap-3 p-3 rounded-bc bg-bc-gray-50 cursor-pointer hover:bg-bc-gray-100 transition-colors">
                  <input
                    type="checkbox"
                    checked={settings.debug_mode}
                    onChange={e => update('debug_mode', e.target.checked)}
                    className="rounded border-bc-gray-300 text-bc-primary focus:ring-bc-primary"
                  />
                  <div>
                    <span className="text-sm text-bc-gray-700 font-medium">{t('Debug Mode')}</span>
                    <p className="text-xs text-bc-gray-400">{t('Detailed logging of all actions')}</p>
                  </div>
                </label>

                <div className="pt-2 border-t border-bc-gray-100">
                  <Button
                    variant="ghost"
                    onClick={handleReset}
                    disabled={!loadSuccess || resetting}
                    loading={resetting}
                    icon={<RotateCcw className="w-4 h-4" />}
                    className="text-red-500 hover:text-red-600 hover:bg-red-50"
                  >
                    {t('Reset settings to defaults')}
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Save bar */}
          <div className={`sticky bottom-0 bg-white border-t border-bc-gray-200 -mx-6 px-6 py-4 flex items-center gap-4 transition-all ${hasChanges ? 'shadow-bc-md' : ''}`}>
            <Button
              variant="primary"
              onClick={handleSave}
              loading={saving}
              disabled={!loadSuccess || saving || !hasChanges}
              icon={<Save className="w-4 h-4" />}
            >
              {saving ? t('Saving...') : t('Save settings')}
            </Button>
            {hasChanges && (
              <span className="text-xs text-bc-gray-500">{t('Unsaved changes')}</span>
            )}
            {saveMessage && (
              <span className={`flex items-center gap-1.5 text-sm ${
                saveMessage.type === 'success' ? 'text-green-600' : 'text-red-600'
              }`}>
                {saveMessage.type === 'success'
                  ? <CheckCircle className="w-4 h-4" />
                  : <AlertCircle className="w-4 h-4" />
                }
                {saveMessage.text}
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
