import { useMemo, useRef } from 'react';
import { useInventoryPageStore } from '../inventoryPage';
import { getScopedInventoryKey } from '../slices/inventories';

/**
 * Custom hook to get scoped inventory data with optimization to prevent unnecessary re-renders
 *
 * @param field       The field to get inventory data for
 * @param scopeValues The scope values to use for the inventory data
 * @return The scoped inventory data
 */
export function useScopedInventoryData(
	field: GravityFormsField,
	scopeValues: Record<string, string>
) {
	// Get the scoped inventory data from the store
	const inventoryData = useInventoryPageStore.use.scopedInventories();
	const scopedInventoryKey = getScopedInventoryKey(field.id, scopeValues);
	const scopedInventory = inventoryData[scopedInventoryKey];

	// Keep a reference to the previous inventory data
	const prevInventoryRef = useRef<any>(null);

	// Memoize the result to only return a new value if the scoped inventory data changes
	return useMemo(() => {
		// Default empty data
		const emptyData = {
			inventory: null,
			isLoading: false,
			error: null,
		};

		// Get the current inventory data or use empty data
		const currentInventory = scopedInventory || emptyData;

		// If there's no previous inventory, set it and return the current
		if (!prevInventoryRef.current) {
			prevInventoryRef.current = currentInventory;
			return currentInventory;
		}

		// Compare the current and previous inventory data
		const prevInventory = prevInventoryRef.current;
		const hasChanged =
			prevInventory.inventory !== currentInventory.inventory ||
			prevInventory.isLoading !== currentInventory.isLoading ||
			prevInventory.error !== currentInventory.error;

		// If the data has changed, update the reference and return the new data
		if (hasChanged) {
			prevInventoryRef.current = currentInventory;
			return currentInventory;
		}

		// If nothing has changed, return the previous data to prevent re-renders
		return prevInventoryRef.current;
	}, [scopedInventory]);
}
