import * as React from 'react';
import {
  describe,
  it,
  jest,
  beforeAll,
  afterEach,
  afterAll,
  expect,
} from '@jest/globals';
import { render, screen, waitFor } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { BrowserRouter } from 'react-router-dom';
import { ChakraProvider, theme as chakraTheme } from '@chakra-ui/react';
import { Provider } from 'react-redux';

import ErrorBoundary from '../../components/ErrorBoundary';
import { store } from '../../__data__/store';
import Page from '../arm';
import { PageSpinner } from '../../components';

const server = setupServer(
  http.post('/api/arm/orders', () => {
    return HttpResponse.json({}, { status: 500 });
  }),
  http.get('/api/arm/masters', () => {
    return HttpResponse.json({
      success: true,
      body: [
        {
          id: '4545423234',
          name: 'Иван Иванов',
          phone: '+7 900 123 45 67',
        },
        {
          name: 'Олег Макаров',
          phone: '79001234567',
          id: '23423442',
        },
        {
          id: '345354234',
          name: 'Иван Галкин',
          schedule: [
            {
              id: 'order1',
              startWashTime: '2024-11-24T10:30:00.000Z',
              endWashTime: '2024-11-24T16:30:00.000Z',
            },
            {
              id: 'order2',
              startWashTime: '2024-11-24T11:30:00.000Z',
              endWashTime: '2024-11-24T17:30:00.000Z',
            },
          ],
          phone: '+7 900 123 45 67',
        },
      ],
    });
  }),
);

jest.mock('@brojs/cli', () => {
  return {
    getNavigationValue: () => '/auth/login',
    getConfigValue: () => '/api',
  };
});

describe('order page', () => {
  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  it('обработка ошибки при загрузке данных', async () => {
    render(
      <Provider store={store}>
        <ChakraProvider theme={chakraTheme}>
          <ErrorBoundary>
            <BrowserRouter>
              <Page mockUser={{ name: 'ilnaz' }} />
            </BrowserRouter>
          </ErrorBoundary>
        </ChakraProvider>
      </Provider>,
    );

    await waitFor(() => screen.getByText('Ошибка при загрузке данных'));
  });
});

describe('Routers', () => {
  it('отображает PageSpinner ', async () => {
    render(<PageSpinner />);

    expect(await screen.findByTestId('spinner')).toBeTruthy();
  });
});
