import { Component, Element, Event, h, Host, Listen, Prop, State } from '@stencil/core';
import { __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
import apiFetch from '../../../functions/fetch';
import { expand } from '../../../services/session';
import { state as checkoutState } from '@store/checkout';
import { clearCheckout } from '@store/checkout/mutations';
/**
 * This component listens to the order status
 * and confirms the order when payment is successful.
 */
export class ScOrderConfirmProvider {
  constructor() {
    /** Whether to show success modal */
    this.showSuccessModal = false;
  }
  /** Listen for paid event. This is triggered by Stripe or Paypal elements when payment succeeds. */
  handlePaidEvent() {
    this.confirmOrder();
  }
  /** Confirm the order. */
  async confirmOrder() {
    var _a, _b, _c;
    try {
      this.confirmedCheckout = (await apiFetch({
        method: 'PATCH',
        path: addQueryArgs(`surecart/v1/checkouts/${(_a = checkoutState === null || checkoutState === void 0 ? void 0 : checkoutState.checkout) === null || _a === void 0 ? void 0 : _a.id}/confirm`, [expand]),
      }));
      this.scSetState.emit('CONFIRMED');
      // emit the order paid event for tracking scripts.
      this.scOrderPaid.emit(this.confirmedCheckout);
    }
    catch (e) {
      console.error(e);
      this.scError.emit(e);
    }
    finally {
      // always clear the checkout.
      clearCheckout();
      // get success url.
      const successUrl = ((_c = (_b = this.confirmedCheckout) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.success_url) || this.successUrl;
      if (successUrl) {
        // set state to redirecting.
        this.scSetState.emit('REDIRECT');
        setTimeout(() => { var _a; return window.location.assign(addQueryArgs(successUrl, { order: (_a = this.confirmedCheckout) === null || _a === void 0 ? void 0 : _a.id })); }, 50);
      }
      else {
        this.showSuccessModal = true;
      }
    }
  }
  getSuccessUrl() {
    var _a, _b, _c, _d, _e;
    const url = ((_b = (_a = this.confirmedCheckout) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.success_url) || this.successUrl;
    return url ? addQueryArgs(url, { order: (_c = this.confirmedCheckout) === null || _c === void 0 ? void 0 : _c.id }) : (_e = (_d = window === null || window === void 0 ? void 0 : window.scData) === null || _d === void 0 ? void 0 : _d.pages) === null || _e === void 0 ? void 0 : _e.dashboard;
  }
  render() {
    var _a, _b, _c, _d;
    const manualPaymentMethod = (_a = this.confirmedCheckout) === null || _a === void 0 ? void 0 : _a.manual_payment_method;
    return (h(Host, null,
      h("slot", null),
      h("sc-dialog", { open: !!this.showSuccessModal, style: { '--body-spacing': 'var(--sc-spacing-xxx-large)' }, noHeader: true, onScRequestClose: e => e.preventDefault() },
        h("div", { class: "confirm__icon" },
          h("div", { class: "confirm__icon-container" },
            h("sc-icon", { name: "check" }))),
        h("sc-dashboard-module", { heading: ((_b = this.successText) === null || _b === void 0 ? void 0 : _b.title) || __('Thanks for your order!', 'surecart'), style: { '--sc-dashboard-module-spacing': 'var(--sc-spacing-x-large)', 'textAlign': 'center' } },
          h("span", { slot: "description" }, ((_c = this.successText) === null || _c === void 0 ? void 0 : _c.description) || __('Your payment was successful, and your order is complete. A receipt is on its way to your inbox.', 'surecart')),
          !!(manualPaymentMethod === null || manualPaymentMethod === void 0 ? void 0 : manualPaymentMethod.name) && !!(manualPaymentMethod === null || manualPaymentMethod === void 0 ? void 0 : manualPaymentMethod.instructions) && (h("sc-alert", { type: "info", open: true, style: { 'text-align': 'left' } },
            h("span", { slot: "title" }, manualPaymentMethod === null || manualPaymentMethod === void 0 ? void 0 : manualPaymentMethod.name), manualPaymentMethod === null || manualPaymentMethod === void 0 ? void 0 :
            manualPaymentMethod.instructions.split('\n').map(i => {
              return h("p", null, i);
            }))),
          h("sc-button", { href: this.getSuccessUrl(), size: "large", type: "primary" },
            ((_d = this.successText) === null || _d === void 0 ? void 0 : _d.button) || __('Continue', 'surecart'),
            h("sc-icon", { name: "arrow-right", slot: "suffix" }))))));
  }
  static get is() { return "sc-order-confirm-provider"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["sc-order-confirm-provider.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-order-confirm-provider.css"]
  }; }
  static get properties() { return {
    "successUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Success url."
      },
      "attribute": "success-url",
      "reflect": false
    },
    "successText": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "{\n    title: string;\n    description: string;\n    button: string;\n  }",
        "resolved": "{ title: string; description: string; button: string; }",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Success text for the form."
      }
    }
  }; }
  static get states() { return {
    "showSuccessModal": {},
    "confirmedCheckout": {}
  }; }
  static get events() { return [{
      "method": "scOrderPaid",
      "name": "scOrderPaid",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "The order is paid event."
      },
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "location": "import",
            "path": "../../../types"
          }
        }
      }
    }, {
      "method": "scSetState",
      "name": "scSetState",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      }
    }, {
      "method": "scError",
      "name": "scError",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Error event."
      },
      "complexType": {
        "original": "{ message: string; code?: string; data?: any; additional_errors?: any } | {}",
        "resolved": "{ message: string; code?: string; data?: any; additional_errors?: any; } | {}",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "scPaid",
      "method": "handlePaidEvent",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
