/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n'

/**
 * Rule Form Extension
 */
const ruleFormExtension = ( ruleForm ) => {
	if ( ! ruleForm ) {
		return;
	}

	// exit if not on rules page
	const isRulesPage = ruleForm.querySelector( '.conditions-measure' ) ||
	   document.body.classList.contains( 'post-type-personalizewp_rule' ) ||
	   ruleForm.classList.contains( 'personalizewp-rules-form' );

	if ( ! isRulesPage ) {
		return;
	}

	const autocompleteConditions = window.pwpRuleFormEx?.autocomplete_conditions || [
		'woocommerce_product_stock_level',
		'woocommerce_product_quantity_in_cart',
		'woocommerce_category_quantity_in_cart'
	];

	/**
	 * Check if a condition identifier is an autocomplete condition
	 */
	const isAutocompleteCondition = ( conditionId ) => {
		return autocompleteConditions.includes( conditionId );
	};

	/**
	 * Extract numeric ID from autocomplete value
	 */
	const extractNumericId = ( value ) => {
		if ( ! value ) return '';

		// If it's already numeric, return as is
		if ( /^\d+$/.test( value ) ) {
			return value;
		}

		const match = value.match( /:(\d+)$/ );
		return match ? match[1] : value;
	};

	/**
	 * Update the comma-separated values input field
	 */
	const updateCommaSeparatedInput = ( autocompleteElement ) => {
		const condition = autocompleteElement.closest( '.condition' );
		const hiddenInput = condition?.querySelector( '.rule-condition-values' );

		if ( ! hiddenInput ) {
			return;
		}

		// access the selectedItems property
		const selectedItems = autocompleteElement.selectedItems || [];
		const values = selectedItems
			.map( item => extractNumericId( item.value || item.id ) )
			.filter( Boolean );

		const newValue = values.join( ',' );

		// Only update if the value has changed to avoid unnecessary updates
		if ( hiddenInput.value !== newValue ) {
			hiddenInput.value = newValue;
		}
	};

	/**
	 * Configure field visibility based on condition type
	 */
	const configureFieldVisibility = ( condition, isAutocomplete ) => {
		const autocompleteWrapper = condition.querySelector( '.autocomplete-field-wrapper' );

		if ( isAutocomplete ) {
			// Show autocomplete field
			if ( autocompleteWrapper ) {
				autocompleteWrapper.style.display = 'block';
			}

			// Hide AND disable the base plugin's meta_value text fields
			const metaValueWrappers = condition.querySelectorAll( '.meta-text-field-wrapper, .meta-value-wrapper' );
			metaValueWrappers.forEach( wrapper => {
				wrapper.style.display = 'none';
				const input = wrapper.querySelector( 'input[name*="[meta_value]"]' );
				if ( input ) {
					input.disabled = true;
					input.value = '';
				}
			} );
		} else if ( autocompleteWrapper ) {
			// Only hide autocomplete field
			autocompleteWrapper.style.display = 'none';

			// Un-disable meta inputs
			const metaValueWrappers = condition.querySelectorAll( '.meta-text-field-wrapper, .meta-value-wrapper' );
			metaValueWrappers.forEach( wrapper => {
				const input = wrapper.querySelector( 'input[name*="[meta_value]"]' );
				if ( input ) {
					input.disabled = false;
				}
			} );
		}
	};

	/**
	 * Setup autocomplete field for new conditions
	 */
	const setupAutocompleteForNewCondition = ( condition, conditionId ) => {
		const template = document.getElementById( `pwp-autocomplete-template-${conditionId}` );

		if ( ! template ) {
			return;
		}

		const templateContent = template.content.cloneNode( true );
		const autocompleteWrapper = templateContent.querySelector( '.autocomplete-field-wrapper' );

		if ( autocompleteWrapper ) {
			const insertBefore = condition.querySelector( '.conditions-comparator' );
			if ( insertBefore ) {
				insertBefore.before( autocompleteWrapper );
			}
			updateValuePlaceholder( condition );

			configureFieldVisibility( condition, true );
		}
	};

	/**
	 * Hack to update the value input with the correct placeholder depending on the condition measure.
	 *
	 * ToDo: Remove this, instead use better form condition action/filters
	 */
	const updateValuePlaceholder = ( condition ) => {
		const measureSelect = condition.querySelector( '.conditions-measure' );
		const measureValue = measureSelect?.value;
		const valueInput = condition.querySelector( '.text-field-wrapper .field-value-text' );
		let valuePlaceholder = null;

		switch ( measureValue ) {
			case 'woocommerce_product_quantity_in_cart':
				valuePlaceholder = __( 'Number of products', 'personalizewp' );
				break;

			case 'woocommerce_category_quantity_in_cart':
				valuePlaceholder = __( 'Number of products from category', 'personalizewp' );
				break;

			default:
				const resetPlaceholder = valueInput.getAttribute( 'data-initial-placeholder' );
				if ( resetPlaceholder ) {
					valuePlaceholder=resetPlaceholder;
				}

				break;
		}
		if ( valuePlaceholder && valueInput ) {
			if ( ! valueInput.getAttribute( 'data-initial-placeholder' ) ) {
				valueInput.setAttribute( 'data-initial-placeholder', valueInput.placeholder );
			}
			valueInput.placeholder = valuePlaceholder;
		}
	};

	/**
	 * Update autocomplete attributes when switching condition types using public APIs only
	 */
	const updateAutocompleteAttributes = ( autocompleteElement, conditionId ) => {
		// Configuration for each condition type
		const configs = {
			'woocommerce_product_stock_level': {
				mode: 'product',
				'content-types': 'products',
				placeholder: __( 'Search for a product', 'personalizewp' ),
			},
			'woocommerce_product_quantity_in_cart': {
				mode: 'product',
				'content-types': 'products',
				placeholder: __( 'Search for a product', 'personalizewp' ),
			},
			'woocommerce_category_quantity_in_cart': {
				mode: 'product',
				'content-types': 'categories',
				placeholder: __( 'Search for a category', 'personalizewp' ),
			}
		};

		const config = configs[ conditionId ];
		if ( ! config || ! autocompleteElement ) {
			return;
		}

		// Update attributes
		autocompleteElement.setAttribute( 'mode', config.mode );
		autocompleteElement.setAttribute( 'placeholder', config.placeholder );
		autocompleteElement.removeAttribute( 'taxonomy' );
		autocompleteElement.setAttribute( 'content-types', config['content-types'] );

		// Reset component to apply new configuration
		setTimeout( () => {
			autocompleteElement.removeAttribute( 'disabled' );
			if ( typeof autocompleteElement.resetAll === 'function' ) {
				autocompleteElement.resetAll();
			}
		}, 10 );
	};

	/**
	 * Initialize autocomplete fields for existing conditions
	 */
	const initializeExistingConditions = () => {
		const conditions = ruleForm.querySelectorAll( '.condition' );

		conditions.forEach( condition => {
			const measureSelect = condition.querySelector( '.conditions-measure' );
			const measureValue = measureSelect?.value;

			// Only handle autocomplete conditions
			if ( measureValue && isAutocompleteCondition( measureValue ) ) {
				// Shift ordering of components, ToDo: Remove this, instead use better form condition action/filters
				const autocompleteWrapper = condition.querySelector( '.autocomplete-field-wrapper' );
				const insertBefore = condition.querySelector( '.conditions-comparator' );
				if ( insertBefore ) {
					insertBefore.before( autocompleteWrapper );
				}
				updateValuePlaceholder( condition );

				configureFieldVisibility( condition, true );
			}
		} );
	};

	// Event Listeners

	// Handle condition type changes
	ruleForm.addEventListener( 'change', ( event ) => {
		if ( ! event.target.classList.contains( 'conditions-measure' ) ) {
			return;
		}

		const condition = event.target.closest( '.condition' );
		const measureValue = event.target.value;
		const isAutocomplete = isAutocompleteCondition( measureValue );

		if ( isAutocomplete ) {
			// Check if autocomplete field already exists
			const autocompleteWrapper = condition.querySelector( '.autocomplete-field-wrapper' );
			const existingAutocomplete = condition.querySelector( 'auto-complete.rule-condition-autocomplete' );

			if ( ! autocompleteWrapper ) {
				// Create autocomplete field from template
				setupAutocompleteForNewCondition( condition, measureValue );
			} else {
				// Update existing autocomplete for new condition type
				if ( existingAutocomplete ) {
					updateAutocompleteAttributes( existingAutocomplete, measureValue );
				}
				configureFieldVisibility( condition, true );
			}
		} else {
			const existingAutocomplete = condition.querySelector( 'auto-complete.rule-condition-autocomplete' );
			if ( existingAutocomplete && typeof existingAutocomplete.resetAll === 'function' ) {
				existingAutocomplete.resetAll();
			}
			configureFieldVisibility( condition, false );
		}
		updateValuePlaceholder( condition );
	} );

	const syncAutoCompleteItemsToMetaInputs = ( event ) => {
		// Update all autocomplete fields before submitting
		const autocompleteElements = ruleForm.querySelectorAll( 'auto-complete.rule-condition-autocomplete' );
		autocompleteElements.forEach( updateCommaSeparatedInput );
	};
	// Ensure all autocomplete values are updated before form submission
	ruleForm.addEventListener( 'submit', syncAutoCompleteItemsToMetaInputs );

	// Ensure we have auto complete items before submitting
	const validateAutoCompleteItems = ( event, data ) => {
		const actions = ruleForm.querySelector('#form-actions');
		if ( data?.detail?.items?.length && actions ) {
			jQuery(actions).show();
		} else if ( actions ) {
			jQuery(actions).show();
		}
		syncAutoCompleteItemsToMetaInputs();
	};
	ruleForm.addEventListener( 'pwp-auto-complete:remove-item', validateAutoCompleteItems );
	ruleForm.addEventListener( 'pwp-auto-complete:add-item', validateAutoCompleteItems );


	// Initialize on load
	initializeExistingConditions();
};

export default ruleFormExtension;
