import React from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';

vi.mock('@/api/mail', () => ({
  fetchAccounts: vi.fn().mockResolvedValue([
    { id: 'acc1', email: 'test@example.com', display_name: 'Test User', is_shared: false, is_active: true, imap_host: '', imap_port: 993, smtp_host: '', smtp_port: 587 },
  ]),
  createAccount: vi.fn().mockResolvedValue({ id: 'acc2', email: 'new@example.com', display_name: 'New User', is_shared: false, is_active: true, imap_host: '', imap_port: 993, smtp_host: '', smtp_port: 587 }),
  testConnection: vi.fn().mockResolvedValue({ success: true, message: 'OK' }),
  triggerSync: vi.fn().mockResolvedValue({ success: true, synced_count: 5 }),
  fetchSignatures: vi.fn().mockResolvedValue([]),
  createSignature: vi.fn().mockResolvedValue({ id: 's1', name: 'Test', body_html: '<p>Test</p>', is_default: false }),
  updateSignature: vi.fn().mockResolvedValue({ id: 's1', name: 'Test', body_html: '<p>Test</p>', is_default: false }),
  deleteSignature: vi.fn().mockResolvedValue(undefined),
  fetchRules: vi.fn().mockResolvedValue([]),
  createRule: vi.fn().mockResolvedValue({ id: 'r1', name: 'Rule 1', account_id: 'acc1', priority: 1, is_active: true, conditions: [], actions: [] }),
  deleteRule: vi.fn().mockResolvedValue(undefined),
  fetchLabels: vi.fn().mockResolvedValue([]),
  createLabel: vi.fn().mockResolvedValue({ id: 'l1', name: 'Important', color: '#ef4444' }),
  deleteLabel: vi.fn().mockResolvedValue(undefined),
  configureVacation: vi.fn().mockResolvedValue({ success: true }),
  testVacationDedup: vi.fn().mockResolvedValue({ dedup_count: 0 }),
  importPgpKey: vi.fn().mockResolvedValue({ id: 'k1', key_id: 'ABC', fingerprint: 'DEF', user_id: 'test', is_private: true, expires_at: null }),
  fetchPgpKeys: vi.fn().mockResolvedValue([]),
  fetchContactPgpKeys: vi.fn().mockResolvedValue([]),
  storeContactPgpKey: vi.fn().mockResolvedValue(undefined),
  fetchTemplates: vi.fn().mockResolvedValue([]),
  substituteTemplate: vi.fn().mockResolvedValue({ subject: '', body: '' }),
}));

vi.mock('@/components/ui/Toast', () => ({
  useToast: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }),
}));

import { MailSettingsPage } from '@/pages/MailSettings';

function renderWithRouter() {
  return render(<MemoryRouter><MailSettingsPage /></MemoryRouter>);
}

beforeEach(() => {
  vi.clearAllMocks();
});

describe('MailSettingsPage', () => {
  it('renders settings page', async () => {
    renderWithRouter();
    expect(screen.getByTestId('mail-settings-page')).toBeInTheDocument();
  });

  it('renders accounts tab content', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('tab-accounts')).toBeInTheDocument();
    });
  });

  it('renders add account button', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('add-account-btn')).toBeInTheDocument();
    });
  });

  it('shows add account form when button is clicked', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('add-account-btn')).toBeInTheDocument();
    });
    fireEvent.click(screen.getByTestId('add-account-btn'));
    await waitFor(() => {
      expect(screen.getByTestId('add-account-form')).toBeInTheDocument();
    });
  });

  it('renders signature manager in signatures tab', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('mail-settings-page')).toBeInTheDocument();
    });
    // Click on signatures tab
    const sigTab = screen.getByRole('tab', { name: /Signaturen/i });
    fireEvent.click(sigTab);
    await waitFor(() => {
      expect(screen.getByTestId('signature-manager')).toBeInTheDocument();
    });
  });

  it('renders rule editor in rules tab', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('mail-settings-page')).toBeInTheDocument();
    });
    const rulesTab = screen.getByRole('tab', { name: /Regeln/i });
    fireEvent.click(rulesTab);
    await waitFor(() => {
      expect(screen.getByTestId('rule-editor')).toBeInTheDocument();
    });
  });

  it('renders label manager in labels tab', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('mail-settings-page')).toBeInTheDocument();
    });
    const labelsTab = screen.getByRole('tab', { name: /Labels/i });
    fireEvent.click(labelsTab);
    await waitFor(() => {
      expect(screen.getByTestId('label-manager')).toBeInTheDocument();
    });
  });

  it('renders vacation responder in vacation tab', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('mail-settings-page')).toBeInTheDocument();
    });
    const vacationTab = screen.getByRole('tab', { name: /Abwesenheit/i });
    fireEvent.click(vacationTab);
    await waitFor(() => {
      expect(screen.getByTestId('vacation-responder')).toBeInTheDocument();
    });
  });

  it('renders PGP settings in PGP tab', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('mail-settings-page')).toBeInTheDocument();
    });
    const pgpTab = screen.getByRole('tab', { name: /PGP/i });
    fireEvent.click(pgpTab);
    await waitFor(() => {
      expect(screen.getByTestId('pgp-settings')).toBeInTheDocument();
    });
  });

  it('renders account list with test connection button', async () => {
    renderWithRouter();
    await waitFor(() => {
      expect(screen.getByTestId('account-list')).toBeInTheDocument();
    });
    expect(screen.getByTestId('test-conn-acc1')).toBeInTheDocument();
  });
});
