import { addHours, isValid, parse } from 'date-fns';
import { useCallback } from 'react';
import { DATEPICKER_ACTION } from './types';
function parseDate(datePickerFormat, value) {
  if (!value) {
    return null;
  }
  var date = parse(value, datePickerFormat, new Date());
  if (!isValid(date) || date.getFullYear() <= 999) {
    return new Date(NaN);
  }
  return addHours(date, 12);
}
export function useInput(datePickerFormat, isRange, handleDayClick, dispatch) {
  var handleKeyDown = useCallback(function (event) {
    if (isRange || event.key !== 'Enter') {
      return;
    }
    dispatch({
      type: DATEPICKER_ACTION.REFRESH_INPUT_VALUE
    });
  }, [dispatch, isRange]);
  var handleInputBlur = useCallback(function () {
    if (isRange) {
      return;
    }
    dispatch({
      type: DATEPICKER_ACTION.REFRESH_HAS_ERROR
    });
    dispatch({
      type: DATEPICKER_ACTION.REFRESH_INPUT_VALUE
    });
  }, [dispatch, isRange]);
  var handleInputChange = useCallback(function (event) {
    if (isRange) {
      return;
    }
    dispatch({
      type: DATEPICKER_ACTION.UPDATE,
      data: {
        inputValue: event.currentTarget.value
      }
    });
    var date = parseDate(datePickerFormat, event.currentTarget.value);
    handleDayClick(date);
  }, [isRange, dispatch, datePickerFormat, handleDayClick]);
  return {
    handleKeyDown: handleKeyDown,
    handleInputBlur: handleInputBlur,
    handleInputChange: handleInputChange
  };
}