import React from 'react';
import { NavigationAPI } from '../../../hooks';

export const handleNavigationAttempt = async (
  navigation: NavigationAPI,
  dirty: boolean,
  isValid: boolean,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  submitForm: (() => Promise<void>) & (() => Promise<any>),
  isSubmitting: boolean,
  canSubmit: boolean,
  setCanSubmit: React.Dispatch<React.SetStateAction<boolean>>,
  onNavigationCancelled: () => void,
): Promise<void> => {
  if (!dirty) {
    // Form values didn't change, just navigate away
    navigation.resume();
    return;
  }
  if (!isValid) {
    // Form is invalid, cancel navigation
    // TODO: Add a message here (probably connected to "Error handling")
    navigation.cancel();
    onNavigationCancelled();
    return;
  }
  // Form values have changed and form is valid, attempt save
  navigation.pause();
  try {
    // only attempt to submit the form if there is no current submission in progress
    if (!isSubmitting && canSubmit) {
      // Block additional submit requests before continuing navigation or double clicking can cause the form to be submitted again.
      setCanSubmit(false);
      // Wait for success response
      await submitForm();
      // Successfully saved, continue navigation
      navigation.resume();
    }
  } catch (error) {
    // TODO: Proper Error handling
    // An error occurred while attempting to save, cancel navigation
    navigation.cancel();
    // Allow submits again if error
    setCanSubmit(true);
  }
};
