import React from 'react';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from 'styled-components';
import { MemoryRouter } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import '@testing-library/jest-dom';
import NotificationPreferencesPage from '@/features/notifications/pages/NotificationPreferencesPage';
import * as notificationService from '@/features/notifications/services/notificationService';
import type { NotificationPreference } from '@/features/notifications/types/notification.types';
import i18n from '@/locales/i18n';
import { LocaleProvider } from '@/app/providers/LocaleProvider';
import { lightTheme } from '@/styles/theme';

vi.mock('@/features/notifications/services/notificationService');

vi.mock('@/shared/components/layout/AppLayout', () => ({
  AppLayout: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

const mockPreferences: NotificationPreference[] = [
  {
    id: 'pref-1',
    notification_type: 'ticket_created',
    notification_type_label: 'Ticket Created',
    channels: { in_app: true, email: true, slack: false, sms: false },
    enabled_channels: ['in_app', 'email'],
  },
];

function renderPreferencesPage() {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
      mutations: { retry: false },
    },
  });

  return render(
    <QueryClientProvider client={queryClient}>
      <I18nextProvider i18n={i18n}>
        <LocaleProvider>
          <ThemeProvider theme={lightTheme}>
            <MemoryRouter>
              <NotificationPreferencesPage />
            </MemoryRouter>
          </ThemeProvider>
        </LocaleProvider>
      </I18nextProvider>
    </QueryClientProvider>,
  );
}

describe('NotificationPreferencesPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    void i18n.changeLanguage('en');
    vi.mocked(notificationService.fetchNotificationPreferences).mockResolvedValue(mockPreferences);
  });

  it('renders preferences on success', async () => {
    renderPreferencesPage();

    await waitFor(() => {
      expect(screen.getByText('Ticket Created')).toBeInTheDocument();
    });
    expect(screen.getAllByRole('checkbox').length).toBeGreaterThan(0);
  });

  it('updates preferences on save', async () => {
    vi.mocked(notificationService.updateNotificationPreferences).mockResolvedValue();

    renderPreferencesPage();

    await waitFor(() => {
      expect(screen.getByText('Ticket Created')).toBeInTheDocument();
    });

    const emailCheckbox = screen.getAllByRole('checkbox')[1];
    fireEvent.click(emailCheckbox);
    fireEvent.click(screen.getByRole('button', { name: /^save$/i }));

    await waitFor(() => {
      expect(notificationService.updateNotificationPreferences).toHaveBeenCalled();
    });
  });
});
