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

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

	// Use our optimized hook to get choice inventory data
	const { choices, isLoading, error } = useScopedChoiceInventory(
		field,
		scopeValues
	);

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

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

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

	// Content to display when not loading or error
	const getContentSection = () => {
		if (!allValid) {
			return (
				<div className="inventory-field-content-blue">
					<SelectScopeValuesMessage />
				</div>
			);
		} else if (field.choices && field.choices.length > 0) {
			return (
				<ChoicesTable choices={field.choices} inventoryData={choices} />
			);
		}

		return (
			<div className="inventory-error">
				<p>No choices found for this field.</p>
			</div>
		);
	};

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