/**
 * 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 { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
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 { Loader2, Pencil } from 'lucide-react';
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);

  // ── Account create form (RHF + Zod) ──
  const accountSchema = z.object({
    email: z.string().min(1, 'required').email('invalidEmail'),
    display_name: z.string().optional().default(''),
    username: z.string().optional().default(''),
    imap_host: z.string().min(1, 'required'),
    imap_port: z.coerce.number().int().min(1, 'invalidNumber').max(65535, 'invalidNumber').default(993),
    smtp_host: z.string().min(1, 'required'),
    smtp_port: z.coerce.number().int().min(1, 'invalidNumber').max(65535, 'invalidNumber').default(587),
    password: z.string().min(1, 'required'),
    is_shared: z.boolean().default(false),
  });
  type AccountFormData = z.infer<typeof accountSchema>;

  const { register: registerAccount, handleSubmit: handleSubmitAccount, reset: resetAccount, formState: { errors: accountErrors, isSubmitting: accountSubmitting } } = useForm<AccountFormData>({
    resolver: zodResolver(accountSchema),
    defaultValues: { email: '', display_name: '', username: '', imap_host: '', imap_port: 993, smtp_host: '', smtp_port: 587, 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 (data: AccountFormData) => {
    try {
      const acc = await createAccount(data);
      setAccounts((prev) => [...prev, acc]);
      toast.success(t('mail.accountCreated'));
      setShowAddAccount(false);
      resetAccount({ email: '', display_name: '', username: '', imap_host: '', imap_port: 993, smtp_host: '', smtp_port: 587, password: '', is_shared: false });
    } catch (err: any) {
      toast.error(err?.message || err?.detail || 'Save failed');
    }
  }, [toast, t, resetAccount]);

  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">
              <form onSubmit={handleSubmitAccount(handleCreateAccount)} className="space-y-3">
                <Input
                  label={t('mail.email')}
                  {...registerAccount('email')}
                  error={accountErrors.email?.message === 'required' ? t('validation.required') : accountErrors.email?.message === 'invalidEmail' ? t('validation.email') : undefined}
                  placeholder="user@example.com"
                  required
                />
                <Input
                  label={t('mail.displayName')}
                  {...registerAccount('display_name')}
                  placeholder="John Doe"
                />
                <Input
                  label="Benutzername (IMAP/SMTP)"
                  {...registerAccount('username')}
                  placeholder="Leer lassen für E-Mail-Adresse"
                />
                <div className="grid grid-cols-2 gap-3">
                  <Input
                    label={t('mail.imapHost')}
                    {...registerAccount('imap_host')}
                    error={accountErrors.imap_host?.message === 'required' ? t('validation.required') : undefined}
                    placeholder="imap.example.com"
                  />
                  <Input
                    label={t('mail.imapPort')}
                    type="number"
                    {...registerAccount('imap_port')}
                    error={accountErrors.imap_port?.message === 'invalidNumber' ? t('validation.invalidNumber', 'Invalid number') : undefined}
                  />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <Input
                    label={t('mail.smtpHost')}
                    {...registerAccount('smtp_host')}
                    error={accountErrors.smtp_host?.message === 'required' ? t('validation.required') : undefined}
                    placeholder="smtp.example.com"
                  />
                  <Input
                    label={t('mail.smtpPort')}
                    type="number"
                    {...registerAccount('smtp_port')}
                    error={accountErrors.smtp_port?.message === 'invalidNumber' ? t('validation.invalidNumber', 'Invalid number') : undefined}
                  />
                </div>
                <Input
                  label={t('mail.password')}
                  type="password"
                  {...registerAccount('password')}
                  error={accountErrors.password?.message === 'required' ? t('validation.required') : undefined}
                  required
                />
                <label className="flex items-center gap-2 text-sm text-secondary-700">
                  <input
                    type="checkbox"
                    {...registerAccount('is_shared')}
                    className="rounded"
                  />
                  Geteiltes Postfach (für alle Tenant-Benutzer sichtbar)
                </label>
                <div className="flex gap-2">
                  <Button type="submit" isLoading={accountSubmitting} size="sm">{t('common.save')}</Button>
                  <Button variant="secondary" size="sm" type="button" onClick={() => setShowAddAccount(false)}>{t('common.cancel')}</Button>
                </div>
              </form>
            </Card>
          )}

          {loading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="animate-spin h-5 w-5 text-secondary-400" aria-hidden="true" />
            </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}`}
                          >
                            <Pencil className="w-3.5 h-3.5" aria-hidden="true" strokeWidth={2} />
                          </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>
  );
}