import { useCallback, useRef } from 'react';

import { useAppConfirm } from '~/src/components/NextApp/lib/CoreUi';
import { useItemContext } from '../ItemPageContext';
import { getItemChanges } from './utils';

/**
 * Guards navigation away from the edit page.
 * Returns an async function that resolves to `true` when it's safe to navigate
 * (no changes, or the user confirmed) and `false` when the user cancelled.
 */
export const useConfirmNavigation = () => {
  const itemContext = useItemContext();
  const confirm = useAppConfirm();

  // Read the latest itemContext at call-time via a ref so the returned guard
  // stays stable and never sees a stale context when captured inside a
  // memoized handler (e.g. the "no more items" app alert action).
  const itemContextRef = useRef(itemContext);
  itemContextRef.current = itemContext;

  return useCallback(async (): Promise<boolean> => {
    const changes = Object.keys(getItemChanges(itemContextRef.current));
    const hasChanges = !!changes.length;

    if (!hasChanges) return true;

    return confirm({
      content: 'Exit without saving changes?',
      actionText: 'Exit',
    });
  }, [confirm]);
};
