import { renderWithClient } from '../../../utils/test/react-query';
import { MemoryRouter } from 'react-router-dom';
import { mockFailureResponse } from '../../../mocks/server';
import { mockedMobile } from '../../../mocks/data';
import * as tempUserAPI from '../../../api/temp-user';
import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/react';
import MobileForm from '../mobile-form';

describe('MobileForm component', () => {
  const mockedHandleSubmit = jest.fn();

  afterEach(() => {
    jest.restoreAllMocks();
    jest.restoreAllMocks();
  });

  test('successful render component', async () => {
    mockFailureResponse();

    const result = renderWithClient(<MobileForm onSubmit={mockedHandleSubmit} />, MemoryRouter);
    expect(await result.findByTestId('mobile-form')).toBeInTheDocument();
    expect(await result.findByText('تایید')).toBeInTheDocument();
  });

  test('call register user function with correct arguments', async () => {
    const createTempUser = jest.spyOn(tempUserAPI, 'createTempUser');

    const result = renderWithClient(<MobileForm onSubmit={mockedHandleSubmit} />, MemoryRouter);
    const user = userEvent.setup();
    await user.type(result.getByTestId('mobile-field'), mockedMobile);
    await user.click(await result.getByRole('button', { name: /تایید/i }));

    await waitFor(() => expect(createTempUser).toHaveBeenCalledWith({ mobile: mockedMobile }));
    await waitFor(() => expect(mockedHandleSubmit).toHaveBeenCalled());
  });

  test('form errors', async () => {
    const result = renderWithClient(<MobileForm onSubmit={mockedHandleSubmit} />, MemoryRouter);
    const mobileField = await result.getByTestId('mobile-field');
    const user = userEvent.setup();
    await user.type(mobileField, mockedMobile.substring(2));
    await user.tab();

    expect(await result.getByTestId('mobile-field-error')).toHaveTextContent(
      'لطفا یک شماره تلفن همراه معتبر وارد نمایید.'
    );
  });
});
