import { useBoundStore } from './store/store';

function productHasQuantityField(fieldId: number, form: GFForm) {
	for (const field of form.fields) {
		if (
			// @ts-ignore
			field.type === 'quantity' &&
			String(field.productId) === String(fieldId)
		) {
			return true;
		}
	}

	return false;
}

function isQtyField(fieldId: string) {
	const field = window.GetFieldById(fieldId);
	// @ts-ignore
	return field && field.type === 'quantity';
}

function isCustomQtyField(fieldId: string) {
	// check for actual field IDs cheaply
	if (!isNaN(parseInt(fieldId))) {
		return false;
	}

	// check of our quantity_X tag
	const regex = /(quantity)_([0-9]+)/;
	const match = regex.exec(fieldId);

	if (!match || match[1] !== 'quantity') {
		return false;
	}

	return true;
}

export function setupHooks() {
	window.gform.addFilter('gform_conditional_object', (object, objectType) => {
		if (objectType !== 'pricing_level') {
			return object;
		}

		return useBoundStore.getState().getActivePricingLevel();
	});

	window.gform.addFilter(
		'gform_conditional_logic_description',
		(description, descPieces, objectType, object) => {
			// read the current user entered price from the DOM and use that to re-render
			// the input in the description.
			const currentPrice = jQuery(
				'#gwcp-pricing-level-price'
			).val() as string;

			const priceNumber = currentPrice
				? Number(currentPrice)
				: window.gformToNumber(object.price);

			descPieces.objectDescription = `This product costs  <input type="text" class="gf_money" id="gwcp-pricing-level-price" value="${priceNumber}" /> if `;

			return Object.values(descPieces).join(' ');
		}
	);

	window.gform.addFilter(
		'gform_conditional_logic_fields',
		(options, form) => {
			for (const field of form.fields) {
				if (
					field.type !== 'product' ||
					field.inputType !== 'singleproduct' ||
					productHasQuantityField(field.id, form) ||
					field.disableQuantity
				) {
					continue;
				}

				options.push({
					label: `${
						field.adminLabel ? field.adminLabel : field.label
					} (Quantity)`,
					value: `quantity_${field.id}`,
				});
			}

			return options;
		}
	);

	window.gform.addFilter(
		'gform_conditional_logic_operators',
		(operators, objectType, fieldId) => {
			if (!isQtyField(fieldId) && !isCustomQtyField(fieldId)) {
				return operators;
			}

			return {
				is: 'is',
				isnot: 'isNot',
				'>': 'greaterThan',
				'<': 'lessThan',
			};
		}
	);

	window.gform.addFilter(
		'gform_conditional_logic_values_input',
		(inputHtml, objectType, ruleIndex, selectedFieldId, selectedValue) => {
			const field = window.GetFieldById(selectedFieldId);

			if (
				field &&
				['multiselect', 'checkbox', 'dropdown'].includes(
					window.GetInputType(field)
				)
			) {
				const ruleChoices = [
					{ text: window.gf_vars.emptyChoice, value: '' },
					...(field.choices ?? []),
				];

				return window.GetRuleValuesDropDown(
					ruleChoices,
					objectType,
					ruleIndex,
					selectedValue,
					false
				);
			}

			if (
				!isQtyField(selectedFieldId) &&
				!isCustomQtyField(selectedFieldId)
			) {
				return inputHtml;
			}

			if (!selectedValue) {
				selectedValue = '';
			}

			const setRuleProp =
				'SetRuleProperty("' +
				objectType +
				'", ' +
				ruleIndex +
				', "value", jQuery(this).val());';
			const inputId = `${objectType}_rule_value_${ruleIndex}`;

			return `
            <input
                type='number'
                placeholder='Enter Quantity'
                class='gfield_rule_select'
                id='${inputId}'
                value='${selectedValue.replace(/'/g, '&#039;')}' \
				onchange='${setRuleProp}' \
				onkeyup='${setRuleProp}'
            >
       		`;
		}
	);
}
