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

const name = 'wc-koin-billet'
const settings = getSetting(`${name}_data`, {});
const defaultLabel = __('Billet - Koin', 'wc-koin-official');

const label = decodeEntities(settings.title) || defaultLabel;
const sandbox = decodeEntities(settings.sandbox || '');
const description = decodeEntities(settings.description || '');
const allowedCountries = decodeEntities(settings.countries || '');
const icon = decodeEntities(settings.icon || '');

const Content = (props) => {
    const handleClick = (e) => {
        e.preventDefault();
        const event = new CustomEvent('koinOpenPopup');
        document.dispatchEvent(event);
    };

    return (
        <>
            <GatewayDescription sandbox={sandbox} description={description} />
            <div className="koin-checkout-fields">
                <div className="koin-checkout-message">
                    <div>
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style={{ width: '20px', height: '20px' }}>
                            <path d="M256 0C114.6 0 0 114.6 0 256s114.6 256 256 256s256-114.6 256-256S397.4 0 256 0zM256 128c17.67 0 32 14.33 32 32c0 17.67-14.33 32-32 32S224 177.7 224 160C224 142.3 238.3 128 256 128zM296 384h-80C202.8 384 192 373.3 192 360s10.75-24 24-24h16v-64H224c-13.25 0-24-10.75-24-24S210.8 224 224 224h32c13.25 0 24 10.75 24 24v88h16c13.25 0 24 10.75 24 24S309.3 384 296 384z" />
                        </svg>
                        <a id="koin-about-link" onClick={handleClick} >
                            {__("How does work", 'wc-koin-official')}&nbsp;
                            <span>{__("Koin's payment in installments?", 'wc-koin-official')}</span>
                            <i>{__("click here", 'wc-koin-official')}</i>.
                        </a>
                    </div>
                </div>
            </div >
        </>
    );
};

const Label = (props) => {
    return (
        <span style={{ width: '100%', display: 'flex', alignItems: 'center', gap: '8px' }}>
            {label}
            {icon && <img src={icon} alt="Koin" style={{ height: '24px' }} />}
        </span>
    );
};

const Billet = {
    name: name,
    label: <Label />,
    content: <Content />,
    edit: <Content />,
    canMakePayment: (args) => allowedCountries.includes(args.billingAddress.country),
    ariaLabel: label,
    supports: {
        features: settings.supports,
    }
};

registerPaymentMethod(Billet);
