import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { emailProviderApi, EmailProviderConfig } from '../../services/api';
import Card from '../../components/ui/Card';
import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import Select from '../../components/ui/Select';
import { ArrowLeft, Plus, Edit, Trash2, Check, X, Wifi, WifiOff, Eye, EyeOff, Mail } from 'lucide-react';

const PROVIDER_TYPES = [
  { value: 'PLESK', label: 'Plesk' },
  { value: 'CPANEL', label: 'cPanel' },
  { value: 'DIRECTADMIN', label: 'DirectAdmin' },
];

// Verschlüsselungstyp
type MailEncryption = 'SSL' | 'STARTTLS' | 'NONE';

const ENCRYPTION_OPTIONS = [
  { value: 'SSL', label: 'SSL/TLS', description: 'Verschlüsselung von Anfang an' },
  { value: 'STARTTLS', label: 'STARTTLS', description: 'Startet unverschlüsselt, dann Upgrade' },
  { value: 'NONE', label: 'Keine', description: 'Keine Verschlüsselung' },
];

interface ProviderFormData {
  name: string;
  type: 'PLESK' | 'CPANEL' | 'DIRECTADMIN';
  apiUrl: string;
  apiKey: string;
  username: string;
  password: string;
  domain: string;
  // Optional: Bezeichnung im UI. Wenn leer, wird sie aus der Domain abgeleitet
  // (z.B. "stressfrei-wechseln.de" → "Stressfrei-Wechseln"). Hier kann ein
  // freier Override gesetzt werden (z.B. "interne Kunden Email Adressen"),
  // ohne die echte Domain zu ändern.
  customerEmailLabel: string;
  defaultForwardEmail: string;
  // Verschlüsselungs-Einstellungen
  imapEncryption: MailEncryption;
  smtpEncryption: MailEncryption;
  allowSelfSignedCerts: boolean;
  // System-E-Mail
  systemEmailAddress: string;
  systemEmailPassword: string;
  isActive: boolean;
  isDefault: boolean;
}

const emptyForm: ProviderFormData = {
  name: '',
  type: 'PLESK',
  apiUrl: '',
  apiKey: '',
  username: '',
  password: '',
  domain: 'stressfrei-wechseln.de',
  customerEmailLabel: '',
  defaultForwardEmail: '',
  imapEncryption: 'SSL',
  smtpEncryption: 'SSL',
  allowSelfSignedCerts: false,
  systemEmailAddress: '',
  systemEmailPassword: '',
  isActive: true,
  isDefault: false,
};

interface TestResult {
  success: boolean;
  message?: string;
  error?: string;
}

export default function EmailProviders() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<ProviderFormData>(emptyForm);
  const [showPassword, setShowPassword] = useState(false);
  const [showSystemPassword, setShowSystemPassword] = useState(false);
  const [modalTestResult, setModalTestResult] = useState<TestResult | null>(null);
  const [isTestingInModal, setIsTestingInModal] = useState(false);
  // Test-Status pro Provider in der Liste
  const [providerTestResults, setProviderTestResults] = useState<Record<number, TestResult | null>>({});
  const [testingProviderId, setTestingProviderId] = useState<number | null>(null);
  // E-Mail-Zugang-Test
  const [isTestingMailAccess, setIsTestingMailAccess] = useState(false);
  const [mailAccessResult, setMailAccessResult] = useState<{
    imap: { success: boolean; error?: string; server: string; port: number; encryption: string };
    smtp: { success: boolean; error?: string; server: string; port: number; encryption: string };
    user: string;
  } | null>(null);

  const { data: configsData, isLoading } = useQuery({
    queryKey: ['email-provider-configs'],
    queryFn: () => emailProviderApi.getConfigs(),
  });

  const createMutation = useMutation({
    mutationFn: (data: Partial<EmailProviderConfig> & { password?: string }) =>
      emailProviderApi.createConfig(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-provider-configs'] });
      queryClient.invalidateQueries({ queryKey: ['email-provider-public-settings'] });
      closeModal();
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<EmailProviderConfig> & { password?: string } }) =>
      emailProviderApi.updateConfig(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-provider-configs'] });
      queryClient.invalidateQueries({ queryKey: ['email-provider-public-settings'] });
      closeModal();
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => emailProviderApi.deleteConfig(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-provider-configs'] });
      queryClient.invalidateQueries({ queryKey: ['email-provider-public-settings'] });
    },
  });

  const configs = configsData?.data || [];

  const openCreateModal = () => {
    setFormData(emptyForm);
    setEditingId(null);
    setShowPassword(false);
    setModalTestResult(null);
    setIsModalOpen(true);
  };

  const openEditModal = (config: EmailProviderConfig) => {
    setFormData({
      name: config.name,
      type: config.type,
      apiUrl: config.apiUrl,
      apiKey: config.apiKey || '',
      username: config.username || '',
      password: '', // Passwort wird nicht geladen
      domain: config.domain,
      customerEmailLabel: config.customerEmailLabel || '',
      defaultForwardEmail: config.defaultForwardEmail || '',
      imapEncryption: config.imapEncryption ?? 'SSL',
      smtpEncryption: config.smtpEncryption ?? 'SSL',
      allowSelfSignedCerts: config.allowSelfSignedCerts ?? false,
      systemEmailAddress: config.systemEmailAddress || '',
      systemEmailPassword: '', // Passwort wird nicht geladen
      isActive: config.isActive,
      isDefault: config.isDefault,
    });
    setEditingId(config.id);
    setShowPassword(false);
    setModalTestResult(null);
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setEditingId(null);
    setFormData(emptyForm);
    setShowPassword(false);
    setModalTestResult(null);
    setMailAccessResult(null);
  };

  // Test für einen gespeicherten Provider in der Liste
  const handleTestProvider = async (config: EmailProviderConfig) => {
    setTestingProviderId(config.id);
    setProviderTestResults((prev) => ({ ...prev, [config.id]: null }));

    try {
      // Provider per ID testen (Backend holt das gespeicherte Passwort)
      const result = await emailProviderApi.testConnection({ id: config.id });
      const testResult: TestResult = {
        success: result.data?.success || false,
        message: result.data?.message,
        error: result.data?.error,
      };
      setProviderTestResults((prev) => ({ ...prev, [config.id]: testResult }));
    } catch (error) {
      setProviderTestResults((prev) => ({
        ...prev,
        [config.id]: {
          success: false,
          error: error instanceof Error ? error.message : 'Unbekannter Fehler beim Testen',
        },
      }));
    } finally {
      setTestingProviderId(null);
    }
  };

  // Test im Modal mit aktuellen Formulardaten
  const handleTestInModal = async () => {
    // Nur URL und Domain sind Pflicht - Auth-Fehler kommen vom Backend
    if (!formData.apiUrl || !formData.domain) {
      setModalTestResult({ success: false, error: 'Bitte geben Sie API-URL und Domain ein.' });
      return;
    }

    setIsTestingInModal(true);
    setModalTestResult(null);
    try {
      const result = await emailProviderApi.testConnection({
        testData: {
          type: formData.type,
          apiUrl: formData.apiUrl,
          apiKey: formData.apiKey || undefined,
          username: formData.username || undefined,
          password: formData.password || undefined,
          domain: formData.domain,
        }
      });
      setModalTestResult({
        success: result.data?.success || false,
        message: result.data?.message,
        error: result.data?.error,
      });
    } catch (error) {
      setModalTestResult({
        success: false,
        error: error instanceof Error ? error.message : 'Unbekannter Fehler beim Verbindungstest'
      });
    } finally {
      setIsTestingInModal(false);
    }
  };

  // IMAP + SMTP-Zugang der System-E-Mail testen
  const handleTestMailAccess = async () => {
    if (!formData.systemEmailAddress) {
      setMailAccessResult({
        imap: { success: false, error: 'System-E-Mail-Adresse fehlt', server: '', port: 0, encryption: '' },
        smtp: { success: false, error: 'System-E-Mail-Adresse fehlt', server: '', port: 0, encryption: '' },
        user: '',
      });
      return;
    }

    setIsTestingMailAccess(true);
    setMailAccessResult(null);
    try {
      const body: Parameters<typeof emailProviderApi.testMailAccess>[0] = editingId
        ? {
            id: editingId,
            systemEmailAddress: formData.systemEmailAddress,
            systemEmailPassword: formData.systemEmailPassword || undefined,
          }
        : {
            apiUrl: formData.apiUrl,
            domain: formData.domain,
            systemEmailAddress: formData.systemEmailAddress,
            systemEmailPassword: formData.systemEmailPassword,
            imapEncryption: formData.imapEncryption,
            smtpEncryption: formData.smtpEncryption,
            allowSelfSignedCerts: formData.allowSelfSignedCerts,
          };

      const result = await emailProviderApi.testMailAccess(body);
      if (result.data) {
        setMailAccessResult(result.data);
      }
    } catch (error) {
      setMailAccessResult({
        imap: {
          success: false,
          error: error instanceof Error ? error.message : 'Fehler beim Test',
          server: '',
          port: 0,
          encryption: '',
        },
        smtp: { success: false, server: '', port: 0, encryption: '' },
        user: '',
      });
    } finally {
      setIsTestingMailAccess(false);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const data: Partial<EmailProviderConfig> & { password?: string } = {
      name: formData.name,
      type: formData.type,
      apiUrl: formData.apiUrl,
      apiKey: formData.apiKey,  // Leerer String wird im Backend zu null
      username: formData.username,
      domain: formData.domain,
      customerEmailLabel: formData.customerEmailLabel.trim() || null,
      defaultForwardEmail: formData.defaultForwardEmail,
      imapEncryption: formData.imapEncryption,
      smtpEncryption: formData.smtpEncryption,
      allowSelfSignedCerts: formData.allowSelfSignedCerts,
      systemEmailAddress: formData.systemEmailAddress,
      isActive: formData.isActive,
      isDefault: formData.isDefault,
    };

    // Passwort nur senden wenn eingegeben
    if (formData.password) {
      data.password = formData.password;
    }

    // System-E-Mail-Passwort nur senden wenn eingegeben
    if (formData.systemEmailPassword) {
      (data as any).systemEmailPassword = formData.systemEmailPassword;
    }

    if (editingId) {
      updateMutation.mutate({ id: editingId, data });
    } else {
      createMutation.mutate(data);
    }
  };

  const handleDelete = (id: number, name: string) => {
    if (confirm(`Möchten Sie den Provider "${name}" wirklich löschen?`)) {
      deleteMutation.mutate(id);
    }
  };

  // Fehlermeldung benutzerfreundlich formatieren
  const formatErrorMessage = (result: TestResult): string => {
    if (result.error) return result.error;
    if (result.message) return result.message;
    return 'Verbindung fehlgeschlagen';
  };

  return (
    <div>
      <div className="flex items-center gap-4 mb-6">
        <Button variant="ghost" onClick={() => navigate('/settings')}>
          <ArrowLeft className="w-4 h-4 mr-2" />
          Zurück
        </Button>
        <h1 className="text-2xl font-bold">Email-Provisionierung</h1>
      </div>

      <Card className="mb-6">
        <p className="text-gray-600 mb-4">
          Hier konfigurieren Sie die automatische Erstellung von Kunden-E-Mail-Adressen auf Ihrer
          eigenen Domain. Wenn beim Anlegen einer Adresse die Option "Bei Provider anlegen"
          aktiviert ist, wird die E-Mail-Weiterleitung automatisch erstellt.
        </p>
        <Button onClick={openCreateModal}>
          <Plus className="w-4 h-4 mr-2" />
          Provider hinzufügen
        </Button>
      </Card>

      {isLoading ? (
        <div className="text-center py-8">Laden...</div>
      ) : configs.length === 0 ? (
        <Card>
          <div className="text-center py-8 text-gray-500">
            Noch keine Email-Provider konfiguriert.
          </div>
        </Card>
      ) : (
        <div className="space-y-4">
          {configs.map((config) => {
            const testResult = providerTestResults[config.id];
            const isTesting = testingProviderId === config.id;

            return (
              <Card key={config.id}>
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3">
                      <h3 className="font-semibold text-lg">{config.name}</h3>
                      <span className="px-2 py-1 text-xs rounded bg-blue-100 text-blue-800">
                        {config.type}
                      </span>
                      {config.isDefault && (
                        <span className="px-2 py-1 text-xs rounded bg-green-100 text-green-800">
                          Standard
                        </span>
                      )}
                      {!config.isActive && (
                        <span className="px-2 py-1 text-xs rounded bg-gray-100 text-gray-600">
                          Inaktiv
                        </span>
                      )}
                    </div>
                    <dl className="mt-3 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <dt className="text-gray-500">API-URL</dt>
                        <dd className="font-mono text-xs truncate">{config.apiUrl}</dd>
                      </div>
                      <div>
                        <dt className="text-gray-500">Domain</dt>
                        <dd>{config.domain}</dd>
                      </div>
                      <div>
                        <dt className="text-gray-500">Benutzer</dt>
                        <dd>{config.username || '-'}</dd>
                      </div>
                      <div>
                        <dt className="text-gray-500">Standard-Weiterleitung</dt>
                        <dd className="truncate">{config.defaultForwardEmail || '-'}</dd>
                      </div>
                      <div>
                        <dt className="text-gray-500">System-E-Mail</dt>
                        <dd className="truncate">{config.systemEmailAddress || <span className="text-amber-500">nicht konfiguriert</span>}</dd>
                      </div>
                    </dl>

                    {/* Test-Ergebnis für diesen Provider */}
                    {testResult && (
                      <div className={`mt-3 p-3 rounded-lg text-sm ${testResult.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
                        {testResult.success ? (
                          <div className="flex items-center gap-2">
                            <Check className="w-4 h-4 flex-shrink-0" />
                            <span>Verbindung erfolgreich!</span>
                          </div>
                        ) : (
                          <div className="flex items-start gap-2">
                            <WifiOff className="w-4 h-4 flex-shrink-0 mt-0.5" />
                            <span>{formatErrorMessage(testResult)}</span>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                  <div className="flex gap-2 ml-4">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleTestProvider(config)}
                      disabled={isTesting}
                      title="Verbindung testen"
                    >
                      {isTesting ? (
                        <span className="w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin" />
                      ) : (
                        <Wifi className="w-4 h-4 text-blue-500" />
                      )}
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => openEditModal(config)}>
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDelete(config.id, config.name)}
                    >
                      <Trash2 className="w-4 h-4 text-red-500" />
                    </Button>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      )}

      {/* Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-semibold">
                  {editingId ? 'Provider bearbeiten' : 'Neuer Provider'}
                </h2>
                <button onClick={closeModal} className="text-gray-400 hover:text-gray-600">
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Mutation Fehler anzeigen */}
              {(createMutation.error || updateMutation.error) && (
                <div className="mb-4 p-3 rounded-lg bg-red-50 text-red-800 text-sm">
                  <div className="flex items-start gap-2">
                    <X className="w-4 h-4 flex-shrink-0 mt-0.5" />
                    <span>
                      {createMutation.error instanceof Error
                        ? createMutation.error.message
                        : updateMutation.error instanceof Error
                          ? updateMutation.error.message
                          : 'Fehler beim Speichern'}
                    </span>
                  </div>
                </div>
              )}

              <form onSubmit={handleSubmit} className="space-y-4">
                <Input
                  label="Name *"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="z.B. Plesk Hauptserver"
                  required
                />

                <Select
                  label="Provider-Typ *"
                  value={formData.type}
                  onChange={(e) => setFormData({ ...formData, type: e.target.value as 'PLESK' | 'CPANEL' | 'DIRECTADMIN' })}
                  options={PROVIDER_TYPES}
                />

                <Input
                  label="API-URL *"
                  value={formData.apiUrl}
                  onChange={(e) => setFormData({ ...formData, apiUrl: e.target.value })}
                  placeholder="https://server.de:8443"
                  required
                />

                <Input
                  label="API-Key"
                  value={formData.apiKey}
                  onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
                  placeholder="Optional - alternativ zu Benutzername/Passwort"
                />

                <div className="grid grid-cols-2 gap-4">
                  <Input
                    label="Benutzername"
                    value={formData.username}
                    onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                    placeholder="admin"
                  />
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      {editingId ? 'Neues Passwort (leer = beibehalten)' : 'Passwort'}
                    </label>
                    <div className="relative">
                      <input
                        type={showPassword ? 'text' : 'password'}
                        value={formData.password}
                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                        className="block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600"
                      >
                        {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                </div>

                <div>
                  <Input
                    label="Domain *"
                    value={formData.domain}
                    onChange={(e) =>
                      setFormData({ ...formData, domain: e.target.value.toLowerCase().trim() })
                    }
                    placeholder="stressfrei-wechseln.de"
                    required
                    pattern="^[a-z0-9]([a-z0-9\-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]*[a-z0-9])?)+$"
                    title="Gültige Domain erforderlich, z.B. meine-firma.de oder mail.beispiel.com"
                  />
                  {formData.domain &&
                    !/^[a-z0-9]([a-z0-9\-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]*[a-z0-9])?)+$/.test(
                      formData.domain,
                    ) && (
                      <p className="text-xs text-red-600 mt-1">
                        Keine gültige Domain – Format: name.tld (z.B. meine-firma.de)
                      </p>
                    )}
                </div>

                <p className="text-xs text-gray-500 -mt-2">
                  Wird auch für die Kunden-E-Mail-Adressen genutzt (z.B. <code>name@{formData.domain || 'meine-domain.de'}</code>)
                  und als Bezeichnung im UI angezeigt ("{formData.domain ? formData.domain.split('.')[0].split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('-') : 'Meine-Domain'}").
                </p>

                <div>
                  <Input
                    label="Bezeichnung im UI (optional)"
                    value={formData.customerEmailLabel}
                    onChange={(e) => setFormData({ ...formData, customerEmailLabel: e.target.value })}
                    placeholder={formData.domain ? formData.domain.split('.')[0].split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('-') : 'aus Domain ableiten'}
                    maxLength={60}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    Überschreibt die aus der Domain abgeleitete Bezeichnung – z.B.
                    "interne Kunden Email Adressen". Leer lassen für Auto-Ableitung.
                  </p>
                </div>

                <Input
                  label="Standard-Weiterleitungsadresse"
                  value={formData.defaultForwardEmail}
                  onChange={(e) => setFormData({ ...formData, defaultForwardEmail: e.target.value })}
                  placeholder="info@meinefirma.de"
                  type="email"
                />
                <p className="text-xs text-gray-500 -mt-2">
                  Diese E-Mail-Adresse wird zusätzlich zur Kunden-E-Mail als Weiterleitungsziel hinzugefügt.
                </p>

                {/* Verschlüsselungs-Einstellungen */}
                <div className="pt-4 border-t">
                  <h4 className="text-sm font-medium text-gray-700 mb-3">E-Mail-Verbindungseinstellungen</h4>
                  <div className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      {/* IMAP Verschlüsselung */}
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          IMAP Verschlüsselung
                          <span className="text-gray-400 font-normal ml-1">
                            (Port {formData.imapEncryption === 'SSL' ? '993' : '143'})
                          </span>
                        </label>
                        <select
                          value={formData.imapEncryption}
                          onChange={(e) => setFormData({ ...formData, imapEncryption: e.target.value as MailEncryption })}
                          className="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm"
                        >
                          {ENCRYPTION_OPTIONS.map((opt) => (
                            <option key={opt.value} value={opt.value}>
                              {opt.label} - {opt.description}
                            </option>
                          ))}
                        </select>
                      </div>

                      {/* SMTP Verschlüsselung */}
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          SMTP Verschlüsselung
                          <span className="text-gray-400 font-normal ml-1">
                            (Port {formData.smtpEncryption === 'SSL' ? '465' : formData.smtpEncryption === 'STARTTLS' ? '587' : '25'})
                          </span>
                        </label>
                        <select
                          value={formData.smtpEncryption}
                          onChange={(e) => setFormData({ ...formData, smtpEncryption: e.target.value as MailEncryption })}
                          className="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm"
                        >
                          {ENCRYPTION_OPTIONS.map((opt) => (
                            <option key={opt.value} value={opt.value}>
                              {opt.label} - {opt.description}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>

                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.allowSelfSignedCerts}
                        onChange={(e) => setFormData({ ...formData, allowSelfSignedCerts: e.target.checked })}
                        className="rounded border-gray-300"
                      />
                      <span className="text-sm">Selbstsignierte Zertifikate erlauben</span>
                    </label>
                    <p className="text-xs text-gray-500">
                      Aktivieren Sie diese Option für Testumgebungen mit selbstsignierten SSL-Zertifikaten.
                    </p>
                  </div>
                </div>

                {/* System-E-Mail */}
                <div className="pt-4 border-t">
                  <div className="flex items-center gap-2 mb-3">
                    <Mail className="w-4 h-4 text-gray-500" />
                    <h4 className="text-sm font-medium text-gray-700">System-E-Mail für automatischen Versand</h4>
                  </div>
                  <p className="text-xs text-gray-500 mb-3">
                    Diese E-Mail-Adresse wird für automatisierte Nachrichten verwendet (z.B. DSGVO Consent-Links). Der Kunden-E-Mail-Client wird davon nicht beeinflusst.
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    <Input
                      label="System-E-Mail-Adresse"
                      value={formData.systemEmailAddress}
                      onChange={(e) => setFormData({ ...formData, systemEmailAddress: e.target.value })}
                      placeholder="info@stressfrei-wechseln.de"
                      type="email"
                    />
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        {editingId ? 'Neues Passwort (leer = beibehalten)' : 'Passwort'}
                      </label>
                      <div className="relative">
                        <input
                          type={showSystemPassword ? 'text' : 'password'}
                          value={formData.systemEmailPassword}
                          onChange={(e) => setFormData({ ...formData, systemEmailPassword: e.target.value })}
                          className="block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        />
                        <button
                          type="button"
                          onClick={() => setShowSystemPassword(!showSystemPassword)}
                          className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600"
                        >
                          {showSystemPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex gap-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.isActive}
                      onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm">Aktiv</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.isDefault}
                      onChange={(e) => setFormData({ ...formData, isDefault: e.target.checked })}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm">Als Standard verwenden</span>
                  </label>
                </div>

                {/* Verbindungstest im Modal */}
                <div className="pt-4 border-t">
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={handleTestInModal}
                    disabled={isTestingInModal}
                    className="w-full"
                  >
                    {isTestingInModal ? (
                      'Teste Verbindung...'
                    ) : (
                      <>
                        <Wifi className="w-4 h-4 mr-2" />
                        Verbindung testen
                      </>
                    )}
                  </Button>
                  {modalTestResult && (
                    <div className={`mt-2 p-3 rounded-lg text-sm ${modalTestResult.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
                      {modalTestResult.success ? (
                        <div className="flex items-center gap-2">
                          <Check className="w-4 h-4 flex-shrink-0" />
                          <span>Verbindung erfolgreich!</span>
                        </div>
                      ) : (
                        <div className="flex items-start gap-2">
                          <WifiOff className="w-4 h-4 flex-shrink-0 mt-0.5" />
                          <span>{formatErrorMessage(modalTestResult)}</span>
                        </div>
                      )}
                    </div>
                  )}

                  {/* E-Mail-Zugang testen (IMAP + SMTP) */}
                  <div className="mt-4">
                    <p className="text-xs text-gray-500 mb-2">
                      Testet den tatsächlichen E-Mail-Zugang (IMAP-Empfang und SMTP-Versand) der System-E-Mail.
                    </p>
                    <Button
                      type="button"
                      variant="secondary"
                      onClick={handleTestMailAccess}
                      disabled={isTestingMailAccess || !formData.systemEmailAddress}
                      className="w-full"
                    >
                      {isTestingMailAccess ? (
                        'Teste IMAP + SMTP...'
                      ) : (
                        <>
                          <Mail className="w-4 h-4 mr-2" />
                          E-Mail-Zugang testen (IMAP + SMTP)
                        </>
                      )}
                    </Button>

                    {mailAccessResult && (
                      <div className="mt-2 space-y-2">
                        {/* IMAP-Ergebnis */}
                        <div className={`p-3 rounded-lg text-sm ${mailAccessResult.imap.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
                          {mailAccessResult.imap.success ? (
                            <div className="flex items-center gap-2">
                              <Check className="w-4 h-4 flex-shrink-0" />
                              <span>
                                <strong>IMAP</strong> erfolgreich ({mailAccessResult.imap.server}:{mailAccessResult.imap.port}, {mailAccessResult.imap.encryption})
                              </span>
                            </div>
                          ) : (
                            <div className="flex items-start gap-2">
                              <WifiOff className="w-4 h-4 flex-shrink-0 mt-0.5" />
                              <div>
                                <strong>IMAP</strong> fehlgeschlagen
                                {mailAccessResult.imap.server && (
                                  <span className="text-xs opacity-75">
                                    {' '}({mailAccessResult.imap.server}:{mailAccessResult.imap.port}
                                    {mailAccessResult.imap.encryption ? `, ${mailAccessResult.imap.encryption}` : ''})
                                  </span>
                                )}
                                {mailAccessResult.imap.error && (
                                  <div className="mt-1 text-xs">{mailAccessResult.imap.error}</div>
                                )}
                              </div>
                            </div>
                          )}
                        </div>

                        {/* SMTP-Ergebnis */}
                        <div className={`p-3 rounded-lg text-sm ${mailAccessResult.smtp.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
                          {mailAccessResult.smtp.success ? (
                            <div className="flex items-center gap-2">
                              <Check className="w-4 h-4 flex-shrink-0" />
                              <span>
                                <strong>SMTP</strong> erfolgreich ({mailAccessResult.smtp.server}:{mailAccessResult.smtp.port}, {mailAccessResult.smtp.encryption})
                              </span>
                            </div>
                          ) : (
                            <div className="flex items-start gap-2">
                              <WifiOff className="w-4 h-4 flex-shrink-0 mt-0.5" />
                              <div>
                                <strong>SMTP</strong> fehlgeschlagen
                                {mailAccessResult.smtp.server && (
                                  <span className="text-xs opacity-75">
                                    {' '}({mailAccessResult.smtp.server}:{mailAccessResult.smtp.port}
                                    {mailAccessResult.smtp.encryption ? `, ${mailAccessResult.smtp.encryption}` : ''})
                                  </span>
                                )}
                                {mailAccessResult.smtp.error && (
                                  <div className="mt-1 text-xs">{mailAccessResult.smtp.error}</div>
                                )}
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                <div className="flex justify-end gap-3 pt-4 border-t">
                  <Button type="button" variant="secondary" onClick={closeModal}>
                    Abbrechen
                  </Button>
                  <Button
                    type="submit"
                    disabled={createMutation.isPending || updateMutation.isPending}
                  >
                    {(createMutation.isPending || updateMutation.isPending) ? 'Speichern...' : 'Speichern'}
                  </Button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
