import { useEffect } from 'react';
import { useInventoryPageStore } from '../../store/inventoryPage';
import {
	InventoryFieldWrapper,
	ResourceScopes,
	SelectScopeValuesMessage,
} from '../shared';
import { useScopeValues } from '../../hooks/useScopeValues';
import { useScopedInventoryData } from '../../store/hooks/useScopedInventoryData';

export function AdvancedInventoryField({
	field,
}: {
	field: GravityFormsField;
}) {
	// Use our custom hook to manage scope values
	const { scopeValues, handleScopeValueChange, allValid } =
		useScopeValues(field);

	// Fetch inventory when all dropdowns have valid values
	useEffect(() => {
		if (!allValid) return;

		// Fetch inventory with scope values
		useInventoryPageStore
			.getState()
			.fetchScopedInventory(field.id, scopeValues);
	}, [field.id, allValid, scopeValues]);

	// Use our optimized hook to get inventory data
	// This will only trigger re-renders when the actual inventory data changes
	const { inventory, isLoading, error } = useScopedInventoryData(
		field,
		scopeValues
	);

	// Scope section to display
	const scopeSection = (
		<ResourceScopes
			field={field}
			scopeValues={scopeValues}
			onScopeValueChange={handleScopeValueChange}
		/>
	);

	// Content to display when not loading or error
	const contentSection = (
		<div className="inventory-available">
			<span className="inventory-available-label">
				Inventory Available
			</span>
			{inventory !== null && inventory !== undefined ? (
				<span className="inventory-available-value">{inventory}</span>
			) : (
				<SelectScopeValuesMessage />
			)}
		</div>
	);

	return (
		<InventoryFieldWrapper
			field={field}
			isLoading={isLoading}
			error={error}
			scopeSection={scopeSection}
			contentSection={contentSection}
		/>
	);
}
