import { useCallback } from 'react';
import { ScopeDropdown } from './';
import { useResource } from '../../hooks';
import './ResourceScopes.css';

/**
 * Component for rendering resource scopes
 *
 * @param root0
 * @param root0.field              The field to render scopes for
 * @param root0.scopeValues        The scope values from parent component
 * @param root0.onScopeValueChange Callback when a scope value changes
 */
export function ResourceScopes({
	field,
	scopeValues,
	onScopeValueChange,
}: {
	field: GravityFormsField;
	scopeValues: Record<string, string>;
	onScopeValueChange: (scopeId: string, value: string) => void;
}) {
	// Use the resource hook to get resource information
	const { resource, hasProperties, properties } = useResource(field);

	// Handle dropdown value changes - use useCallback to stabilize
	const handleDropdownChange = useCallback(
		(scopeId: string, value: string) => {
			onScopeValueChange(scopeId, value);
		},
		[onScopeValueChange]
	);

	// Return null if there's no resource or properties
	if (!hasProperties) return null;

	return (
		<div className="inventory-scopes">
			<div className="inventory-scopes-row inventory-field-content-blue">
				<div className="inventory-scopes-label">Scopes</div>
				<div className="inventory-scopes-dropdowns">
					{properties.map((property) => (
						<ScopeDropdown
							key={property.id}
							scopeName={property.name}
							scopeId={property.id}
							fieldId={
								field.gpiResourcePropertyMap?.[property.id] ||
								''
							}
							value={scopeValues[property.id] || ''}
							onChange={(value) =>
								handleDropdownChange(property.id, value)
							}
						/>
					))}
				</div>
			</div>
		</div>
	);
}
