import {registerPlugin} from '@wordpress/plugins';
import apiFetch from '@wordpress/api-fetch';
import {useSelect, dispatch, select} from "@wordpress/data";
import {useEffect} from "@wordpress/element";
import {addQueryArgs} from '@wordpress/url'
import {registerCheckoutFilters,ExperimentalDiscountsMeta} from '@woocommerce/blocks-checkout';
import axios from 'axios';

const maybeAddCoupon = (cartData) => {
    const appliedCoupons = cartData.coupons;
    const extension = cartData.extensions.yith_dynamic_wc_block_manager;

    const yithDynamicCoupon = appliedCoupons.filter(coupon => coupon.code === extension.ywdpd_coupon_code).shift();

    if (!yithDynamicCoupon?.code) {
        apiFetch({
            path: addQueryArgs('/wc/store/v1/cart/apply-coupon', {
                code: extension.ywdpd_coupon_code,
                context: 'yith_dynamic_block'
            }),
            method: 'POST',
            cache: 'no-store',
        }).then((result) => {
            dispatch('wc/store/cart').receiveCart(result);
        }).catch((error) => {
            dispatch('wc/store/cart').receiveError(error);
        });
    }
}

const maybeRemoveCoupon = (cartData) => {
    const appliedCoupons = cartData.coupons;
    const extension = cartData.extensions.yith_dynamic_wc_block_manager;
    const yithDynamicCoupon = appliedCoupons.filter(coupon => coupon.code === extension.ywdpd_coupon_code).shift();
    if (yithDynamicCoupon?.code) {
        apiFetch({
            path: addQueryArgs('/wc/store/v1/cart/remove-coupon', {
                code: yithDynamicCoupon.code,
                context: 'yith_dynamic_block'
            }),
            method: 'POST',
            cache: 'no-store',
        }).then((result) => {
            dispatch('wc/store/cart').receiveCart(result);
        }).catch((error) => {
            dispatch('wc/store/cart').receiveError(error);
        });
    }
}
const render = () => {
    const cartData = useSelect((select) => select('wc/store/cart').getCartData());

    useEffect(() => {
        const extension = cartData.extensions?.yith_dynamic_wc_block_manager;
      if( cartData.items.length > 0 && extension?.ywdpd_can_add_coupon  ) {

          if( 'yes' === extension.ywdpd_can_add_coupon) {
              maybeAddCoupon(cartData);
          }else{
              maybeRemoveCoupon(cartData);
          }
      }
    }, [cartData]);


}

registerPlugin('yith-dynamic-discount-manager', {
    render,
    scope: 'woocommerce-checkout',
})
const filterCoupons = (coupons) => {
    const cartData =  select('wc/store/cart').getCartData();
    const extension= cartData.extensions?.yith_dynamic_wc_block_manager;
    return coupons.map((coupon) => {
        if ( !extension?.ywdpd_coupon_code || coupon.code !== extension.ywdpd_coupon_code ) {
            return coupon;
        }
        let label = extension.ywdpd_coupon_label;
        return {
            ...coupon,
            label:label
        }
    });
};

registerCheckoutFilters('yith-dynamic-rename-coupon', {
    coupons: filterCoupons,
});

const storePaymentMethod = async (paymentMethod)=>{
    let formData = new FormData();
      formData.append('action', ywdpd_ajax_args.action );
      formData.append( 'security',ywdpd_ajax_args.nonce );
      formData.append( 'paymentMethod', paymentMethod );


try {
   const response = await axios.post(ywdpd_ajax_args.ajaxURL, formData);
    dispatch('wc/store/cart').receiveCart(response.data);
}catch (error){
    console.log(error);
}

}
const updatePaymentMethod = () =>{
    const selectedPaymentMethod = useSelect((select) => select('wc/store/payment').getActivePaymentMethod() );

    useEffect(()=>{
        storePaymentMethod(selectedPaymentMethod);
    },[selectedPaymentMethod])

}

registerPlugin('yith-dynamic-update-payment-method', {
    render:updatePaymentMethod,
    scope: 'woocommerce-checkout',
})



const totalCartDiscount = () => {
    const cartData =  select('wc/store/cart').getCartData();
    const extension= cartData.extensions?.yith_dynamic_wc_block_manager;
    if( extension?.ywdpd_total_discount_message && extension.ywdpd_total_discount_message !=='') {
        return (
            <ExperimentalDiscountsMeta>
                <div class="wc-block-components-totals-wrapper">
                    {extension.ywdpd_total_discount_message}
                </div>
            </ExperimentalDiscountsMeta>
        );
    }
}

registerPlugin('yith-dynamic-total-discount-message', {
    render:totalCartDiscount,
    scope: 'woocommerce-checkout',
})