import { isValid, max, min } from 'date-fns';
import { ModifiersUtils } from 'react-day-picker';
import { DATE_VALIDITY } from './constants';
import { DATEPICKER_ACTION } from './types';
function getNewState(isRange, day, _ref) {
  var startDate = _ref.startDate,
    endDate = _ref.endDate;
  if (!isRange || !day) {
    return {
      startDate: day,
      endDate: day
    };
  }
  if (startDate && !endDate) {
    return {
      startDate: min([startDate, day]),
      endDate: max([startDate, day])
    };
  }
  return {
    startDate: day,
    endDate: null
  };
}
function calculateDateValidity(date, disabledDays) {
  if (!date) {
    return null;
  }
  if (!isValid(date)) {
    return DATE_VALIDITY.INVALID;
  }
  if (ModifiersUtils.dayMatchesModifier(date, disabledDays)) {
    return DATE_VALIDITY.DISABLED;
  }
  return DATE_VALIDITY.VALID;
}
export var useHandleDayClick = function useHandleDayClick(state, dispatch, isRange, disabledDays, onChange) {
  function handleDayClick(day) {
    var newState = getNewState(isRange, day, state);
    dispatch({
      type: DATEPICKER_ACTION.UPDATE,
      data: newState
    });
    var startDate = newState.startDate,
      endDate = newState.endDate;
    if (onChange) {
      onChange({
        startDate: startDate,
        startDateValidity: calculateDateValidity(startDate, disabledDays),
        endDate: endDate,
        endDateValidity: calculateDateValidity(endDate, disabledDays)
      });
    }
    return newState;
  }
  return handleDayClick;
};