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

const settings = getSetting('wc_gateway_precisionpay_data', {});

const defaultLabel = __('PrecisionPay', 'woo-gutenberg-products-block');

const id = decodeEntities(settings.id) || 'wc_gateway_precisionpay';
const label = decodeEntities(settings.title) || defaultLabel;
const logo = decodeEntities(settings.logo) || '';
const buttonLogo = decodeEntities(settings.buttonLogo) || '';
const buttonTitle = decodeEntities(settings.buttonTitle) || '';
const description = decodeEntities(settings.description) || '';
const brandColor = decodeEntities(settings.brandColor) || '';
const wpNonceName = decodeEntities(settings.wpNonceName) || '';
const wpNonce = decodeEntities(settings.wpNonce) || '';
const isTestMode = decodeEntities(settings.isTestMode);
const hasAPIKeys = decodeEntities(settings.hasAPIKeys);
const loadingIconLong = ''; // ToDo: add this

/**
 * Wordpress Nonce component
 */
const WPNonce = () => {
  return <input type="hidden" id={wpNonceName} name={wpNonceName} value={wpNonce} />;
};

/**
 * Content Component
 */
const Content = (props) => {
  const { eventRegistration, emitResponse } = props;
  const { onPaymentSetup, onCheckoutFail } = eventRegistration;

  useEffect(() => {
    // Code to run when the payment gateway is loaded/selected
    const usePrecisionPayPaymentGateway = window.usePrecisionPayPaymentGateway;

    // useEffect still getting called before the main js (with usePreicsionPayPaymentGateway fuction) when PrecisionPay is the only payment gateway
    if (!usePrecisionPayPaymentGateway) {
      setTimeout(activateGateway, 500);
    } else {
      activateGateway();
    }

    function activateGateway() {
      const $ = window.jQuery;
      const usePrecisionPayPaymentGateway = window.usePrecisionPayPaymentGateway;
      if (!$ || !usePrecisionPayPaymentGateway) {
        console.error('Missing either jQuery or the usePrecisionPayPaymentGateway function');
        return;
      }
      const precisionPayPaymentGateway = usePrecisionPayPaymentGateway($);
      precisionPayPaymentGateway.init();

      onPaymentSetup(async () => {
        // Prep data to be sent to the server - grab from session storage
        let payload = {};
        const plaidDataStorage = sessionStorage.getItem(precisionPayPaymentGateway.plaidStorage);
        const precisionpayDataStorage = sessionStorage.getItem(
          precisionPayPaymentGateway.precisionPayStorage
        );
        if (plaidDataStorage) {
          const plaidData = JSON.parse(plaidDataStorage);
          payload = {
            precisionpay_public_token: plaidData.public_token,
            precisionpay_account_id: plaidData.accountId,
            precisionpay_plaid_user_id: plaidData.precisionPayPlaidUserId,
            precisionpay_registered_user_id: plaidData.precisionPayRegisteredUserId,
            [wpNonceName]: wpNonce,
          };
        } else if (precisionpayDataStorage) {
          const precisionpayData = JSON.parse(precisionpayDataStorage);
          payload = {
            precisionpay_checkout_token: precisionpayData,
            [wpNonceName]: wpNonce,
          };
        }

        return {
          type: emitResponse.responseTypes.SUCCESS,
          meta: {
            paymentMethodData: payload,
          },
        };
      });

      onCheckoutFail((result) => {
        let message = '';
        if (result.processingResponse) message = result.processingResponse.message;
        precisionPayPaymentGateway.handleCheckoutError(null, message);
      });
    }
  }, [emitResponse.responseTypes.SUCCESS, onPaymentSetup]);

  // Let's require SSL unless the website is in test mode
  const isSSL = window.location.protocol === 'https:';

  if (!isTestMode && !isSSL) {
    return (
      <div className="precsionpay-block-checkout precisionpay-warning">
        <Icon icon={warning} />
        <p className="error" style={{ color: 'red' }}>
          {__(
            'SSL is required for the PrecisionPay payment gateway. Please enable SSL on your site to continue.',
            'precisionpay-payments-for-woocommerce'
          )}
        </p>
      </div>
    );
  }

  return (
    <div className="wc-precisionpay-form precsionpay-block-checkout">
      {!hasAPIKeys && (
        <p className="error precisionpay-warning" style={{ color: 'red' }}>
          The {label} plugin is not fully configured yet and will not work. Please complete the
          configuration process before going live with this plugin.
        </p>
      )}
      {isTestMode && (
        <p className="notice precisionpay-notice" style={{ color: '#5d5c09' }}>
          <strong className="bold-text">Test Mode Enabled</strong> Use this mode for testing
          purposes only. You can find the guest/one-time-pay test credentials in this{' '}
          <a href="https://plaid.com/docs/quickstart/" target="_blank" rel="noopener noreferrer">
            documentation
          </a>
          .
        </p>
      )}
      <p>{description}</p>
      <div style={{ display: 'none' }}>
        <div className="bank-plaid">
          <input name="precisionpay_public_token" id="precisionpay_public_token" type="hidden" />
          <input name="precisionpay_account_id" id="precisionpay_account_id" type="hidden" />
          <input
            name="precisionpay_plaid_user_id"
            id="precisionpay_plaid_user_id"
            value=""
            type="hidden"
          />
          <input
            name="precisionpay_registered_user_id"
            id="precisionpay_registered_user_id"
            value=""
            type="hidden"
          />
        </div>
        <div className="bank-precision-pay-member">
          <input
            name="precisionpay_checkout_token"
            id="precisionpay_checkout_token"
            value=""
            type="hidden"
          />
        </div>
        <WPNonce />
      </div>
      <button
        id="precisionpay-link-button"
        className="precisionpay-plaid-link-button precisionpay-button"
        style={{ backgroundColor: brandColor }}
      >
        <span>{buttonTitle}</span> <img src={buttonLogo} alt="PrecisionPay" />
      </button>
      <div className="clear"></div>
      <div className="clear">
        <img className="precisionPayLoadingFullPNG" src={loadingIconLong} />
      </div>
    </div>
  );
};

/**
 * Label component
 *
 * @param {*} props Props from payment API.
 */
const Label = (props) => {
  const { PaymentMethodLabel } = props.components;
  // const { PaymentMethodLabel, PaymentMethodIcon } = props.components;
  // return <PaymentMethodIcon id="precisionpay-logo" src={ logo } alt="PrecisionPay" />

  return (
    <div className="precisionpay-label">
      <span style={{ display: 'inline-block', width: '0', height: '30px', overflow: 'hidden' }}>
        <PaymentMethodLabel text={label} />
      </span>
      <img
        style={{ height: '30px', maxHeight: '30px' }}
        id="precisionpay-logo"
        src={logo}
        alt="PrecisionPay"
      />
    </div>
  );
};

/**
 * PrecisionPay payment method config object.
 */
const PrecisionPay = {
  name: id,
  label: <Label />,
  content: <Content />,
  edit: <Content />,
  canMakePayment: () => true,
  ariaLabel: label,
  supports: {
    features: settings.supports,
  },
};

registerPaymentMethod(PrecisionPay);
