import { getFieldById } from '../../utils/fieldUtils';
import { useScopeOptions } from '../../hooks';

// Import the ScopeOption interface
interface ScopeOption {
	value: string;
	label: string;
}

/**
 * Component for rendering a scope dropdown
 *
 * @param root0
 * @param root0.scopeName The name of the scope
 * @param root0.scopeId   The ID of the scope
 * @param root0.fieldId   The ID of the field associated with the scope
 * @param root0.value     The current value of the dropdown
 * @param root0.onChange  Function to call when the value changes
 */
export function ScopeDropdown({
	scopeName,
	scopeId,
	fieldId,
	value,
	onChange,
}: {
	scopeName: string;
	scopeId: string;
	fieldId: string;
	value: string;
	onChange: (value: string) => void;
}) {
	const field = getFieldById(fieldId);
	const fieldType = field?.type || 'Unknown';
	const capitalizedFieldType =
		fieldType.charAt(0).toUpperCase() + fieldType.slice(1);

	// Get form ID from the field
	const formId = field?.formId?.toString() || '';

	// Use our custom hook to get options
	const { loading, error, options } = useScopeOptions(fieldId, formId);

	// Generate a unique ID for the select element
	const selectId = `scope-${scopeId}`;

	const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
		onChange(e.target.value);
	};

	return (
		<div className="scope-dropdown">
			<select
				id={selectId}
				aria-label={scopeName}
				value={value}
				onChange={handleChange}
				disabled={loading}
			>
				<option value="">
					{loading
						? 'Loading...'
						: `${scopeName}: Select ${capitalizedFieldType}`}
				</option>
				{options.map((option: ScopeOption) => (
					<option key={option.value} value={option.value}>
						{option.label}
					</option>
				))}
			</select>
			{error && <span className="error-message">{error}</span>}
		</div>
	);
}
