import { renderWithClient } from '../../../utils/test/react-query';
import RegisterContent from '../register-content';
import {
  mockedAuthKey,
  mockedMobile,
  mockedRestrictedMobile,
  mockedSmsKey
} from '../../../mocks/data';
import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { act } from '@testing-library/react-hooks';
import { DEFAULT_TIME_LEFT } from '../sms-key/resend-view';

describe('RegisterContent component', () => {
  test('successful render component step 1', async () => {
    const result = renderWithClient(<RegisterContent />, MemoryRouter);
    expect(await result.findByTestId('mobile-form')).toBeInTheDocument();
    expect(await result.findByText('تایید')).toBeInTheDocument();
  });

  test('successful render component step 2', async () => {
    const result = renderWithClient(<RegisterContent startStep={1} defaultMobile={mockedMobile} />);
    expect(await result.findByTestId('smskey-content')).toBeInTheDocument();
    expect(await result.findByText('تایید')).toBeInTheDocument();
  });

  test('successful render component step 3', async () => {
    const result = renderWithClient(
      <RegisterContent startStep={2} defaultMobile={mockedMobile} defaultAuthKey={mockedAuthKey} />,
      MemoryRouter
    );
    expect(await result.findByTestId('register-form')).toBeInTheDocument();
    expect(await result.findByText('تایید')).toBeInTheDocument();
  });

  test('call checkSmsKeyRequest function with error 403', async () => {
    const data = { mobile: mockedRestrictedMobile, smsKey: mockedSmsKey };

    const result = renderWithClient(<RegisterContent startStep={1} defaultMobile={data.mobile} />);

    const user = userEvent.setup();
    await user.type(result.getByTestId('smsKey-field'), data.smsKey);
    await user.click(await result.getByRole('button', { name: /تایید/i }));
    await waitFor(() =>
      expect(result.getByRole('alert')).toHaveTextContent(
        'محدودیت‌ وارد کردن کد پیامکی اشتباه برای شما به پایان رسیده است.'
      )
    );
  });

  test('call sendSmsKeyRequest function with error 403', async () => {
    jest.useFakeTimers();
    const data = { mobile: mockedRestrictedMobile };

    const result = renderWithClient(
      <RegisterContent startStep={1} defaultMobile={data.mobile} />,
      MemoryRouter
    );

    act(() => jest.advanceTimersToNextTimer(DEFAULT_TIME_LEFT));
    jest.useRealTimers();

    const user = userEvent.setup();
    await user.click(await result.getByRole('button', { name: /ارسال مجدد کد/i }));
    await waitFor(() =>
      expect(result.getByRole('alert')).toHaveTextContent(
        'محدودیت‌ ارسال کد پیامکی برای شما به پایان رسیده است.'
      )
    );
  });
});
