import { Component, Event, Fragment, h, Prop, State } from '@stencil/core';
import { sprintf, __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
import { state as selectedProcessor } from '@store/selected-processor';
import { state as processorsState } from '@store/processors';
import { hasMultipleMethodChoices, availableMethodTypes, availableManualPaymentMethods } from '@store/processors/getters';
// checkout store.
import { state as checkoutState } from '@store/checkout';
import { listenTo } from '@store/checkout/functions';
import { checkoutIsLocked } from '@store/checkout/getters';
import { lockCheckout, unLockCheckout } from '@store/checkout/mutations';
import apiFetch from '../../../../functions/fetch';
import { ManualPaymentMethods } from '../payment/ManualPaymentMethods';
export class ScCheckoutMolliePayment {
  componentWillLoad() {
    selectedProcessor.id = 'mollie';
    this.fetchMethods();
    listenTo('checkout', ['total_amount', 'currency', 'reusabled_payment_method_required', 'shipping_address'], () => this.fetchMethods());
  }
  async fetchMethods() {
    var _a;
    const checkout = checkoutState.checkout;
    if (!(checkout === null || checkout === void 0 ? void 0 : checkout.currency) || !(checkout === null || checkout === void 0 ? void 0 : checkout.total_amount))
      return; // wait until we have a currency.
    try {
      lockCheckout('methods');
      const response = (await apiFetch({
        path: addQueryArgs(`surecart/v1/processors/${this.processorId}/payment_method_types`, {
          amount: checkout === null || checkout === void 0 ? void 0 : checkout.total_amount,
          country: ((_a = checkout === null || checkout === void 0 ? void 0 : checkout.shipping_address) === null || _a === void 0 ? void 0 : _a.country) || 'us',
          currency: checkout === null || checkout === void 0 ? void 0 : checkout.currency,
          ...((checkout === null || checkout === void 0 ? void 0 : checkout.reusable_payment_method_required) ? { reusable: checkout === null || checkout === void 0 ? void 0 : checkout.reusable_payment_method_required } : {}),
          per_page: 100,
        }),
      }));
      processorsState.methods = (response === null || response === void 0 ? void 0 : response.data) || [];
    }
    catch (e) {
      this.scError.emit(e);
      console.error(e);
    }
    finally {
      unLockCheckout('methods');
    }
  }
  renderLoading() {
    return (h("sc-card", null,
      h("sc-skeleton", { style: { width: '50%', marginBottom: '0.5em' } }),
      h("sc-skeleton", { style: { width: '30%', marginBottom: '0.5em' } }),
      h("sc-skeleton", { style: { width: '60%', marginBottom: '0.5em' } })));
  }
  render() {
    var _a, _b, _c;
    if (checkoutIsLocked('methods') && !((_a = availableMethodTypes()) === null || _a === void 0 ? void 0 : _a.length)) {
      return this.renderLoading();
    }
    if (!((_b = checkoutState.checkout) === null || _b === void 0 ? void 0 : _b.currency)) {
      return this.renderLoading();
    }
    if (!((_c = availableMethodTypes()) === null || _c === void 0 ? void 0 : _c.length)) {
      return (h("sc-alert", { type: "warning", open: true },
        __('No available payment methods', 'surecart'),
        ' '));
    }
    const Tag = hasMultipleMethodChoices() ? 'sc-toggles' : 'div';
    return (h(Fragment, null,
      h(Tag, { collapsible: false, theme: "container" },
        (availableMethodTypes() || []).map(method => (h("sc-payment-method-choice", { "processor-id": "mollie", "method-id": method === null || method === void 0 ? void 0 : method.id, key: method === null || method === void 0 ? void 0 : method.id },
          h("span", { slot: "summary", class: "sc-payment-toggle-summary" },
            !!(method === null || method === void 0 ? void 0 : method.image) && h("img", { src: method === null || method === void 0 ? void 0 : method.image }),
            h("span", null, method === null || method === void 0 ? void 0 : method.description)),
          h("sc-card", null,
            h("sc-payment-selected", { label: sprintf(__('%s selected for check out.', 'surecart'), method === null || method === void 0 ? void 0 : method.description) },
              !!(method === null || method === void 0 ? void 0 : method.image) && h("img", { slot: "icon", src: method === null || method === void 0 ? void 0 : method.image, style: { width: '32px' } }),
              __('Another step will appear after submitting your order to complete your purchase details.', 'surecart')))))),
        h(ManualPaymentMethods, { methods: availableManualPaymentMethods() })),
      !!checkoutIsLocked('methods') && h("sc-block-ui", { class: "busy-block-ui", "z-index": 9, style: { '--sc-block-ui-opacity': '0.4' } })));
  }
  static get is() { return "sc-checkout-mollie-payment"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["sc-checkout-mollie-payment.css"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-checkout-mollie-payment.css"]
  }; }
  static get properties() { return {
    "processorId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "processor-id",
      "reflect": false
    },
    "method": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "method",
      "reflect": false
    }
  }; }
  static get states() { return {
    "error": {},
    "methods": {}
  }; }
  static get events() { return [{
      "method": "scError",
      "name": "scError",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Error event"
      },
      "complexType": {
        "original": "ResponseError",
        "resolved": "ResponseError",
        "references": {
          "ResponseError": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }]; }
}
