// Function to check if a checkbox choice is disabled
function isCheckboxChoiceDisabled(
	formId: string | number,
	fieldId: string | number,
	choiceValue: string
): boolean {
	const field = jQuery(`#input_${formId}_${fieldId}`);
	const checkbox = field.find(
		`input[type="checkbox"][value="${choiceValue}"]`
	);

	return checkbox.is(':disabled') && checkbox.hasClass('gpi-disabled');
}

// Function to handle the "Select All" checkbox logic
function handleCheckboxChoiceAll(event: Event): void {
	const target = event.target as Element;
	if (!target.matches('.gfield_choice_all_toggle')) {
		return;
	}

	const button = target;
	const checkboxDiv = button.closest('.ginput_container_checkbox');
	if (!checkboxDiv) {
		return;
	}

	const checkboxes = checkboxDiv.querySelectorAll('input[type="checkbox"]');

	// Iterate over the checkboxes and ensure disabled choice isn't selected/deselected.
	checkboxes.forEach((checkbox) => {
		const inputCheckbox = checkbox as HTMLInputElement;
		const choiceValue = inputCheckbox.value;
		const checkboxId = inputCheckbox.id;
		const formId = checkboxId ? parseInt(checkboxId.split('_')[1]) : null;
		const fieldId = checkboxId ? parseInt(checkboxId.split('_')[2]) : null;

		if (
			formId !== null &&
			fieldId !== null &&
			isCheckboxChoiceDisabled(formId, fieldId, choiceValue)
		) {
			event.preventDefault();
			inputCheckbox.checked = false;
		}
	});
}

// Function to initialize the event listener
export function initCheckboxHandler(): void {
	document.addEventListener('click', handleCheckboxChoiceAll);
}
