import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { Spinner } from '../components/Spinner'
import { Layout } from '../components/Layout'

interface UserOut {
  id: string; first_name: string; last_name: string; email: string; role: string; company_id: string
}

interface SmtpConfigOut {
  id: string
  company_id: string
  host: string
  port: number
  use_tls: boolean
  use_starttls: boolean
  username: string | null
  from_email: string
  from_name: string
  is_enabled: boolean
}

const DEFAULT_FORM = {
  host: '',
  port: 587,
  use_tls: false,
  use_starttls: true,
  username: '',
  password: '',
  from_email: '',
  from_name: 'TimeMaster',
  is_enabled: true,
}

export function SmtpSettingsPage() {
  const [user, setUser] = useState<UserOut | null>(null)
  const [config, setConfig] = useState<SmtpConfigOut | null>(null)
  const [form, setForm] = useState(DEFAULT_FORM)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [testing, setTesting] = useState(false)
  const [testEmail, setTestEmail] = useState('')
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  useEffect(() => {
    async function load() {
      try {
        const [me, cfg] = await Promise.all([
          api.get<UserOut>('/auth/me'),
          api.get<SmtpConfigOut | null>('/smtp/config'),
        ])
        setUser(me)
        setTestEmail(me.email)
        if (cfg) {
          setConfig(cfg)
          setForm({
            host: cfg.host,
            port: cfg.port,
            use_tls: cfg.use_tls,
            use_starttls: cfg.use_starttls,
            username: cfg.username ?? '',
            password: '',  // nie vom Server zurückgegeben
            from_email: cfg.from_email,
            from_name: cfg.from_name,
            is_enabled: cfg.is_enabled,
          })
        }
      } catch (e: unknown) {
        setError(e instanceof Error ? e.message : 'Fehler beim Laden')
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  const save = async () => {
    setSaving(true)
    setError('')
    setSuccess('')
    try {
      const body = {
        ...form,
        username: form.username || null,
        password: form.password || null,
      }
      const saved = await api.post<SmtpConfigOut>('/smtp/config', body)
      setConfig(saved)
      setForm(f => ({ ...f, password: '' }))
      setSuccess('SMTP-Konfiguration gespeichert.')
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler beim Speichern')
    } finally {
      setSaving(false)
    }
  }

  const test = async () => {
    if (!testEmail) return
    setTesting(true)
    setError('')
    setSuccess('')
    try {
      const res = await api.post<{ message: string }>('/smtp/test', { to: testEmail })
      setSuccess(res.message)
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'SMTP-Test fehlgeschlagen')
    } finally {
      setTesting(false)
    }
  }

  const set = (key: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.type === 'checkbox' ? e.target.checked : e.target.type === 'number' ? Number(e.target.value) : e.target.value
    setForm(f => ({ ...f, [key]: val }))
  }

  const inputCls = 'w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'

  if (loading) return <Layout userRole='' userName=''><div className='flex justify-center py-20'><Spinner /></div></Layout>
  if (!user) return null

  return (
    <Layout userRole={user.role} userName={`${user.first_name} ${user.last_name}`}>
      <div className='max-w-2xl space-y-6'>
        <h1 className='text-2xl font-bold text-gray-900'>SMTP-Konfiguration</h1>

        {error   && <div className='bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700'>{error}</div>}
        {success && <div className='bg-green-50 border border-green-200 rounded-lg p-3 text-sm text-green-700'>{success}</div>}

        <div className='bg-white rounded-xl shadow-sm border border-gray-200 p-6 space-y-5'>
          <h2 className='text-base font-semibold text-gray-800'>Postausgangs-Server</h2>

          <div className='grid grid-cols-3 gap-3'>
            <div className='col-span-2'>
              <label className='block text-sm font-medium text-gray-700 mb-1'>SMTP-Server *</label>
              <input type='text' value={form.host} onChange={set('host')} placeholder='mail.example.de' className={inputCls} />
            </div>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Port *</label>
              <input type='number' value={form.port} onChange={set('port')} min={1} max={65535} className={inputCls} />
            </div>
          </div>

          <div className='flex gap-6'>
            <label className='flex items-center gap-2 text-sm text-gray-700 cursor-pointer'>
              <input type='checkbox' checked={form.use_starttls} onChange={set('use_starttls')} className='rounded' />
              STARTTLS (Port 587)
            </label>
            <label className='flex items-center gap-2 text-sm text-gray-700 cursor-pointer'>
              <input type='checkbox' checked={form.use_tls} onChange={set('use_tls')} className='rounded' />
              SSL/TLS (Port 465)
            </label>
          </div>

          <div className='grid grid-cols-2 gap-3'>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Benutzername</label>
              <input type='text' value={form.username} onChange={set('username')} placeholder='user@example.de' className={inputCls} />
            </div>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>
                Passwort {config ? '(leer lassen = unverändert)' : ''}
              </label>
              <input type='password' value={form.password} onChange={set('password')} placeholder='••••••••' className={inputCls} autoComplete='new-password' />
            </div>
          </div>

          <div className='grid grid-cols-2 gap-3'>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Absender-E-Mail *</label>
              <input type='email' value={form.from_email} onChange={set('from_email')} placeholder='noreply@example.de' className={inputCls} />
            </div>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Absender-Name *</label>
              <input type='text' value={form.from_name} onChange={set('from_name')} placeholder='TimeMaster' className={inputCls} />
            </div>
          </div>

          <label className='flex items-center gap-2 text-sm text-gray-700 cursor-pointer'>
            <input type='checkbox' checked={form.is_enabled} onChange={set('is_enabled')} className='rounded' />
            SMTP aktiviert (E-Mails werden tatsächlich versendet)
          </label>

          <div className='flex justify-end'>
            <button
              onClick={save}
              disabled={saving || !form.host || !form.from_email}
              className='px-5 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50'
            >
              {saving ? 'Speichern…' : 'Konfiguration speichern'}
            </button>
          </div>
        </div>

        {/* Test */}
        {config && (
          <div className='bg-white rounded-xl shadow-sm border border-gray-200 p-6'>
            <h2 className='text-base font-semibold text-gray-800 mb-4'>Test-E-Mail senden</h2>
            <div className='flex gap-3'>
              <input
                type='email'
                value={testEmail}
                onChange={e => setTestEmail(e.target.value)}
                placeholder='test@example.de'
                className={`flex-1 ${inputCls}`}
              />
              <button
                onClick={test}
                disabled={testing || !testEmail}
                className='px-5 py-2 bg-gray-700 text-white rounded-lg text-sm font-medium hover:bg-gray-800 disabled:opacity-50'
              >
                {testing ? 'Sende…' : 'Test senden'}
              </button>
            </div>
            <p className='text-xs text-gray-400 mt-2'>
              Sendet eine Test-E-Mail mit der aktuell <em>gespeicherten</em> Konfiguration.
            </p>
          </div>
        )}

        {/* Preset-Hilfe */}
        <div className='bg-blue-50 border border-blue-100 rounded-xl p-5'>
          <p className='text-sm font-semibold text-blue-800 mb-2'>Typische Einstellungen</p>
          <div className='grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-blue-700'>
            {[
              { name: 'Gmail', host: 'smtp.gmail.com', port: '587', tls: 'STARTTLS' },
              { name: 'Outlook/Office 365', host: 'smtp.office365.com', port: '587', tls: 'STARTTLS' },
              { name: 'Ionos / 1&1', host: 'smtp.ionos.de', port: '587', tls: 'STARTTLS' },
              { name: 'Strato', host: 'smtp.strato.de', port: '465', tls: 'SSL/TLS' },
            ].map(p => (
              <div key={p.name} className='bg-white rounded-lg px-3 py-2'>
                <span className='font-medium'>{p.name}</span>: {p.host}:{p.port} ({p.tls})
              </div>
            ))}
          </div>
        </div>
      </div>
    </Layout>
  )
}
