import { useFormContext } from 'react-hook-form';

import useRules from 'src/hooks/useRules';
import { setTimeString } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { FieldTypes } from '../types';

export const useValidations = () => {
  const { watch } = useFormContext();
  const { t } = useLokaliseTranslation('events');

  const [
    endDate,
    endHoursTime,
    endMinutesTime,
    startDate,
    startHoursTime,
    startMinutesTime,
  ] = watch([
    FieldTypes.END_DATE,
    FieldTypes.END_HOURS_TIME,
    FieldTypes.END_MINUTES_TIME,
    FieldTypes.START_DATE,
    FieldTypes.START_HOURS_TIME,
    FieldTypes.START_MINUTES_TIME,
  ]);

  const requiredRules = useRules({
    requiredWithMessage: true,
  });

  const validateEndDate = useRules(
    {
      validateRequiredWithOptional: {
        valuesToCompare: [endMinutesTime, endHoursTime],
        message: t('CONDITIONAL_REQUIRED_FIELD', {
          context: FieldTypes.END_DATE,
        }),
      },
    },
    {
      validate: () => {
        if (
          endDate &&
          endHoursTime &&
          endMinutesTime &&
          startDate &&
          startHoursTime &&
          startMinutesTime
        ) {
          const startParsed = setTimeString(
            new Date(startDate),
            `${startHoursTime}:${startMinutesTime}`,
          );
          const endParsed = setTimeString(
            new Date(endDate),
            `${endHoursTime}:${endMinutesTime}`,
          );
          if (startParsed >= endParsed) {
            return t('ERRORS.COMPARE_DATES');
          }
        }
        return true;
      },
    },
  );

  const validateEndHoursTime = useRules({
    validateRequiredWithOptional: {
      valuesToCompare: [endDate, endMinutesTime],
      message: t('CONDITIONAL_REQUIRED_FIELD', {
        context: FieldTypes.END_HOURS_TIME,
      }),
    },
  });

  const validateEndMinutesTime = useRules({
    validateRequiredWithOptional: {
      valuesToCompare: [endDate, endHoursTime],
      message: t('CONDITIONAL_REQUIRED_FIELD', {
        context: FieldTypes.END_HOURS_TIME,
      }),
    },
  });

  return {
    requiredRules,
    validateEndDate,
    validateEndHoursTime,
    validateEndMinutesTime,
  };
};
