import { useState } from 'react';
import { useResource } from './useResource';

/**
 * Hook for managing scope values for advanced inventory fields
 *
 * @param field The field to manage scope values for
 * @return Object containing scope values state and helper functions
 */
export function useScopeValues(field: GravityFormsField) {
	// Use the resource hook to get resource information
	const { resource, hasProperties, properties } = useResource(field);

	// Store scope values in this component
	const [scopeValues, setScopeValues] = useState<Record<string, string>>(
		() => {
			if (!hasProperties) return {};

			return properties.reduce((acc, property) => {
				acc[property.id] = '';
				return acc;
			}, {} as Record<string, string>);
		}
	);

	// Handle scope value changes
	const handleScopeValueChange = (scopeId: string, value: string) => {
		setScopeValues((prev) => ({
			...prev,
			[scopeId]: value,
		}));
	};

	// Check if all dropdowns have valid values
	// all are valid if there are no properties OR if all properties have values selected
	const allValid =
		!hasProperties ||
		(hasProperties &&
			properties.every(
				(property) =>
					scopeValues[property.id] && scopeValues[property.id] !== ''
			));

	return {
		scopeValues,
		handleScopeValueChange,
		hasProperties,
		allValid,
		resource,
	};
}
