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

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

import useVacationApprovalMutation, {
  type VacationChangeStateMutationProps,
} from 'src/hooks/queryHooks/vacations';
import { VacationStatus } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ResolutionDrawerContent from './ResolutionDrawerContent';

export type UseResolutionDrawerProps = {
  mutationProps: VacationChangeStateMutationProps;
  backButton?: boolean;
};

const useResolutionDrawer = (props: UseResolutionDrawerProps) => {
  const { mutationProps, backButton = false } = props;
  const { t } = useLokaliseTranslation('time_off');
  const form = useForm({
    defaultValues: {
      resolutionReason: '',
    },
  });

  const formValue = form.watch('resolutionReason');
  const isApprove = mutationProps.state === VacationStatus.APPROVED;
  const isSingleStep = mutationProps.isSingleApprovalStep ?? true;
  const isApproveOrReject =
    mutationProps.state === VacationStatus.APPROVED ||
    mutationProps.state === VacationStatus.REJECTED;
  const isCancelled = mutationProps.state === VacationStatus.CANCELLED;

  const sendComment = isApproveOrReject && !isSingleStep;
  const sendResolutionReason =
    (isApproveOrReject && isSingleStep) || isCancelled;

  const mutation = useVacationApprovalMutation({
    ...mutationProps,
    comment: sendComment ? formValue : undefined,
    resolutionReason: sendResolutionReason ? formValue : undefined,
  });

  const handleConfirm = form.handleSubmit(async () => {
    await mutation.mutateAsync();
    drawer.closeDrawer();
  });

  const drawer = useDrawer(
    ResolutionDrawerContent,
    {
      title: isApprove
        ? t('approve_modal_title')
        : t('reject_modal_title', { context: mutationProps.state }),
      primaryButtonProps: {
        children: t('general:confirm'),
        onClick: handleConfirm,
        loading: mutation.isLoading,
        color: 'primary',
        sx: { width: '100%' },
      },
      ...(backButton && {
        secondaryButtonProps: {
          children: t('general:cancel'),
          color: 'secondary',
          onClick: () => drawer.closeDrawer(),
          sx: { width: '100%' },
        },
      }),
    },
    { form, state: mutationProps.state },
  );

  return {
    drawer,
    mutation,
  };
};

export default useResolutionDrawer;
