/**
 * Class for handling DATE_SETTINGS field functionality in Elementor forms.
 */
class DATE_SETTINGS extends elementorModules.frontend.handlers.Base {

    /**
     * Retrieves the default DATE_SETTINGS field functionality.
     * @returns {Object} An object containing DATE_SETTINGSor configurations.
     */
    getDefaultSettings() {
        return {
            selectors: {
                dateElement: '.elementor-field-type-date',
            },
        };
    }

    /**
     * Retrieves the default elements based on the settings defined.
     * @returns {Object} An object containing jQuery elements for the DATE_SETTINGS field.
     */
    getDefaultElements() {
        const selectors = this.getSettings('selectors');
        return {
            $dateElement: this.$element.find(selectors.dateElement),
        };
    }  

    /**
     * Binds events to the elements. This method is intended to be overridden by subclasses to add specific event handlers.
     */
    bindEvents() {
        this.initialise();
        this.onChangeEvent(); 
    }

    /**
     * Retrieves and stores unique DATE_SETTINGS input IDs from the Elementor div element.
     */
    initialise(){
        const divWrapperElement = this.elements.$dateElement;
        const divEditorObject = jQuery(divWrapperElement);
        divEditorObject.each((index, element) => { 
            const $element = jQuery(element);
            const elementInput = $element[0].querySelector('input');
            this.getData(elementInput);
        });
    }

    getData(elementInput){
        let fieldId = "";
        // Use getAttribute instead of attr for vanilla JavaScript elements
        fieldId = elementInput.getAttribute('ccfef_fieldId') ? elementInput.getAttribute('ccfef_fieldId') : false;
        if(fieldId){
            let minId = elementInput.getAttribute('ccfef_link_min_fieldid');
            let maxId = elementInput.getAttribute('ccfef_link_max_fieldid');
            let fieldVal = elementInput.value;
            this.changeAttributes(elementInput,minId,maxId,fieldVal);

        }else{
            const classList = elementInput.className.split(' ');
            const ccfefClasses = classList.filter(cls => cls.startsWith('ccfef'));
            // Function to extract attribute value by name
                function getAttributeValue(array, attributeName) {
                    const regex = new RegExp(`${attributeName}="(.*?)"`);
                    const attribute = array.find(cls => regex.test(cls));
                    return attribute ? attribute.match(regex)[1] : null;
                }
                // Example usage
                let minId = getAttributeValue(ccfefClasses, 'ccfef_link_min_fieldId');
                let maxId = getAttributeValue(ccfefClasses, 'ccfef_link_max_fieldId');
                let fieldVal = elementInput.value;
                this.changeAttributes(elementInput,minId,maxId,fieldVal);    
            }
        }



    changeAttributes(elementInput,minId,maxId,fieldValue=""){
        // let minattr = elementInput.getAttribute('min');
        // let maxattr = elementInput.getAttribute('max');

        if(minId){
            let linkedMinField  = jQuery(`.elementor-field-type-date #form-field-${minId}`)[0];
            // Look for field inside the class for editor side
        if (!linkedMinField) {  
            linkedMinField = jQuery(`.elementor-field-type-date .ccfef_link_min_fieldId_${minId}`)[0];
        }  

        if (!linkedMinField) {
            
        }else{
            let linkedMinFieldAttr_min = linkedMinField.getAttribute('min');
            let linkedMinFieldAttr_max = linkedMinField.getAttribute('max');
            let linkedMinFieldValue_min = linkedMinField.value;

            if (linkedMinFieldAttr_min) {
                elementInput.setAttribute('min', linkedMinFieldAttr_min);
            }

            if (linkedMinFieldValue_min) {
                if (linkedMinFieldAttr_min === null || linkedMinFieldValue_min > linkedMinFieldAttr_min) {
                    elementInput.setAttribute('min', linkedMinFieldValue_min);
                }
            }

            if(linkedMinFieldAttr_max){
            if (linkedMinFieldAttr_max < fieldValue) {
                linkedMinField.setAttribute('max', fieldValue);
                }
            }
            }
        }

        if(maxId){
        let linkedMaxField = jQuery(`.elementor-field-type-date #form-field-${maxId}`)[0];
        // Look for field inside the class for editor side
        if (!linkedMaxField) {  
            linkedMaxField = jQuery(`.elementor-field-type-date .ccfef_link_max_fieldId_${maxId}`)[0];
        }  

        if(!linkedMaxField){ 

        }else{
            let linkedMaxFieldAttr_max = linkedMaxField.getAttribute('max');
            let linkedMaxFieldValue_max = linkedMaxField.value;
            let linkedMaxFieldAttr_min = linkedMaxField.getAttribute('min'); 

            if (linkedMaxFieldAttr_max) {
                elementInput.setAttribute('max', linkedMaxFieldAttr_max);
            }

            if (linkedMaxFieldValue_max) {
                if (linkedMaxFieldAttr_max === null || linkedMaxFieldValue_max < linkedMaxFieldAttr_max) {
                    elementInput.setAttribute('max', linkedMaxFieldValue_max);
                }
            }

            if(linkedMaxFieldAttr_min){
                if (linkedMaxFieldAttr_min < fieldValue) {
                    linkedMaxField.setAttribute('min', fieldValue);
                }
            }
        }
    }
    this.initializeFlatpickr(elementInput); // intialize flatpikr
}

initializeFlatpickr(inputElement) {
    const minDate = inputElement.getAttribute('min');
    const maxDate = inputElement.getAttribute('max');

    // Avoid reinitialization if Flatpickr already exists
    if (inputElement._flatpickr) {
        inputElement._flatpickr.set({
            minDate: minDate || null,
            maxDate: maxDate || null,
        });
        return; // Exit early if already initialized
    }

    // Initialize Flatpickr with updated min and max
    flatpickr(inputElement, {
        minDate: minDate || null,
        maxDate: maxDate || null,
        dateFormat: "Y-m-d", // Adjust format as needed
        onChange: (selectedDates, dateStr) => {
            jQuery(inputElement).trigger('change'); 
            inputElement._flatpickr.open();
        },

    });
    }      

    onChangeEvent() {
    // Common handler function to avoid repetition
    const handleEvent = (e) => {
        const $inputElement = jQuery(e.currentTarget);
        let elementInput = $inputElement[0];
        
        if (!elementInput._flatpickr) {
            this.initializeFlatpickr(elementInput);
        }
        this.getData(elementInput);

    };

    const dateInputs = jQuery('.elementor-field-type-date input');
    dateInputs.on('focus', handleEvent); 
}
}

jQuery(window).on('elementor/frontend/init', () => {
    const addHandler = ($element) => {
        elementorFrontend.elementsHandler.addHandler(DATE_SETTINGS, {
            $element,
        });
    };

    elementorFrontend.hooks.addAction('frontend/element_ready/form.default', addHandler);
});

