import { useEffect, useState, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
const { ExperimentalOrderMeta } = wc.blocksCheckout;

export const Block = ( { checkoutExtensionData, extensions } ) => {

    let isInpostShippingMethod     = false;
    let selectedShippingInstanceID = null;

    const [inpostDeliveryPoint, setInpostDeliveryPoint]         = useState( "" );
    const [inpostDeliveryPointDesc, setInpostDeliveryPointDesc] = useState( "" );
    const { setExtensionData }                                  = checkoutExtensionData;
    const validationErrorId                               = 'inpost-international-delivery-point-error';
    const { setValidationErrors, clearValidationError }         = useDispatch(
        'wc/store/validation'
    );

    // Get current shipping options.
    let shippingRates = useSelect(
        function (select) {
            const store = select( 'wc/store/cart' );
            return store.getShippingRates();
        }
    );

    // State to track pickup selection with both store and DOM monitoring.
    const [isPickupSelected, setIsPickupSelected] = useState(false);

    // Get pickup selection status from store.
    const storePickupSelected = useSelect(
        (select) => {
            const checkoutStore = select('wc/store/checkout');
            const prefersCollection = checkoutStore.prefersCollection();
            return prefersCollection;
        },
        [] // Dependencies array - will re-run when store changes.
    );

    // Update local state when store changes.
    useEffect(() => {
        setIsPickupSelected(storePickupSelected);
    }, [storePickupSelected]);

    // DOM listener for immediate Ship/Pickup changes.
    useEffect(() => {
        const handleShippingMethodChange = () => {
            const container = document.getElementById('shipping-method');
            if ( ! container ) return;

            const allOptions = container.querySelectorAll('.wc-block-checkout__shipping-method-option');
            const selectedOption = container.querySelector('.wc-block-checkout__shipping-method-option--selected');

            if (selectedOption && allOptions.length > 0) {
                // Find the index of the selected option
                const selectedIndex = Array.from(allOptions).indexOf(selectedOption);
                const isPickup = selectedIndex === 1; // Ship = 0, Pickup = 1

                console.log('Selected shipping method index:', selectedIndex);
                console.log('isPickup shipping method:', isPickup);

                if (isPickup) {
                    clearValidationError(validationErrorId);
                }
                setIsPickupSelected(isPickup);
            }
        };

        // Initial check.
        handleShippingMethodChange();

        // Listen for clicks on shipping method container.
        const container = document.getElementById('shipping-method');
        if (container) {
            container.addEventListener('click', (event) => {
                // Small delay to allow DOM to update.
                setTimeout( handleShippingMethodChange, 300 );
            });

            // Also listen for any changes in the container.
            const observer = new MutationObserver(() => {
                handleShippingMethodChange();
            });

            observer.observe(container, {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: ['class']
            });

            return () => {
                observer.disconnect();
            };
        }
    }, []);

    function useInpostConfiguredMethods() {
        if (wcSettings.inpost_intl_block_data && wcSettings.inpost_intl_block_data.configured_methods) {
            return wcSettings.inpost_intl_block_data.configured_methods;
        }
        return [];
    }

    const configured_shipping_methods = useInpostConfiguredMethods();

    if (typeof shippingRates != 'undefined' && shippingRates !== null) {
        let firstObjKey = shippingRates[Object.keys( shippingRates )[0]];
        if (typeof firstObjKey != 'undefined' && firstObjKey !== null) {
            if ( firstObjKey.hasOwnProperty( 'shipping_rates' ) ) {
                const shippingRatesArray           = firstObjKey.shipping_rates;
                const shippingRatesExcludingPickup = [];
                if (typeof shippingRatesArray != 'undefined' && shippingRatesArray !== null) {
                    for (let method of shippingRatesArray) {
                        if (method.method_id === 'pickup_location') {
                            continue;
                        }
                        if (method.selected === true) {

                            selectedShippingInstanceID   = method.instance_id;
                            let selectedShippingMethodID = method.method_id;
                            if (selectedShippingMethodID.indexOf( 'inpost_international_automated_locker_point' ) !== -1) {
                                isInpostShippingMethod = true;
                            } else {
                                let ship_method_data = configured_shipping_methods[selectedShippingInstanceID];
                                if (typeof ship_method_data != 'undefined' && ship_method_data !== null) {
                                    if (ship_method_data.hasOwnProperty( "need_map" )) {
                                        isInpostShippingMethod = true;
                                    }
                                }
                            }
                        }
                        shippingRatesExcludingPickup.push( method );
                    }


                    if ( ! selectedShippingInstanceID && shippingRatesExcludingPickup.length > 0 ) {
                        const shipping_section = document.getElementsByClassName( 'wc-block-components-shipping-rates-control' )[0];
                        if (typeof shipping_section != 'undefined' && shipping_section !== null) {
                            const checkedRadioControl = shipping_section.querySelector( 'input[name^="radio-control-"]:checked' );
                            if (typeof checkedRadioControl != 'undefined' && checkedRadioControl !== null) {
                                let shipping_method_id = checkedRadioControl.getAttribute( 'id' );
                                if (typeof shipping_method_id != 'undefined' && shipping_method_id !== null) {
                                    let shipping_method_data = shipping_method_id.split( ":" );

                                    selectedShippingInstanceID = shipping_method_data[shipping_method_data.length - 1];

                                    let selectedShippingMethodRadioID = shipping_method_data[0];
                                    if (selectedShippingMethodRadioID.indexOf( 'inpost_international_automated_locker_point' ) !== -1) {
                                        isInpostShippingMethod = true;
                                    } else {
                                        let ship_method_data = configured_shipping_methods[selectedShippingInstanceID];
                                        if (typeof ship_method_data != 'undefined' && ship_method_data !== null) {
                                            if (ship_method_data.hasOwnProperty( "need_map" )) {
                                                isInpostShippingMethod = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    // Initial validation error - prevent to place order after Checkout page loaded, and we have empty value in inpost hidden input (no point code yet).
    const initialValiadtion = useCallback(
        function () {
            if ( isInpostShippingMethod && ! inpostDeliveryPoint ) {
                console.log('block_order');
                setValidationErrors(
                    {
                        [validationErrorId]: {
                            message: __( 'Parcel locker must be chosen.', 'inpost-international' ),
                            hidden: true,
                        },
                    }
                );
            }
        },
        [inpostDeliveryPoint, setValidationErrors, clearValidationError, isInpostShippingMethod]
    );


    // Additional validation: clear validation error if we have value for inpost hidden input with point code.
    const validateInput = useCallback(
        function () {
            if (inpostDeliveryPoint || ! isInpostShippingMethod) {
                clearValidationError( validationErrorId );
                return true; // Allow order placement.
            }
        },
        [inpostDeliveryPoint, setValidationErrors, clearValidationError, isInpostShippingMethod]
    );


    // Effect to validate input whenever Delivery Point input value changes.
    useEffect(
        function () {
            initialValiadtion();
            validateInput();
            setExtensionData( "inpost_intl", "inpost-international-locker-id", inpostDeliveryPoint );
            setExtensionData( "inpost_intl", "inpost-international-locker-description", inpostDeliveryPointDesc );
        },
        [inpostDeliveryPoint, inpostDeliveryPointDesc, setExtensionData, validateInput]
    );


    const [ shippingMethods, setShippingMethods ] = useState( [] );

    useEffect(
        function () {
            // Function to get shipping methods from the DOM.
            const getShippingMethods = function () {
                const shipping_block_html = document.querySelector(
                    '.wc-block-components-shipping-rates-control'
                );
                if (shipping_block_html) {
                    const shipping_radio_buttons = shipping_block_html.querySelectorAll(
                        'input[name^="radio-control-"]'
                    );
                    return Array.from( shipping_radio_buttons ).map(
                        function (radio) {
                            return {
                                id: radio.id,
                                value: radio.value,
                                checked: radio.checked
                            };
                        }
                    );
                }
                return [];
            };

            // Update shipping methods.
            const updateShippingMethods = function () {
                setShippingMethods( getShippingMethods() );
            };

            // Initial update.
            updateShippingMethods();

            // Set up a MutationObserver to watch for DOM changes.
            const observer = new MutationObserver( updateShippingMethods );
            observer.observe( document.body, { subtree: true, childList: true } );

            // Cleanup function.
            return () => observer.disconnect();
        },
        []
    );

    useEffect(
        function () {
            // Function to add Inpost icons.
            const showInpostButton = () => {

                let inpost_methods = [];

                if (typeof window.inpost_intl_frontend != 'undefined' && window.inpost_intl_frontend !== null) {
                    if ( window.inpost_intl_frontend.inpost_methods ) {
                        inpost_methods = window.inpost_intl_frontend.inpost_methods;
                    }
                }

                let is_inpost_method_checked = false;

                shippingMethods.forEach(function(method) {
                    if (method.value && method.value.indexOf(':') > -1) {
                        const [shipping_method, instance_id] = method.value.split(':');
                        if (shipping_method.indexOf('inpost_international_automated_locker_point') !== -1) {
                            if (method.checked) {
                                is_inpost_method_checked = true;
                            }
                        }
                    }
                });

                if (is_inpost_method_checked) {
                    const map_button = document.getElementById('inpost_intl_show_geowidget');
                    if (map_button) {
                        map_button.style.display = 'block';
                    }
                }


                shippingMethods.forEach(function(method) {
                    if (method.value && method.value.indexOf(':') > -1) {
                        const [shipping_method, instance_id] = method.value.split(':');
                        let inpost_logo = false;
                        let delivery_terms = false;
                        if (typeof inpost_methods != 'undefined' && inpost_methods !== null) {
                            let inpost_method_data = inpost_methods[instance_id];
                            if (typeof inpost_method_data != 'undefined' && inpost_method_data !== null) {
                                if( 'inpost_icon' in inpost_method_data ) {
                                    let logo_src = inpost_method_data.inpost_icon;

                                    if ( logo_src && typeof logo_src != 'undefined' && logo_src !== null ) {
                                        inpost_logo = logo_src;
                                    }
                                }

                                if( 'delivery_terms' in inpost_method_data && inpost_method_data.delivery_terms ) {
                                    delivery_terms = inpost_method_data.delivery_terms;
                                }
                            }
                        }

                        const title_span = document.querySelector(
                            `span[id="${method.id}__label"]`
                        );

                        let shipping_info = false;

                        if (inpost_logo || delivery_terms ) {
                            shipping_info = `<span class="inpost_intl-shipping-method-meta-wrap">`;
                            if (inpost_logo) {
                                shipping_info += `<span class="inpost_intl-shipping-method-meta-wrap"><span class="inpost-intl-block-shipping-meta inpost-intl-shipping-method-logo">`;
                                shipping_info += `<img class="inpost_icon" src="${inpost_logo}" alt="inpost icon" style="height:35px;width:auto;display:block">`;
                                shipping_info += `</span>`;
                            }

                            if (delivery_terms) {
                                shipping_info += `<span class="inpost-intl-block-shipping-meta inpost-intl-shipping-terms">`;
                                shipping_info += delivery_terms;
                                shipping_info += `</span>`;
                            }

                            shipping_info += `</span>`;
                        }

                        if (shipping_info && title_span && !title_span.querySelector('.inpost_intl-shipping-method-meta-wrap')) {
                            title_span.insertAdjacentHTML('beforeend', shipping_info);
                        }
                    }
                });
            };

            showInpostButton();
        },
        [ shippingMethods ]
    );

    // Change Delivery Point input value.
    const handleDeliveryPointChange = function (event) {
        const selectedId = event.target.value;
        setInpostDeliveryPoint( selectedId );
    };


    // Change Delivery Point Description input value.
    const handleDeliveryPointDescChange = function (event) {
        const pointDescription = event.target.value;
        setInpostDeliveryPointDesc( pointDescription );
    };

    return (
        <>
            {
                <>
                    <button className="button alt inpost_intl_show_geowidget" id="inpost_intl_show_geowidget">
                        {__( 'Choose pick-up point', 'inpost-international' )}
                    </button>
                    <div id="inpost_intl_selected_point_data_wrap" className="inpost_intl_selected_point_data_wrap"
                         style={{display: 'none'}}>
                    </div>
                    <ExperimentalOrderMeta>
                        <PointLockerInput
                            inpostDeliveryPoint       = {inpostDeliveryPoint}
                            inpostDeliveryPointDesc       = {inpostDeliveryPointDesc}
                            handleDeliveryPointChange = {handleDeliveryPointChange}
                            handleDeliveryPointDescChange= {handleDeliveryPointDescChange}
                        />
                    </ExperimentalOrderMeta>
                </>
            }
        </>
    );


};


function PointLockerInput({ handleDeliveryPointChange, handleDeliveryPointDescChange, inpostDeliveryPoint, inpostDeliveryPointDesc }) {

    return (
        <div className="inpost-parcel-locker-wrap" style={{display: 'none'}}>
            <input
                value={inpostDeliveryPoint}
                type="text"
                id="inpost-international-locker-id"
                onChange={handleDeliveryPointChange}
            />
            <input
                value={inpostDeliveryPointDesc}
                type="text"
                id="inpost-international-locker-description"
                onChange={handleDeliveryPointDescChange}
            />
        </div>
    );
}
