import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MemoryRouter } from 'react-router-dom';
import EmailSettings from '../EmailSettings';
import * as ticketEmailHooks from '../../../hooks/useTicketEmailAddresses';

// Mock react-i18next
vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, defaultValue?: string) => defaultValue || key,
  }),
}));

// Mock react-router-dom hooks
const mockOutletContext = vi.fn();

vi.mock('react-router-dom', async () => {
  const actual = await vi.importActual('react-router-dom');
  return {
    ...actual,
    useOutletContext: () => mockOutletContext(),
  };
});

// Mock TicketEmailAddressManager component
vi.mock('../../../components/TicketEmailAddressManager', () => ({
  default: () => <div data-testid="ticket-email-manager">Ticket Email Manager</div>,
}));

// Mock the ticket email hooks
vi.mock('../../../hooks/useTicketEmailAddresses', () => ({
  useTicketEmailAddresses: vi.fn(),
  useDeleteTicketEmailAddress: vi.fn(),
  useTestImapConnection: vi.fn(),
  useTestSmtpConnection: vi.fn(),
  useFetchEmailsNow: vi.fn(),
  useSetAsDefault: vi.fn(),
}));

describe('EmailSettings', () => {
  let queryClient: QueryClient;

  const ownerContext = {
    user: { id: '1', role: 'owner', email: 'owner@test.com' },
    business: {
      id: '1',
      name: 'Test Business',
      subdomain: 'test-business',
    },
  };

  const staffContext = {
    ...ownerContext,
    user: { id: '2', role: 'staff', email: 'staff@test.com' },
  };

  beforeEach(() => {
    vi.clearAllMocks();
    queryClient = new QueryClient({
      defaultOptions: {
        queries: { retry: false },
        mutations: { retry: false },
      },
    });

    // Default mock implementations
    vi.mocked(ticketEmailHooks.useTicketEmailAddresses).mockReturnValue({
      data: [],
      isLoading: false,
    } as any);

    vi.mocked(ticketEmailHooks.useDeleteTicketEmailAddress).mockReturnValue({
      mutateAsync: vi.fn(),
      isPending: false,
    } as any);

    vi.mocked(ticketEmailHooks.useTestImapConnection).mockReturnValue({
      mutateAsync: vi.fn(),
      isPending: false,
    } as any);

    vi.mocked(ticketEmailHooks.useTestSmtpConnection).mockReturnValue({
      mutateAsync: vi.fn(),
      isPending: false,
    } as any);

    vi.mocked(ticketEmailHooks.useFetchEmailsNow).mockReturnValue({
      mutateAsync: vi.fn(),
      isPending: false,
    } as any);

    vi.mocked(ticketEmailHooks.useSetAsDefault).mockReturnValue({
      mutateAsync: vi.fn(),
      isPending: false,
    } as any);
  });

  const renderWithProviders = (component: React.ReactElement) => {
    return render(
      <QueryClientProvider client={queryClient}>
        <MemoryRouter>
          {component}
        </MemoryRouter>
      </QueryClientProvider>
    );
  };

  it('renders the title for owner', () => {
    mockOutletContext.mockReturnValue(ownerContext);
    renderWithProviders(<EmailSettings />);
    expect(screen.getByText('Email Setup')).toBeInTheDocument();
  });

  it('renders the subtitle for owner', () => {
    mockOutletContext.mockReturnValue(ownerContext);
    renderWithProviders(<EmailSettings />);
    expect(screen.getByText('Configure email addresses for your ticketing system and customer communication.')).toBeInTheDocument();
  });

  it('shows owner only message for non-owner', () => {
    mockOutletContext.mockReturnValue(staffContext);
    renderWithProviders(<EmailSettings />);
    expect(screen.getByText('Only the business owner can access these settings.')).toBeInTheDocument();
  });

  it('does not render email manager for non-owner', () => {
    mockOutletContext.mockReturnValue(staffContext);
    renderWithProviders(<EmailSettings />);
    expect(screen.queryByTestId('ticket-email-manager')).not.toBeInTheDocument();
  });

  it('renders TicketEmailAddressManager for owner', () => {
    mockOutletContext.mockReturnValue(ownerContext);
    renderWithProviders(<EmailSettings />);
    expect(screen.getByTestId('ticket-email-manager')).toBeInTheDocument();
  });

  it('displays Mail icon in header', () => {
    mockOutletContext.mockReturnValue(ownerContext);
    const { container } = renderWithProviders(<EmailSettings />);
    // Check for Mail icon (Lucide icons render as SVG)
    const mailIcon = container.querySelector('svg');
    expect(mailIcon).toBeInTheDocument();
  });

  it('has proper layout structure', () => {
    mockOutletContext.mockReturnValue(ownerContext);
    const { container } = renderWithProviders(<EmailSettings />);
    const spaceYContainer = container.querySelector('.space-y-6');
    expect(spaceYContainer).toBeInTheDocument();
  });
});
