import { useState, useEffect } from 'react'
import { api } from '../services/api'
import { MailIcon, ToggleLeftIcon, ToggleRightIcon } from '../components/icons'

interface SystemSettings {
  [key: string]: {
    value: boolean | string
    description?: string
  }
}

export default function EmailSettings() {
  const [settings, setSettings] = useState<SystemSettings>({})
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  useEffect(() => {
    fetchSettings()
  }, [])

  const fetchSettings = async () => {
    try {
      setLoading(true)
      const response = await api.get('/admin/settings')
      setSettings(response.data.data)
    } catch (err: any) {
      console.error('Failed to fetch settings:', err)
      setError('Einstellungen konnten nicht geladen werden')
    } finally {
      setLoading(false)
    }
  }

  const handleToggleSetting = async (key: string, currentValue: boolean) => {
    try {
      setSaving(true)
      setError('')
      setSuccess('')

      await api.put(`/admin/settings/${key}`, { 
        value: !currentValue 
      })

      // Update local state
      setSettings(prev => ({
        ...prev,
        [key]: {
          ...prev[key],
          value: !currentValue
        }
      }))

      setSuccess('Einstellung erfolgreich gespeichert')
      setTimeout(() => setSuccess(''), 3000)
    } catch (err: any) {
      console.error('Failed to update setting:', err)
      setError('Einstellung konnte nicht gespeichert werden')
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-secondary">Lade Einstellungen...</div>
      </div>
    )
  }

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-title-lg font-poppins font-bold text-primary mb-2">
          E-Mail-Einstellungen
        </h1>
        <p className="text-body text-secondary">
          Konfigurieren Sie die automatischen E-Mail-Benachrichtigungen des Systems
        </p>
      </div>

      {error && (
        <div className="bg-error-bg text-error px-4 py-3 rounded-input text-sm mb-6">
          {error}
        </div>
      )}

      {success && (
        <div className="bg-green-50 text-green-800 px-4 py-3 rounded-input text-sm mb-6">
          {success}
        </div>
      )}

      <div className="card">
        <div className="flex items-center mb-6">
          <MailIcon className="w-6 h-6 text-primary-blue mr-3" />
          <h2 className="text-title-card font-poppins font-semibold text-primary">
            Benachrichtigungseinstellungen
          </h2>
        </div>

        <div className="space-y-6">
          {Object.entries(settings).map(([key, setting]) => (
            <div key={key} className="flex items-center justify-between p-4 border border-border-light rounded-input hover:bg-bg-hover transition-colors">
              <div className="flex-1">
                <h3 className="text-body font-medium text-primary mb-1">
                  {key === 'email_notifications_enabled' ? 'Passwort-E-Mails versenden' : key}
                </h3>
                <p className="text-small text-secondary">
                  {setting.description || 'Automatische E-Mail-Benachrichtigungen für neue Benutzerpasswörter'}
                </p>
              </div>
              
              <div className="ml-4">
                <button
                  onClick={() => handleToggleSetting(key, setting.value as boolean)}
                  disabled={saving}
                  className={`flex items-center space-x-2 px-4 py-2 rounded-full transition-colors ${
                    setting.value 
                      ? 'bg-primary-blue text-white' 
                      : 'bg-gray-200 text-gray-600'
                  } ${saving ? 'opacity-50 cursor-not-allowed' : 'hover:opacity-80'}`}
                >
                  {setting.value ? (
                    <>
                      <ToggleRightIcon className="w-5 h-5" />
                      <span className="text-sm font-medium">Ein</span>
                    </>
                  ) : (
                    <>
                      <ToggleLeftIcon className="w-5 h-5" />
                      <span className="text-sm font-medium">Aus</span>
                    </>
                  )}
                </button>
              </div>
            </div>
          ))}
        </div>

        <div className="mt-8 p-4 bg-blue-50 border border-blue-200 rounded-input">
          <h3 className="text-body font-semibold text-primary mb-2">
            💡 Hinweise zur E-Mail-Konfiguration
          </h3>
          <ul className="text-small text-secondary space-y-1">
            <li>• E-Mail-Versand erfordert die Konfiguration von SMTP-Einstellungen in den Umgebungsvariablen</li>
            <li>• Umgebungsvariablen: EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASS, EMAIL_FROM</li>
            <li>• Die Standardeinstellung ist "Aus" aus Datenschutzgründen</li>
            <li>• Passwörter werden nur einmal per E-Mail versendet und können nicht erneut abgerufen werden</li>
          </ul>
        </div>
      </div>
    </div>
  )
}