import { getSetting } from '@woocommerce/settings';
import { createElement, useEffect } from '@wordpress/element';
import { registerPaymentMethod } from '@woocommerce/blocks-registry';

// ============================================
// Configuration & Constants
// ============================================

const identifier = 'ipag-gateway_pix';
const settings = getSetting(`${identifier}_data`, {});
const labelText = settings.title || 'Pague com PIX';
const defaultDescription = 'Confirm your order to view the qrcode.';
const contentText = settings.description || defaultDescription;

// ============================================
// UI Components
// ============================================

const Label = ({ components }) => {
  const { PaymentMethodLabel } = components;

  return createElement(
    'div',
    { className: 'ipag-label-with-badge' },
    createElement(PaymentMethodLabel, {
      className: 'ipag-gateway-pix-label',
      text: labelText,
    }),
    createElement('img', {
      src: settings.assets_url
        ? `${settings.assets_url}../images/ipag.png`
        : '/wp-content/plugins/ipag-gateway/images/ipag.png',
      alt: 'iPag',
      className: 'ipag-label-badge',
      title: 'Pagamentos seguros com iPag',
    }),
  );
};

const Content = ({ eventRegistration, emitResponse }) => {
  const { onPaymentSetup } = eventRegistration;

  useEffect(() => {
    const unsubscribe = onPaymentSetup(() => {
      return {
        type: emitResponse.responseTypes.SUCCESS,
        meta: {
          paymentMethodData: {
            ipag_woo_payments_blocks: 'yes',
          },
        },
      };
    });

    return unsubscribe;
  }, [onPaymentSetup, emitResponse.responseTypes.SUCCESS]);

  return createElement(
    'div',
    { className: 'ipag-gateway-credit-form' },
    createElement(
      'div',
      { className: 'ipag-boleto-description' },
      createElement('p', {}, contentText),
    ),
  );
};

// ============================================
// Payment Method Registration
// ============================================

registerPaymentMethod({
  name: identifier,
  label: createElement(Label),
  content: createElement(Content),
  edit: createElement(Content),
  canMakePayment: () => true,
  ariaLabel: labelText,
  shouldSavePaymentMethod: () => false,
});
