import { useEffect } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

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

import { formFieldsRequestCreate } from '../constant';

import { HoursRequestType, type RequestCreateForm } from './useRequestCreate';

export const useValidations = () => {
  const { control, trigger } = useFormContext<RequestCreateForm>();
  const { t } = useLokaliseTranslation('time_off');

  const [
    fromDate,
    fromHour,
    fromHourTime,
    toDate,
    toHour,
    toHourTime,
    hoursRequestType,
  ] = useWatch({
    name: [
      formFieldsRequestCreate.fromDate,
      formFieldsRequestCreate.fromHour,
      formFieldsRequestCreate.fromHourTime,
      formFieldsRequestCreate.toDate,
      formFieldsRequestCreate.toHour,
      formFieldsRequestCreate.toHourTime,
      formFieldsRequestCreate.hoursRequestType,
    ],
    control: control,
  });

  useEffect(() => {
    if (fromHour && fromHourTime && toHour && toHourTime) {
      trigger([formFieldsRequestCreate.toHour]);
    }
  }, [fromHour, fromHourTime, toHour, toHourTime]);

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

  const validateTime = useRules(
    {
      requiredWithMessage: true,
    },
    {
      validate: () => {
        if (fromHour && toHour && fromHourTime && toHourTime) {
          const startParsed = setTimeString(
            new Date(fromDate),
            `${fromHour}:${fromHourTime}`,
          );
          const endParsed = setTimeString(
            new Date(
              hoursRequestType === HoursRequestType.MORE_THAN_ONE_DAY
                ? toDate
                : fromDate,
            ),
            `${toHour}:${toHourTime}`,
          );
          if (startParsed >= endParsed) {
            return t('end_time_of_request_should_be_after_start_time');
          }
        }
        return true;
      },
    },
  );

  return {
    requiredRules,
    validateTime,
  };
};
