/**
 * 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,
  type MailAccount,
  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,
    password: '',
  });
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState<string | null>(null);
  const [syncing, setSyncing] = useState<string | null>(null);

  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,
        password: '',
      });
    } 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 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"
                />
                <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
                />
                <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">
                      <p className="font-medium text-secondary-900">{acc.display_name || acc.email}</p>
                      <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>
                </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>
  );
}