import { useEffect } from 'react';
import type { DatePickerProps } from '../types';

export const getDateValue = (
  value: Date,
  minDate?: Date | undefined,
  maxDate?: Date | undefined
) => {
  if (minDate && value < minDate) {
    return minDate;
  }

  if (maxDate && value > maxDate) {
    return maxDate;
  }

  return value;
};

const useCalculateDate = ({
  maxDate,
  minDate,
  onChange,
  value,
}: Pick<DatePickerProps, 'maxDate' | 'minDate' | 'onChange' | 'value'>) => {
  useEffect(() => {
    const newDate = getDateValue(value || new Date(), minDate, maxDate);
    if (value && newDate.toDateString() !== value.toDateString()) {
      onChange(newDate);
    }
  }, [maxDate, minDate, value]);
};

export default useCalculateDate;
