const { format, isValid } = require('date-fns');
const { utcToZonedTime } = require('date-fns-tz');

const DATE_FORMAT = 'MMM dd, yyyy';
const SHORT_DATE_FORMAT = 'MM/dd/yyyy';
const SHORT_DATE_PLACEHOLDER = 'MM/DD/YYYY';

const DATETIME_FORMAT = 'MMM dd, yyyy h:mm a';
const DATETIME_24H_FORMAT = 'MMM dd, yyyy H:mm';
const SHORT_DATETIME_FORMAT = 'MM/dd/yyyy h:mm a';
const SHORT_DATETIME_24H_FORMAT = 'MM/dd/yyyy H:mm';

const DATETIME_PLACEHOLDER = 'MM/DD/YYYY HH:MM AM/PM';
const DATETIME_24H_PLACEHOLDER = 'MM/DD/YYYY HH:MM';
const TIMEZONE = 'America/Los_Angeles';

module.exports.DATE_FORMAT = DATE_FORMAT;
module.exports.DATETIME_FORMAT = DATETIME_FORMAT;
module.exports.SHORT_DATE_FORMAT = SHORT_DATE_FORMAT;
module.exports.SHORT_DATETIME_FORMAT = SHORT_DATETIME_FORMAT;
module.exports.SHORT_DATE_PLACEHOLDER = SHORT_DATE_PLACEHOLDER;
module.exports.DATETIME_24H_FORMAT = DATETIME_24H_FORMAT;
module.exports.SHORT_DATETIME_24H_FORMAT = SHORT_DATETIME_24H_FORMAT;
module.exports.DATETIME_PLACEHOLDER = DATETIME_PLACEHOLDER;
module.exports.DATETIME_24H_PLACEHOLDER = DATETIME_24H_PLACEHOLDER;

module.exports.formatDate = (incomingDate, dateFormat = DATE_FORMAT, isUTC = false) => {
  if (!incomingDate) {
    return null;
  }

  const date = new Date(incomingDate);

  if (!isValid(date)) {
    return incomingDate;
  }

  if (isUTC) {
    return format(utcToZonedTime(date, TIMEZONE), dateFormat);
  }

  return format(date, dateFormat);
};

module.exports.validateDate = (date) => {
  const year = new Date(date).getFullYear();
  return year && year > 999 && year < 3000;
};

module.exports.maxDate = () => {
  const date = new Date();
  date.setFullYear(date.getFullYear() + 50);
  return date;
};

module.exports.minDate = () => {
  const date = new Date();
  date.setFullYear(date.getFullYear() - 50);
  return date;
};
