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

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

import { useLokaliseTranslation } from 'src/utils/i18n';

type Args = {
  /**
   * `true` once the user has manually saved at least once (or when entering edit
   * mode on an existing item). Controls the wording of the primary action.
   */
  voluntarySaved: boolean;
  isLoading: boolean;
  /**
   * Called by the primary action. Should return a Promise that resolves once
   * the save is settled. The modal closes after it settles regardless of
   * success/error; `onExit` only runs on success so a failed save does not
   * silently discard the user's work.
   */
  onSave: () => Promise<unknown>;
  /** Called after the modal closes once `onSave` resolves successfully. */
  onExit: () => void;
  /** Called by the secondary "exit without saving" action. */
  onExitWithoutSaving: () => void;
};

const useExitOrSaveModal = ({
  voluntarySaved,
  isLoading,
  onSave,
  onExit,
  onExitWithoutSaving,
}: Args) => {
  const { t } = useLokaliseTranslation(['service_management', 'general']);

  const { showModal, modal, closeModal } = useModal(() => (
    <Dialog
      onClose={closeModal}
      title={t('confirm_exit_title')}
      textBody={
        voluntarySaved
          ? t('confirm_exit_or_save_description_edit')
          : t('confirm_exit_or_save_description_draft')
      }
      primaryButtonProps={{
        id: 'confirm-delete-category-button',
        variant: 'primary',
        loading: isLoading,
        children: voluntarySaved ? t('general:save') : t('save_as_draft'),
        onClick: async () => {
          try {
            await onSave();
            onExit();
          } catch {
            // Mutation surfaces its own error snackbar via `onError`; swallow
            // here so the rejection does not become an unhandled promise.
          } finally {
            closeModal();
          }
        },
      }}
      secondaryButtonProps={{
        id: 'confirm-exit-without-saving-button',
        variant: 'tertiary',
        children: t('exit_without_saving'),
        onClick: onExitWithoutSaving,
        disabled: isLoading,
      }}
    />
  ));

  return { open: showModal, close: closeModal, modal };
};

export default useExitOrSaveModal;
