// @flow
import React from 'react';
import {
  mountWrappedComponent,
  renderSnapshot,
  itIsAccessible,
} from '../../../utils/tests';
import type { DateRangePickerProps } from './date-range-picker.proptypes';
import { DateRangePicker } from './index';

const DEFAULT_PROPS: DateRangePickerProps = {
  onRangeChange: jest.fn(),
  placeholder: 'placeholder',
  range: { from: undefined, to: undefined },
};

const getStartOfMonth = date =>
  new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0);

describe('DateRangePicker', () => {
  describe('snapshot', () => {
    it('matches the previous snapshot', () => {
      const dateRangePicker = renderSnapshot(
        <DateRangePicker {...DEFAULT_PROPS} />,
      );
      expect(dateRangePicker).toMatchSnapshot();
    });
  });

  it('can pick dates and pass those dates to onRangeChange', () => {
    const mockOnDateSelect = jest.fn();

    const props = {
      ...DEFAULT_PROPS,
      onRangeChange: mockOnDateSelect,
    };
    let component = mountWrappedComponent(<DateRangePicker {...props} />);

    component.find('button').simulate('click');
    component = component.update();

    const allAvailableDates = component.findWhere(
      n => n.name() === 'Day' && n.prop('ariaDisabled') === false,
    );

    allAvailableDates.at(0).simulate('click');
    allAvailableDates.at(1).simulate('click');

    const startOfMonth = getStartOfMonth(new Date());

    expect(mockOnDateSelect).toHaveBeenCalledTimes(2);
    // TODO: use memo doesn't seem totally supported https://github.com/airbnb/enzyme/issues/2011
    // such that the date picker is always using the first memoized value. In the future, we should
    // be checking that the last click passes a from AND a to value
    expect(mockOnDateSelect.mock.calls[0][0]).toEqual({
      from: startOfMonth,
      to: undefined,
    });
  });

  it('sets the from to the very start of the day', () => {
    const mockOnDateSelect = jest.fn();

    const props = {
      ...DEFAULT_PROPS,
      onRangeChange: mockOnDateSelect,
    };
    let component = mountWrappedComponent(<DateRangePicker {...props} />);

    component.find('button').simulate('click');
    component = component.update();

    const allAvailableDates = component.findWhere(
      n => n.name() === 'Day' && n.prop('ariaDisabled') === false,
    );

    allAvailableDates.at(0).simulate('click');

    const { from = new Date() } = mockOnDateSelect.mock.calls[0][0];

    expect(from.getHours()).toEqual(0);
    expect(from.getMinutes()).toEqual(0);
    expect(from.getSeconds()).toEqual(0);
  });

  describe.only('accessibility', () => {
    itIsAccessible(<DateRangePicker {...DEFAULT_PROPS} />);
  });
});
