import React from 'react';
import { waitFor, fireEvent } from '@testing-library/react';
import renderWithTheme from '../../../../testUtils/renderWithTheme';

import Calendar from '../index';

describe('Month Calendar', () => {
  it('renders correctly', async () => {
    const { getByText, getByTestId } = renderWithTheme(
      <Calendar.Month
        selectedMonth={new Date(2021, 2)}
        minDate={new Date(2021, 2)}
        maxDate={new Date(2021, 10)}
      />
    );

    await waitFor(() => {
      // shows year in select
      const yearSelect = getByTestId('year-select');
      expect(yearSelect).toSelectItem('2021');
      // shows months of year
      expect(getByText('Jan')).toBeInTheDocument();
      expect(getByText('Feb')).toBeInTheDocument();
      expect(getByText('Mar')).toBeInTheDocument();
      expect(getByText('Apr')).toBeInTheDocument();
      expect(getByText('May')).toBeInTheDocument();
      expect(getByText('Jun')).toBeInTheDocument();
      expect(getByText('Jul')).toBeInTheDocument();
      expect(getByText('Aug')).toBeInTheDocument();
      expect(getByText('Sep')).toBeInTheDocument();
      expect(getByText('Oct')).toBeInTheDocument();
      expect(getByText('Nov')).toBeInTheDocument();
      expect(getByText('Dec')).toBeInTheDocument();
    });
  });
});

describe('Month Calendar Interaction', () => {
  it('allows to select year', async () => {
    const { getByText, getByTestId } = renderWithTheme(
      <Calendar.Month selectedMonth={new Date(2021, 4)} />
    );

    const yearSelect = getByTestId('year-select');
    fireEvent.click(yearSelect);
    fireEvent.click(getByText('2025'));

    await waitFor(() => {
      expect(yearSelect).toSelectItem('2025');
    });
  });

  it('allows to select a new month', async () => {
    const onSelectMonth = jest.fn();
    const { getByText, getByTestId } = renderWithTheme(
      <Calendar.Month
        selectedMonth={new Date(2021, 1)}
        onSelectMonth={onSelectMonth}
      />
    );

    fireEvent.click(getByTestId('year-select'));
    fireEvent.click(getByText('2022'));
    fireEvent.click(getByText('Aug'));

    await waitFor(() => {
      expect(onSelectMonth).toHaveBeenCalledTimes(1);
      expect(onSelectMonth).toHaveBeenCalledWith(new Date(2022, 7, 1));
    });
  });

  it('does not allow to select a new date out of range', async () => {
    const onSelectMonth = jest.fn();
    const { getByText } = renderWithTheme(
      <Calendar.Month
        selectedMonth={new Date(2021, 3)}
        minDate={new Date(2021, 2)}
        maxDate={new Date(2021, 5)}
        onSelectMonth={onSelectMonth}
      />
    );

    fireEvent.click(getByText('Sep'));

    await waitFor(() => {
      expect(onSelectMonth).not.toHaveBeenCalled();
    });
  });
});
