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', () => ({
  decodeMimeHeader: (s: string) => s,
  fetchTemplates: vi.fn().mockResolvedValue([
    { id: 't1', name: 'Welcome', subject: 'Welcome!', body: '<p>Welcome {{name}}</p>', variables: ['name'] },
  ]),
  substituteTemplate: vi.fn().mockResolvedValue({ subject: 'Welcome!', body: '<p>Welcome John</p>' }),
}));

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

import { ComposeModal } from '@/components/mail/ComposeModal';

function renderModal(props: Partial<React.ComponentProps<typeof ComposeModal>> = {}) {
  const defaultProps = {
    open: true,
    mode: 'new' as const,
    accountId: 'acc1',
    replyToMail: null,
    forwardMail: null,
    signatures: [],
    onSend: vi.fn().mockResolvedValue(undefined),
    onClose: vi.fn(),
  };
  return render(<MemoryRouter><ComposeModal {...defaultProps} {...props} /></MemoryRouter>);
}

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

describe('ComposeModal', () => {
  it('renders compose modal when open', () => {
    renderModal();
    expect(screen.getByTestId('compose-modal')).toBeInTheDocument();
  });

  it('renders compose toolbar with bold button', () => {
    renderModal();
    expect(screen.getByTestId('compose-toolbar')).toBeInTheDocument();
  });

  it('renders recipient input field', () => {
    renderModal();
    expect(screen.getByTestId('compose-to')).toBeInTheDocument();
  });

  it('renders subject input field', () => {
    renderModal();
    expect(screen.getByTestId('compose-subject')).toBeInTheDocument();
  });

  it('renders editor', () => {
    renderModal();
    expect(screen.getByTestId('rich-text-editor-container')).toBeInTheDocument();
  });

  it('renders send button', () => {
    renderModal();
    expect(screen.getByTestId('compose-send')).toBeInTheDocument();
  });

  it('renders template picker toggle button', () => {
    renderModal();
    expect(screen.getByTestId('template-picker-toggle')).toBeInTheDocument();
  });

  it('shows template picker when template button is clicked', async () => {
    renderModal();
    fireEvent.click(screen.getByTestId('template-picker-toggle'));
    await waitFor(() => {
      expect(screen.getByTestId('template-picker')).toBeInTheDocument();
    });
  });

  it('pre-fills reply fields when mode is reply', async () => {
    renderModal({
      mode: 'reply',
      replyToMail: {
        id: 'm1', folder_id: 'f1', account_id: 'acc1', from_address: 'sender@example.com', from_name: 'Sender',
        to_addresses: ['test@example.com'], cc_addresses: [], bcc_addresses: [],
        subject: 'Original Subject', body_text: 'Original body', body_html: null, sanitized_html: null,
        date: '2026-01-01T10:00:00Z', is_seen: true, is_flagged: false, is_answered: false, has_attachments: false,
      } as any,
    });
    await waitFor(() => {
      const toInput = screen.getByTestId('compose-to');
      expect(toInput).toHaveValue('sender@example.com');
    });
  });

  it('pre-fills forward fields when mode is forward', async () => {
    renderModal({
      mode: 'forward',
      forwardMail: {
        id: 'm1', folder_id: 'f1', account_id: 'acc1', from_address: 'sender@example.com', from_name: 'Sender',
        to_addresses: ['test@example.com'], cc_addresses: [], bcc_addresses: [],
        subject: 'Original Subject', body_text: 'Original body', body_html: null, sanitized_html: null,
        date: '2026-01-01T10:00:00Z', is_seen: true, is_flagged: false, is_answered: false, has_attachments: false,
      } as any,
    });
    await waitFor(() => {
      const subjectInput = screen.getByTestId('compose-subject');
      expect(subjectInput).toHaveValue('Fwd: Original Subject');
    });
  });
});
