/**
 * Mail settings page — signatures, rules, labels, PGP, vacation responder.
 */

import React, { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { useToast } from '@/components/ui/Toast';
import { Tabs } from '@/components/shared/Tabs';
import { SignatureManager } from '@/components/mail/SignatureManager';
import { RuleEditor } from '@/components/mail/RuleEditor';
import { LabelManager } from '@/components/mail/LabelManager';
import { VacationResponder } from '@/components/mail/VacationResponder';
import { PgpSettings } from '@/components/mail/PgpSettings';
import {
  fetchAccounts,
  createAccount,
  deleteAccount,
  testConnection,
  triggerSync,
  updateAccount,
  fetchFolders,
  type MailAccount,
  type MailFolder,
  type CreateAccountPayload,
} from '@/api/mail';

export function MailSettingsPage() {
  const { t } = useTranslation();
  const toast = useToast();
  const [searchParams, setSearchParams] = useSearchParams();
  const [accounts, setAccounts] = useState<MailAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedAccountId, setSelectedAccountId] = useState('');
  const [showAddAccount, setShowAddAccount] = useState(false);
  const [newAccount, setNewAccount] = useState<CreateAccountPayload>({
    email: '',
    display_name: '',
    imap_host: '',
    imap_port: 993,
    smtp_host: '',
    smtp_port: 587,
    username: '',
    password: '',
    is_shared: false,
  });
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState<string | null>(null);
  const [syncing, setSyncing] = useState<string | null>(null);
  const [editingDisplayName, setEditingDisplayName] = useState<string | null>(null);
  const [displayNameValue, setDisplayNameValue] = useState('');
  const [accountFolders, setAccountFolders] = useState<Record<string, MailFolder[]>>({});
  const [folderMappingEdit, setFolderMappingEdit] = useState<string | null>(null);
  const [folderMappingValues, setFolderMappingValues] = useState<Record<string, string>>({});
  const [savingMapping, setSavingMapping] = useState(false);

  const loadAccounts = useCallback(async () => {
    setLoading(true);
    try {
      const accs = await fetchAccounts();
      setAccounts(accs);
      if (accs.length > 0) {
        setSelectedAccountId((prev) => prev || accs[0].id);
      }
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Failed to load accounts');
    }
    setLoading(false);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => { loadAccounts(); }, [loadAccounts]);

  const handleCreateAccount = useCallback(async () => {
    if (!newAccount.email.trim() || !newAccount.password.trim()) return;
    setSaving(true);
    try {
      const acc = await createAccount(newAccount);
      setAccounts((prev) => [...prev, acc]);
      toast.success(t('mail.accountCreated'));
      setShowAddAccount(false);
      setNewAccount({
        email: '',
        display_name: '',
        imap_host: '',
        imap_port: 993,
        smtp_host: '',
        smtp_port: 587,
        username: '',
        password: '',
        is_shared: false,
      });
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Save failed');
    } finally {
      setSaving(false);
    }
  }, [newAccount, toast, t]);

  const handleTestConnection = useCallback(async (accountId: string) => {
    setTesting(accountId);
    try {
      const result = await testConnection(accountId);
      if (result.success) {
        toast.success(t('mail.connectionSuccess'));
      } else {
        toast.error(result.message);
      }
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Connection test failed');
    } finally {
      setTesting(null);
    }
  }, [toast, t]);

  const handleSync = useCallback(async (accountId: string) => {
    setSyncing(accountId);
    try {
      const result = await triggerSync(accountId);
      if ((result as any)?.error) {
        toast.error((result as any).error);
      } else {
        toast.success(t('mail.syncSuccess'));
      }
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Sync failed');
    } finally {
      setSyncing(null);
    }
  }, [toast, t]);

  const handleDeleteAccount = useCallback(async (accountId: string) => {
    if (!window.confirm(t('mail.confirmDeleteAccount'))) return;
    try {
      await deleteAccount(accountId);
      setAccounts((prev) => prev.filter((a) => a.id !== accountId));
      toast.success(t('mail.accountDeleted'));
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Delete failed');
    }
  }, [toast, t]);

  const handleSaveDisplayName = useCallback(async (accountId: string) => {
    try {
      const updated = await updateAccount(accountId, { display_name: displayNameValue });
      setAccounts((prev) => prev.map((a) => (a.id === accountId ? updated : a)));
      setEditingDisplayName(null);
      toast.success(t('common.saved'));
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Save failed');
    }
  }, [displayNameValue, toast, t]);

  const handleStartEditDisplayName = useCallback((acc: MailAccount) => {
    setEditingDisplayName(acc.id);
    setDisplayNameValue(acc.display_name || '');
  }, []);

  const loadAccountFolders = useCallback(async (accountId: string) => {
    try {
      const folders = await fetchFolders(accountId);
      setAccountFolders((prev) => ({ ...prev, [accountId]: folders }));
    } catch {
      // non-critical
    }
  }, []);

  const handleStartFolderMapping = useCallback((acc: MailAccount) => {
    setFolderMappingEdit(acc.id);
    setFolderMappingValues({
      sent: acc.sent_folder_imap_name || '',
      drafts: acc.drafts_folder_imap_name || '',
      spam: acc.spam_folder_imap_name || '',
      trash: acc.trash_folder_imap_name || '',
    });
    if (!accountFolders[acc.id]) {
      loadAccountFolders(acc.id);
    }
  }, [accountFolders, loadAccountFolders]);

  const handleSaveFolderMapping = useCallback(async (accountId: string) => {
    setSavingMapping(true);
    try {
      const payload: Record<string, string | null> = {};
      payload.sent_folder_imap_name = folderMappingValues.sent || null;
      payload.drafts_folder_imap_name = folderMappingValues.drafts || null;
      payload.spam_folder_imap_name = folderMappingValues.spam || null;
      payload.trash_folder_imap_name = folderMappingValues.trash || null;
      const updated = await updateAccount(accountId, payload);
      setAccounts((prev) => prev.map((a) => (a.id === accountId ? updated : a)));
      setFolderMappingEdit(null);
      toast.success(t('common.saved'));
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Save failed');
    } finally {
      setSavingMapping(false);
    }
  }, [folderMappingValues, toast, t]);

  const activeTab = searchParams.get('tab') || 'accounts';

  const tabs = [
    {
      key: 'accounts',
      label: t('mail.tabAccounts'),
      content: (
        <div className="space-y-4" data-testid="tab-accounts">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-secondary-900">{t('mail.accounts')}</h3>
            <Button size="sm" onClick={() => setShowAddAccount(!showAddAccount)} data-testid="add-account-btn">
              {t('mail.addAccount')}
            </Button>
          </div>

          {showAddAccount && (
            <Card className="mb-4" data-testid="add-account-form">
              <div className="space-y-3">
                <Input
                  label={t('mail.email')}
                  value={newAccount.email}
                  onChange={(e) => setNewAccount((prev) => ({ ...prev, email: e.target.value }))}
                  placeholder="user@example.com"
                  required
                />
                <Input
                  label={t('mail.displayName')}
                  value={newAccount.display_name}
                  onChange={(e) => setNewAccount((prev) => ({ ...prev, display_name: e.target.value }))}
                  placeholder="John Doe"
                />
                <Input
                  label="Benutzername (IMAP/SMTP)"
                  value={newAccount.username}
                  onChange={(e) => setNewAccount((prev) => ({ ...prev, username: e.target.value }))}
                  placeholder="Leer lassen für E-Mail-Adresse"
                />
                <div className="grid grid-cols-2 gap-3">
                  <Input
                    label={t('mail.imapHost')}
                    value={newAccount.imap_host}
                    onChange={(e) => setNewAccount((prev) => ({ ...prev, imap_host: e.target.value }))}
                    placeholder="imap.example.com"
                  />
                  <Input
                    label={t('mail.imapPort')}
                    type="number"
                    value={String(newAccount.imap_port)}
                    onChange={(e) => setNewAccount((prev) => ({ ...prev, imap_port: Number(e.target.value) }))}
                  />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <Input
                    label={t('mail.smtpHost')}
                    value={newAccount.smtp_host}
                    onChange={(e) => setNewAccount((prev) => ({ ...prev, smtp_host: e.target.value }))}
                    placeholder="smtp.example.com"
                  />
                  <Input
                    label={t('mail.smtpPort')}
                    type="number"
                    value={String(newAccount.smtp_port)}
                    onChange={(e) => setNewAccount((prev) => ({ ...prev, smtp_port: Number(e.target.value) }))}
                  />
                </div>
                <Input
                  label={t('mail.password')}
                  type="password"
                  value={newAccount.password}
                  onChange={(e) => setNewAccount((prev) => ({ ...prev, password: e.target.value }))}
                  required
                />
                <label className="flex items-center gap-2 text-sm text-secondary-700">
                  <input
                    type="checkbox"
                    checked={newAccount.is_shared || false}
                    onChange={(e) => setNewAccount((prev) => ({ ...prev, is_shared: e.target.checked }))}
                    className="rounded"
                  />
                  Geteiltes Postfach (für alle Tenant-Benutzer sichtbar)
                </label>
                <div className="flex gap-2">
                  <Button onClick={handleCreateAccount} isLoading={saving} size="sm">{t('common.save')}</Button>
                  <Button variant="secondary" size="sm" onClick={() => setShowAddAccount(false)}>{t('common.cancel')}</Button>
                </div>
              </div>
            </Card>
          )}

          {loading ? (
            <div className="flex items-center justify-center py-8">
              <svg className="animate-spin h-5 w-5 text-secondary-400" fill="none" viewBox="0 0 24 24" aria-hidden="true">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
            </div>
          ) : accounts.length === 0 ? (
            <p className="text-sm text-secondary-500">{t('mail.noAccounts')}</p>
          ) : (
            <div className="space-y-2" data-testid="account-list">
              {accounts.map((acc) => (
                <Card key={acc.id}>
                  <div className="flex items-center justify-between">
                    <div className="min-w-0 flex-1">
                      {editingDisplayName === acc.id ? (
                        <div className="flex items-center gap-2">
                          <Input
                            value={displayNameValue}
                            onChange={(e) => setDisplayNameValue(e.target.value)}
                            placeholder={acc.email}
                            className="flex-1"
                          />
                          <Button size="sm" onClick={() => handleSaveDisplayName(acc.id)}>{t('common.save')}</Button>
                          <Button variant="secondary" size="sm" onClick={() => setEditingDisplayName(null)}>{t('common.cancel')}</Button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2">
                          <p className="font-medium text-secondary-900">{acc.display_name || acc.email}</p>
                          <button
                            onClick={() => handleStartEditDisplayName(acc)}
                            className="text-xs text-secondary-400 hover:text-secondary-600"
                            aria-label={t('common.edit')}
                            data-testid={`edit-display-name-${acc.id}`}
                          >
                            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                            </svg>
                          </button>
                        </div>
                      )}
                      <p className="text-sm text-secondary-500 truncate">{acc.email}</p>
                      <p className="text-xs text-secondary-400 mt-1">
                        {t('mail.serverInfo')}: {acc.imap_host}:{acc.imap_port} / {acc.smtp_host}:{acc.smtp_port}
                      </p>
                      <p className="text-xs text-secondary-400">
                        {acc.is_shared ? t('mail.shared') : t('mail.personal')} ·
                        {acc.is_active ? t('common.active') : t('common.inactive')}
                      </p>
                    </div>
                    <div className="flex gap-2 flex-shrink-0">
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => handleTestConnection(acc.id)}
                        isLoading={testing === acc.id}
                        data-testid={`test-conn-${acc.id}`}
                      >
                        {t('mail.testConnection')}
                      </Button>
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => handleSync(acc.id)}
                        isLoading={syncing === acc.id}
                        data-testid={`sync-${acc.id}`}
                      >
                        {t('mail.syncNow')}
                      </Button>
                      <Button
                        variant="danger"
                        size="sm"
                        onClick={() => handleDeleteAccount(acc.id)}
                        data-testid={`delete-account-${acc.id}`}
                      >
                        {t('mail.deleteAccount')}
                      </Button>
                    </div>
                  </div>
                  {/* Folder mapping section */}
                  {folderMappingEdit === acc.id ? (
                    <div className="mt-3 pt-3 border-t border-secondary-200 space-y-2" data-testid={`folder-mapping-${acc.id}`}>
                      <p className="text-xs font-medium text-secondary-600">Ordner-Zuordnung</p>
                      {(['sent', 'drafts', 'spam', 'trash'] as const).map((type) => (
                        <div key={type} className="flex items-center gap-2">
                          <label className="text-xs text-secondary-500 w-20">
                            {type === 'sent' ? 'Gesendet' : type === 'drafts' ? 'Entwürfe' : type === 'spam' ? 'Spam' : 'Papierkorb'}
                          </label>
                          <select
                            value={folderMappingValues[type] || ''}
                            onChange={(e) => setFolderMappingValues((prev) => ({ ...prev, [type]: e.target.value }))}
                            className="text-xs rounded border border-secondary-300 bg-white px-1.5 py-0.5 text-secondary-700 focus:outline-none focus:ring-1 focus:ring-primary-500 flex-1"
                          >
                            <option value="">(automatisch)</option>
                            {(accountFolders[acc.id] || []).map((f) => (
                              <option key={f.id} value={f.imap_name}>{f.imap_name}</option>
                            ))}
                          </select>
                        </div>
                      ))}
                      <div className="flex gap-2 mt-2">
                        <Button size="sm" onClick={() => handleSaveFolderMapping(acc.id)} isLoading={savingMapping}>{t('common.save')}</Button>
                        <Button variant="secondary" size="sm" onClick={() => setFolderMappingEdit(null)}>{t('common.cancel')}</Button>
                      </div>
                    </div>
                  ) : (
                    <div className="mt-2">
                      <button
                        onClick={() => handleStartFolderMapping(acc)}
                        className="text-xs text-secondary-400 hover:text-secondary-600"
                        data-testid={`folder-mapping-btn-${acc.id}`}
                      >
                        Ordner-Zuordnung bearbeiten
                      </button>
                    </div>
                  )}
                </Card>
              ))}
            </div>
          )}
        </div>
      ),
    },
    {
      key: 'signatures',
      label: t('mail.tabSignatures'),
      content: <SignatureManager />,
    },
    {
      key: 'rules',
      label: t('mail.tabRules'),
      content: selectedAccountId ? <RuleEditor accountId={selectedAccountId} /> : (
        <p className="text-sm text-secondary-500">{t('mail.selectAccountFirst')}</p>
      ),
    },
    {
      key: 'labels',
      label: t('mail.tabLabels'),
      content: <LabelManager />,
    },
    {
      key: 'vacation',
      label: t('mail.tabVacation'),
      content: <VacationResponder accountId={selectedAccountId} />,
    },
    {
      key: 'pgp',
      label: t('mail.tabPgp'),
      content: <PgpSettings />,
    },
  ];

  return (
    <div className="p-6 max-w-5xl mx-auto" data-testid="mail-settings-page">
      <h1 className="text-2xl font-bold text-secondary-900 mb-6">{t('mail.settings')}</h1>
      <Tabs tabs={tabs} defaultKey={activeTab} />
    </div>
  );
}