import { decodeEntities } from '@wordpress/html-entities'
import { __ } from '@wordpress/i18n'
import { registerPaymentMethod } from '@woocommerce/blocks-registry'
import { getSetting } from '@woocommerce/settings'
import {useEffect} from "@wordpress/element";

const settings = getSetting('computop_amazonpay_data', {})
const gatewayTitle = settings?.title || __('Amazon Pay', 'computop-payments')
const gatewayName = settings?.id || 'computop_amazonpay'
const gatewayDescription = settings?.description || ''


const AmazonPayContent = ({ eventRegistration, emitResponse }) => {
    const { onCheckoutSuccess } = eventRegistration;
    useEffect(() => {
        /**
         * @param {Object} onCheckoutProcessingData - Checkout processing data from WooCommerce
         * @param {string} onCheckoutProcessingData.redirectUrl - URL to redirect to after checkout
         * @param {number} onCheckoutProcessingData.orderId - WooCommerce order ID
         * @param {number} onCheckoutProcessingData.customerId - WooCommerce customer ID
         * @param {string} onCheckoutProcessingData.orderNotes - Additional order notes
         * @param {Object} onCheckoutProcessingData.processingResponse - Processing response data
         */
        const unsubscribe = onCheckoutSuccess((onCheckoutProcessingData) => {
            console.log(JSON.stringify(onCheckoutProcessingData, null, 2));
            const paymentData = JSON.parse(onCheckoutProcessingData.processingResponse.paymentDetails.paymentDataJson);
            computopStartAmazonPay(paymentData);
            return {
                retry: true
            }
        });
        return unsubscribe
    }, [onCheckoutSuccess])


    return (
        <div>
            {gatewayDescription && <p>{gatewayDescription}</p>}
            <div id="cpt-amazon-pay-button"></div>
        </div>
    )
}

registerPaymentMethod({
    name: gatewayName,
    label: (
        <div>
            <span className='wc-block-components-payment-method-label'>
                {gatewayTitle}
            </span>
        </div>
    ),
    content: <AmazonPayContent />,
    edit: <AmazonPayContent />,
    canMakePayment: () => true,
    ariaLabel: decodeEntities(gatewayTitle),
    supports: {
        features: settings?.supports || ['products'],
        showSavedCards: false,
        showSaveOption: false
    }
})
