import { Component, h, Host, Prop, State, Watch } from '@stencil/core';
import { loadScript } from '@paypal/paypal-js';
import { __ } from '@wordpress/i18n';
import apiFetch from '../../../functions/fetch';
import { getScriptLoadParams } from '../paypal-buttons/functions';
export class ScPaypalAddMethod {
  constructor() {
    this.liveMode = true;
  }
  componentWillLoad() {
    this.createPaymentIntent();
  }
  async handlePaymentIntentCreate() {
    var _a, _b;
    const { external_intent_id } = this.paymentIntent || {};
    const { client_id, account_id, merchant_initiated } = ((_b = (_a = this.paymentIntent) === null || _a === void 0 ? void 0 : _a.processor_data) === null || _b === void 0 ? void 0 : _b.paypal) || {};
    // we need this data.
    if (!client_id || !account_id || !external_intent_id)
      return;
    // check if stripe has been initialized
    if (!this.paypal) {
      try {
        this.paypal = await loadScript(getScriptLoadParams({
          clientId: client_id,
          merchantId: account_id,
          merchantInitiated: merchant_initiated,
          reusable: true,
        }));
        this.paypal
          .Buttons({
          onInit: () => {
            this.loaded = true;
          },
          createBillingAgreement: () => {
            return new Promise(resolve => resolve(external_intent_id));
          },
          onApprove: async () => {
            var _a;
            try {
              this.loading = true;
              const intent = (await apiFetch({
                method: 'PATCH',
                path: `surecart/v1/payment_intents/${(_a = this.paymentIntent) === null || _a === void 0 ? void 0 : _a.id}/capture`,
              }));
              if (['succeeded', 'pending', 'requires_approval'].includes(intent === null || intent === void 0 ? void 0 : intent.status)) {
                window.location.assign(this.successUrl);
              }
              else {
                throw { message: __('The payment did not process. Please try again.', 'surecart') };
              }
            }
            catch (err) {
              console.error(err);
              this.error = (err === null || err === void 0 ? void 0 : err.message) || __('The payment did not process. Please try again.', 'surecart');
              this.loading = false;
            }
          },
          onError: err => {
            console.error(err);
            alert((err === null || err === void 0 ? void 0 : err.message) || __('The payment did not process. Please try again.', 'surecart'));
          },
        })
          .render(this.container);
      }
      catch (err) {
        console.error('Failed to load the PayPal JS SDK script', err);
        this.error = __('Failed to load the PayPal JS SDK script', 'surecart');
      }
    }
  }
  async createPaymentIntent() {
    var _a, _b;
    try {
      this.loading = true;
      this.error = '';
      this.paymentIntent = await apiFetch({
        method: 'POST',
        path: 'surecart/v1/payment_intents',
        data: {
          processor_type: 'paypal',
          reusable: true,
          live_mode: this.liveMode,
          customer_id: this.customerId,
          currency: this.currency,
        },
      });
    }
    catch (e) {
      this.error = ((_b = (_a = e === null || e === void 0 ? void 0 : e.additional_errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.loading = false;
    }
  }
  render() {
    return (h(Host, null,
      this.error && (h("sc-alert", { open: !!this.error, type: "danger" },
        h("span", { slot: "title" }, __('Error', 'surecart')),
        this.error)),
      h("div", { class: "sc-paypal-button-container", hidden: !this.loaded, ref: el => (this.container = el) })));
  }
  static get is() { return "sc-paypal-add-method"; }
  static get originalStyleUrls() { return {
    "$": ["sc-paypal-add-method.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-paypal-add-method.css"]
  }; }
  static get properties() { return {
    "liveMode": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "live-mode",
      "reflect": false,
      "defaultValue": "true"
    },
    "customerId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "customer-id",
      "reflect": false
    },
    "successUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "success-url",
      "reflect": false
    },
    "currency": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "currency",
      "reflect": false
    }
  }; }
  static get states() { return {
    "loading": {},
    "loaded": {},
    "error": {},
    "paymentIntent": {}
  }; }
  static get watchers() { return [{
      "propName": "paymentIntent",
      "methodName": "handlePaymentIntentCreate"
    }]; }
}
