import { useEffect, useRef, useState } from 'react';

import useHugoUnsavedWarning from 'src/hooks/useUnsavedWarning/altHugo';
import { useLokaliseTranslation } from 'src/utils/i18n';

type Props = {
  isDirty: boolean;
};

const useCreateCertificateUnsavedWarning = ({ isDirty }: Props) => {
  const { t } = useLokaliseTranslation('general');
  const [isBlockerBypassed, setIsBlockerBypassed] = useState(false);
  const pendingNavigationRef = useRef<(() => void) | null>(null);

  const { modal, blocker } = useHugoUnsavedWarning({
    shouldBlock: isDirty && !isBlockerBypassed,
    modalProps: {
      title: t('general:wish_to_exit_without_saving'),
      body: t('general:unsaved_changes_will_be_lost'),
      primaryButtonProps: {
        children: t('general:cancel'),
        onClick: () => {
          blocker?.reset?.();
          modal.closeModal();
        },
      },
      secondaryButtonProps: {
        children: t('general:exit_without_saving'),
        onClick: () => {
          modal.closeModal();
          blocker?.proceed?.();
        },
      },
    },
  });

  useEffect(() => {
    if (isBlockerBypassed) pendingNavigationRef.current?.();
  }, [isBlockerBypassed]);

  const navigateWithoutBlocking = (navigate: () => void) => {
    pendingNavigationRef.current = navigate;
    setIsBlockerBypassed(true);
  };

  return { modal, navigateWithoutBlocking };
};

export default useCreateCertificateUnsavedWarning;
