import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import {
  Settings as SettingsIcon,
  Bell,
  Mail,
  MessageCircle,
  Monitor,
  Server,
  Save,
  TestTube,
  CheckCircle2,
  XCircle,
  Loader2,
  Clock,
  Shield,
  HardDrive,
  Info
} from 'lucide-react'
import { useStore } from '../store/useStore'
import type { AppSettings, NotificationType } from '@shared/types'

// Section Component
function SettingsSection({ 
  title, 
  icon: Icon, 
  children 
}: { 
  title: string
  icon: React.ElementType
  children: React.ReactNode
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="bg-dark-800 border border-dark-700 rounded-xl p-6"
    >
      <h2 className="text-lg font-semibold text-dark-100 flex items-center gap-2 mb-4">
        <Icon className="w-5 h-5 text-accent-purple" />
        {title}
      </h2>
      {children}
    </motion.div>
  )
}

// Toggle Switch
function Toggle({ 
  enabled, 
  onChange 
}: { 
  enabled: boolean
  onChange: (value: boolean) => void
}) {
  return (
    <button
      onClick={() => onChange(!enabled)}
      className={`relative w-12 h-6 rounded-full transition-colors ${
        enabled ? 'bg-accent-blue' : 'bg-dark-600'
      }`}
    >
      <span
        className={`absolute top-1 w-4 h-4 rounded-full bg-white transition-transform ${
          enabled ? 'left-7' : 'left-1'
        }`}
      />
    </button>
  )
}

// Input Field
function InputField({ 
  label, 
  type = 'text',
  value, 
  onChange,
  placeholder
}: { 
  label: string
  type?: string
  value: string | number
  onChange: (value: string) => void
  placeholder?: string
}) {
  return (
    <div>
      <label className="block text-sm text-dark-300 mb-2">{label}</label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="w-full px-4 py-2 bg-dark-700 border border-dark-600 rounded-lg text-dark-100 placeholder-dark-500 focus:outline-none focus:border-accent-blue"
      />
    </div>
  )
}

// Test Button
function TestButton({ 
  type, 
  onTest 
}: { 
  type: NotificationType
  onTest: (type: NotificationType) => Promise<void>
}) {
  const [testing, setTesting] = useState(false)
  const [result, setResult] = useState<'success' | 'error' | null>(null)

  const handleTest = async () => {
    setTesting(true)
    setResult(null)
    try {
      await onTest(type)
      setResult('success')
    } catch {
      setResult('error')
    } finally {
      setTesting(false)
      setTimeout(() => setResult(null), 3000)
    }
  }

  return (
    <button
      onClick={handleTest}
      disabled={testing}
      className="flex items-center gap-2 px-3 py-1.5 bg-dark-600 text-dark-300 rounded-lg hover:bg-dark-500 transition-colors disabled:opacity-50"
    >
      {testing ? (
        <Loader2 className="w-4 h-4 spinner" />
      ) : result === 'success' ? (
        <CheckCircle2 className="w-4 h-4 text-accent-green" />
      ) : result === 'error' ? (
        <XCircle className="w-4 h-4 text-accent-red" />
      ) : (
        <TestTube className="w-4 h-4" />
      )}
      Test
    </button>
  )
}

export default function Settings() {
  const { settings, setSettings } = useStore()
  const [localSettings, setLocalSettings] = useState<AppSettings | null>(settings)
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState(false)
  const [appInfo, setAppInfo] = useState<{ version: string; isPortable: boolean; dataPath: string } | null>(null)

  useEffect(() => {
    setLocalSettings(settings)
  }, [settings])

  useEffect(() => {
    const loadAppInfo = async () => {
      if (window.electron?.getAppInfo) {
        const info = await window.electron.getAppInfo()
        setAppInfo(info)
      }
    }
    loadAppInfo()
  }, [])

  const handleSave = async () => {
    if (!localSettings) return
    
    setSaving(true)
    try {
      if (window.electron) {
        await window.electron.saveSettings(localSettings)
      }
      setSettings(localSettings)
      setSaved(true)
      setTimeout(() => setSaved(false), 2000)
    } catch (error) {
      console.error('Failed to save settings:', error)
    } finally {
      setSaving(false)
    }
  }

  const handleTestNotification = async (type: NotificationType) => {
    if (window.electron) {
      await window.electron.testNotification(type)
    }
  }

  const updateSettings = (path: string, value: unknown) => {
    if (!localSettings) return
    
    const keys = path.split('.')
    const newSettings = { ...localSettings }
    let current: Record<string, unknown> = newSettings as Record<string, unknown>
    
    for (let i = 0; i < keys.length - 1; i++) {
      current[keys[i]] = { ...(current[keys[i]] as Record<string, unknown>) }
      current = current[keys[i]] as Record<string, unknown>
    }
    current[keys[keys.length - 1]] = value
    
    setLocalSettings(newSettings as AppSettings)
  }

  if (!localSettings) {
    return (
      <div className="flex items-center justify-center h-full">
        <Loader2 className="w-8 h-8 text-accent-blue spinner" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-display font-bold text-dark-100 flex items-center gap-3">
            <SettingsIcon className="w-7 h-7 text-accent-purple" />
            Ayarlar
          </h1>
          <p className="text-dark-400 text-sm mt-1">
            Uygulama ve bildirim ayarlarını yapılandırın
          </p>
        </div>

        <button
          onClick={handleSave}
          disabled={saving}
          className="flex items-center gap-2 px-4 py-2 bg-accent-blue text-white rounded-lg hover:bg-accent-blue/80 transition-colors disabled:opacity-50"
        >
          {saving ? (
            <Loader2 className="w-4 h-4 spinner" />
          ) : saved ? (
            <CheckCircle2 className="w-4 h-4" />
          ) : (
            <Save className="w-4 h-4" />
          )}
          {saved ? 'Kaydedildi!' : 'Kaydet'}
        </button>
      </div>

      <div className="grid grid-cols-2 gap-6">
        {/* General Settings */}
        <SettingsSection title="Genel Ayarlar" icon={Monitor}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Başlangıçta minimize</p>
                <p className="text-xs text-dark-400">Uygulama açıldığında küçültülmüş başla</p>
              </div>
              <Toggle
                enabled={localSettings.general.startMinimized}
                onChange={(v) => updateSettings('general.startMinimized', v)}
              />
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Tray'e küçült</p>
                <p className="text-xs text-dark-400">Kapatma yerine system tray'e taşı</p>
              </div>
              <Toggle
                enabled={localSettings.general.minimizeToTray}
                onChange={(v) => updateSettings('general.minimizeToTray', v)}
              />
            </div>
          </div>
        </SettingsSection>

        {/* Monitoring Settings */}
        <SettingsSection title="İzleme Ayarları" icon={Clock}>
          <div className="space-y-4">
            <InputField
              label="Ping Aralığı (saniye)"
              type="number"
              value={localSettings.monitoring.pingInterval}
              onChange={(v) => updateSettings('monitoring.pingInterval', parseInt(v) || 30)}
            />
            <InputField
              label="Stream Kontrol Aralığı (saniye)"
              type="number"
              value={localSettings.monitoring.streamCheckInterval}
              onChange={(v) => updateSettings('monitoring.streamCheckInterval', parseInt(v) || 60)}
            />
            <InputField
              label="Zaman Aşımı (ms)"
              type="number"
              value={localSettings.monitoring.timeout}
              onChange={(v) => updateSettings('monitoring.timeout', parseInt(v) || 5000)}
            />
          </div>
        </SettingsSection>

        {/* Windows Notifications */}
        <SettingsSection title="Windows Bildirimleri" icon={Bell}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Etkin</p>
                <p className="text-xs text-dark-400">Windows toast bildirimleri</p>
              </div>
              <div className="flex items-center gap-3">
                <TestButton type="windows" onTest={handleTestNotification} />
                <Toggle
                  enabled={localSettings.notifications.windows.enabled}
                  onChange={(v) => updateSettings('notifications.windows.enabled', v)}
                />
              </div>
            </div>
          </div>
        </SettingsSection>

        {/* Telegram Settings */}
        <SettingsSection title="Telegram Bildirimleri" icon={MessageCircle}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Etkin</p>
                <p className="text-xs text-dark-400">Telegram bot bildirimleri</p>
              </div>
              <div className="flex items-center gap-3">
                <TestButton type="telegram" onTest={handleTestNotification} />
                <Toggle
                  enabled={localSettings.notifications.telegram.enabled}
                  onChange={(v) => updateSettings('notifications.telegram.enabled', v)}
                />
              </div>
            </div>
            <InputField
              label="Bot Token"
              value={localSettings.notifications.telegram.botToken}
              onChange={(v) => updateSettings('notifications.telegram.botToken', v)}
              placeholder="123456:ABC-DEF..."
            />
            <InputField
              label="Chat ID"
              value={localSettings.notifications.telegram.chatId}
              onChange={(v) => updateSettings('notifications.telegram.chatId', v)}
              placeholder="-1001234567890"
            />
          </div>
        </SettingsSection>

        {/* Email Settings */}
        <SettingsSection title="Email Bildirimleri" icon={Mail}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Etkin</p>
                <p className="text-xs text-dark-400">SMTP email bildirimleri</p>
              </div>
              <div className="flex items-center gap-3">
                <TestButton type="email" onTest={handleTestNotification} />
                <Toggle
                  enabled={localSettings.notifications.email.enabled}
                  onChange={(v) => updateSettings('notifications.email.enabled', v)}
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <InputField
                label="SMTP Sunucu"
                value={localSettings.notifications.email.smtpHost}
                onChange={(v) => updateSettings('notifications.email.smtpHost', v)}
                placeholder="smtp.gmail.com"
              />
              <InputField
                label="Port"
                type="number"
                value={localSettings.notifications.email.smtpPort}
                onChange={(v) => updateSettings('notifications.email.smtpPort', parseInt(v) || 587)}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <InputField
                label="Kullanıcı"
                value={localSettings.notifications.email.smtpUser}
                onChange={(v) => updateSettings('notifications.email.smtpUser', v)}
              />
              <InputField
                label="Şifre"
                type="password"
                value={localSettings.notifications.email.smtpPass}
                onChange={(v) => updateSettings('notifications.email.smtpPass', v)}
              />
            </div>
            <InputField
              label="Alıcı Email"
              value={localSettings.notifications.email.toEmail}
              onChange={(v) => updateSettings('notifications.email.toEmail', v)}
              placeholder="admin@example.com"
            />
          </div>
        </SettingsSection>

        {/* Panel Integration */}
        <SettingsSection title="Panel Entegrasyonu" icon={Server}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Etkin</p>
                <p className="text-xs text-dark-400">Monitor API entegrasyonu</p>
              </div>
              <Toggle
                enabled={localSettings.panel.enabled}
                onChange={(v) => updateSettings('panel.enabled', v)}
              />
            </div>
            <InputField
              label="API URL"
              value={localSettings.panel.apiUrl}
              onChange={(v) => updateSettings('panel.apiUrl', v)}
              placeholder="https://panel.example.com/attacker_detection"
            />
            <InputField
              label="Monitor ID"
              value={localSettings.panel.monitorId}
              onChange={(v) => updateSettings('panel.monitorId', v)}
              placeholder="monitor-1"
            />
            <InputField
              label="Auth Token"
              type="password"
              value={localSettings.panel.authToken}
              onChange={(v) => updateSettings('panel.authToken', v)}
            />
          </div>
        </SettingsSection>

        {/* Notification Rules */}
        <SettingsSection title="Bildirim Kuralları" icon={Shield}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Otomatik Bildirim</p>
                <p className="text-xs text-dark-400">Hata anında otomatik bildir</p>
              </div>
              <Toggle
                enabled={localSettings.notifications.autoNotify}
                onChange={(v) => updateSettings('notifications.autoNotify', v)}
              />
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Ping Hatası</p>
                <p className="text-xs text-dark-400">Ping başarısız olduğunda</p>
              </div>
              <Toggle
                enabled={localSettings.notifications.notifyOnPingFail}
                onChange={(v) => updateSettings('notifications.notifyOnPingFail', v)}
              />
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">404 Hatası</p>
                <p className="text-xs text-dark-400">HTTP 404 alındığında</p>
              </div>
              <Toggle
                enabled={localSettings.notifications.notifyOn404}
                onChange={(v) => updateSettings('notifications.notifyOn404', v)}
              />
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Bağlantı Hatası</p>
                <p className="text-xs text-dark-400">ERR_CONNRESET gibi hatalar</p>
              </div>
              <Toggle
                enabled={localSettings.notifications.notifyOnConnReset}
                onChange={(v) => updateSettings('notifications.notifyOnConnReset', v)}
              />
            </div>
          </div>
        </SettingsSection>

        {/* App Info */}
        <SettingsSection title="Uygulama Bilgisi" icon={Info}>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-dark-100">Versiyon</p>
                <p className="text-xs text-dark-400">IP Monitor</p>
              </div>
              <span className="text-accent-blue font-mono">v{appInfo?.version || '1.0.0'}</span>
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <HardDrive className="w-4 h-4 text-dark-400" />
                <div>
                  <p className="text-dark-100">Çalışma Modu</p>
                  <p className="text-xs text-dark-400">Ayarların saklandığı konum</p>
                </div>
              </div>
              <span className={`px-2 py-1 rounded text-xs font-medium ${
                appInfo?.isPortable 
                  ? 'bg-accent-green/20 text-accent-green' 
                  : 'bg-accent-blue/20 text-accent-blue'
              }`}>
                {appInfo?.isPortable ? 'Portable' : 'Normal'}
              </span>
            </div>
            {appInfo?.dataPath && (
              <div className="bg-dark-700/50 rounded-lg p-3">
                <p className="text-xs text-dark-400 mb-1">Veri Konumu:</p>
                <p className="text-xs text-dark-300 font-mono break-all">{appInfo.dataPath}</p>
              </div>
            )}
            <div className="text-xs text-dark-500 mt-2">
              <p>💡 Portable mod için exe yanına <code className="bg-dark-700 px-1 rounded">portable.txt</code> dosyası oluşturun veya <code className="bg-dark-700 px-1 rounded">data</code> klasörü açın.</p>
            </div>
          </div>
        </SettingsSection>
      </div>
    </div>
  )
}

