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

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

import { GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';

import Stack from '@material-hu/mui/Stack';

import Alert from '@material-hu/components/design-system/Alert';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import FormDatePicker from '@material-hu/components/design-system/Inputs/DatePicker/form';
import useFormatDate from 'src/hooks/useFormatDate';
import { BlockedDate, PolicyForm } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  validateDateRequiredRule,
  validateRequiredStringRule,
} from 'src/utils/validation';

import { areDatesOverlapping } from '../utils';

type Props = {
  formDateValues?: AddDateRestrictionDrawerFormValues;
  currentIndex?: number;
  blockedDates: BlockedDate[];
  setBlockedDates: (value: BlockedDate[]) => void;
};

type AddDateRestrictionDrawerFormValues = {
  name: string;
  fromDate: Date | null;
  toDate: Date | null;
  id?: number;
};

const useAddDateRestrictionDrawer: GetDrawerConfiguration<Props> = ({
  formDateValues,
  currentIndex,
  closeDrawer,
  blockedDates,
  setBlockedDates,
}) => {
  const { t } = useLokaliseTranslation('time_off');

  const form = useForm<AddDateRestrictionDrawerFormValues>({
    defaultValues: {
      fromDate: null,
      toDate: null,
      name: '',
      id: undefined,
    },
    mode: 'onChange',
  });

  const policyForm = useFormContext<PolicyForm>();

  const { formatDate } = useFormatDate();

  useEffect(() => {
    if (formDateValues) {
      form.setValue('name', formDateValues.name);
      form.setValue('fromDate', formDateValues.fromDate);
      form.setValue('toDate', formDateValues.toDate);
      form.setValue('id', formDateValues.id);
    }
  }, [formDateValues]);

  const [fromDate, toDate] = useWatch({
    control: form.control,
    name: ['fromDate', 'toDate'],
  });

  const parsedFromDate = formatDate(fromDate || '', 'dd/MM/yyyy');
  const parsedToDate = formatDate(toDate || '', 'dd/MM/yyyy');

  const overlappingDates = useMemo(() => {
    if (!fromDate || !toDate) return false;

    const blockedDatesWithoutCurrent = policyForm
      .getValues('blockedDates')
      .filter((_, index) => index !== currentIndex);

    return areDatesOverlapping(blockedDatesWithoutCurrent, fromDate, toDate);
  }, [fromDate, toDate, policyForm, currentIndex]);

  const handleCloseDrawer = () => {
    form.reset();
    closeDrawer();
  };

  const handleSave = () => {
    const updatedBlockedDates = [...blockedDates];

    const payload = {
      name: form.getValues('name'),
      fromDate: parsedFromDate,
      toDate: parsedToDate,
    };

    if (currentIndex !== undefined) {
      updatedBlockedDates[currentIndex] = {
        ...payload,
        id: updatedBlockedDates[currentIndex].id,
      };
    } else {
      updatedBlockedDates.push(payload);
    }

    setBlockedDates(updatedBlockedDates);
    handleCloseDrawer();
  };

  const disableSaveButton = !form.formState.isValid || overlappingDates;

  return {
    title: t('new_blocked_period'),
    onClose: handleCloseDrawer,
    primaryButtonProps: {
      children: t('general:save'),
      onClick: handleSave,
      disabled: disableSaveButton,
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      onClick: handleCloseDrawer,
    },
    children: (
      <FormProvider {...form}>
        <Stack sx={{ gap: 2 }}>
          <CardContainer
            color="grey"
            fullWidth
            padding={24}
          >
            <FormInputClassic
              name="name"
              inputProps={{
                label: t('period_name'),
                helperText: t('period_name_helper'),
              }}
              rules={{ validate: validateRequiredStringRule }}
            />
          </CardContainer>
          <CardContainer
            color="grey"
            fullWidth
            padding={24}
          >
            <FormDatePicker
              name="fromDate"
              inputProps={{
                label: t('general:from_date'),
                helperText: t('select_first_date_blocked_period'),
              }}
              rules={{
                validate: {
                  validateDateRequiredRule,
                },
              }}
            />
          </CardContainer>
          <CardContainer
            color="grey"
            fullWidth
            padding={24}
          >
            <FormDatePicker
              name="toDate"
              inputProps={{
                label: t('general:to_date'),
                helperText: t('select_last_date_blocked_period'),
                minDate: fromDate || undefined,
              }}
              rules={{ validate: validateRequiredStringRule }}
            />
          </CardContainer>
          {overlappingDates && (
            <Alert
              severity="error"
              title={t('cant_create_blocked_dates')}
              description={t('cant_create_blocked_dates_description')}
            />
          )}
        </Stack>
      </FormProvider>
    ),
  };
};

export default useAddDateRestrictionDrawer;
