import { Component, Event, Fragment, h, Host, Prop, State, Watch } from '@stencil/core';
import { __, sprintf, _n } from '@wordpress/i18n';
import { openWormhole } from 'stencil-wormhole';
import { isPriceInOrder } from '../../../../functions/line-items';
import { intervalString } from '../../../../functions/price';
import { getPricesAndProducts } from '../../../../services/fetch';
export class ScPriceChoice {
  constructor() {
    /** Is this loading */
    this.loading = false;
    /** Show the label */
    this.showLabel = true;
    /** Show the price amount */
    this.showPrice = true;
    /** Show the radio/checkbox control */
    this.showControl = true;
    /** Price entities */
    this.prices = {};
    /** Product entity */
    this.products = {};
    /** Default quantity */
    this.quantity = 1;
    /** Is this checked by default */
    this.checked = false;
    /** Is this blank? */
    this.blank = false;
  }
  /** Refetch if price changes */
  handlePriceIdChage() {
    var _a;
    if (this.price && ((_a = this.price) === null || _a === void 0 ? void 0 : _a.id) === this.priceId)
      return;
    this.fetchPriceWithProduct();
  }
  /** Keep price up to date. */
  handlePricesChange() {
    var _a, _b, _c;
    if (!Object.keys(this.prices || {}).length || !Object.keys(this.products || {}).length)
      return;
    this.price = (_a = this === null || this === void 0 ? void 0 : this.prices) === null || _a === void 0 ? void 0 : _a[this.priceId];
    this.product = (_b = this === null || this === void 0 ? void 0 : this.products) === null || _b === void 0 ? void 0 : _b[(_c = this === null || this === void 0 ? void 0 : this.price) === null || _c === void 0 ? void 0 : _c.product];
  }
  handlePriseChange() {
    var _a;
    this.isAdHoc = (_a = this === null || this === void 0 ? void 0 : this.price) === null || _a === void 0 ? void 0 : _a.ad_hoc;
  }
  handleErrorsChange() {
    var _a;
    const error = (((_a = this === null || this === void 0 ? void 0 : this.error) === null || _a === void 0 ? void 0 : _a.additional_errors) || []).find(error => { var _a; return ((_a = error === null || error === void 0 ? void 0 : error.data) === null || _a === void 0 ? void 0 : _a.attribute) === 'line_items.ad_hoc_amount'; });
    this.adHocErrorMessage = (error === null || error === void 0 ? void 0 : error.message) ? error === null || error === void 0 ? void 0 : error.message : '';
  }
  handleCheckedChange() {
    var _a;
    if (((_a = this.price) === null || _a === void 0 ? void 0 : _a.ad_hoc) && this.choice.checked) {
      setTimeout(() => {
        this.adHocInput.triggerFocus();
      }, 50);
      return;
    }
  }
  /** Fetch on load */
  componentWillLoad() {
    if (!this.price) {
      this.fetchPriceWithProduct();
    }
  }
  /** Fetch prices and products */
  async fetchPriceWithProduct() {
    if (!this.priceId)
      return;
    try {
      this.loading = true;
      const { products, prices } = await getPricesAndProducts({
        archived: false,
        ids: [this.priceId],
      });
      // add to central store.
      this.scAddEntities.emit({ prices, products });
    }
    catch (err) {
    }
    finally {
      this.loading = false;
    }
  }
  /** Is this price in the checkout session. */
  isInOrder() {
    return isPriceInOrder(this.price, this.order);
  }
  /** Is this checked */
  isChecked() {
    return this.isInOrder();
  }
  onChangeAdHoc(e) {
    this.scUpdateLineItem.emit({ price_id: this.priceId, quantity: this.quantity, ad_hoc_amount: e.target.value });
  }
  getLineItem() {
    var _a, _b;
    return (((_b = (_a = this.order) === null || _a === void 0 ? void 0 : _a.line_items) === null || _b === void 0 ? void 0 : _b.data) || []).find(lineItem => lineItem.price.id === this.priceId);
  }
  /** Show we show the ad hoc price box */
  showAdHoc() {
    var _a, _b;
    if (!((_a = this.price) === null || _a === void 0 ? void 0 : _a.ad_hoc)) {
      return false;
    }
    if (this.isInOrder()) {
      return true;
    }
    return (_b = this === null || this === void 0 ? void 0 : this.choice) === null || _b === void 0 ? void 0 : _b.checked;
  }
  renderEmpty() {
    var _a;
    if ((_a = window === null || window === void 0 ? void 0 : window.wp) === null || _a === void 0 ? void 0 : _a.blocks) {
      return (h("sc-alert", { type: "danger", open: true, style: { margin: '0px' } }, __('This product has been archived.', 'surecart')));
    }
    return h(Host, { style: { display: 'none' } });
  }
  renderPrice() {
    return (h(Fragment, null,
      h("sc-format-number", { type: "currency", value: this.price.amount, currency: this.price.currency }),
      intervalString(this.price, {
        showOnce: true,
        abbreviate: true,
        labels: {
          interval: '/',
          period: 
          /** translators: used as in time period: "for 3 months" */
          __('for', 'surecart'),
        },
      })));
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g;
    if (this.loading) {
      return (h("sc-choice-container", { showControl: this.showControl, name: "loading", disabled: true },
        h("div", { class: "price-choice" },
          h("sc-skeleton", { style: { width: '60px', display: 'inline-block' } }),
          h("sc-skeleton", { style: { width: '80px', display: 'inline-block' } }))));
    }
    // we need an active price.
    if (!((_a = this === null || this === void 0 ? void 0 : this.price) === null || _a === void 0 ? void 0 : _a.id) || ((_b = this.price) === null || _b === void 0 ? void 0 : _b.archived))
      return this.renderEmpty();
    // product needs to be active
    if ((_c = this.product) === null || _c === void 0 ? void 0 : _c.archived) {
      return this.renderEmpty();
    }
    return (h("sc-choice-container", { ref: el => (this.choice = el), value: this.priceId, type: this.type, showControl: this.showControl, checked: this.isChecked() },
      h("div", { class: "price-choice" },
        this.showLabel && (h("div", { class: "price-choice__title" },
          h("div", { class: "price-choice__name" }, this.label || ((_d = this === null || this === void 0 ? void 0 : this.price) === null || _d === void 0 ? void 0 : _d.name) || ((_e = this === null || this === void 0 ? void 0 : this.product) === null || _e === void 0 ? void 0 : _e.name)),
          !!this.description && h("div", { class: "price-choice__description" }, this.description))),
        this.showPrice && (h("div", { class: "price-choice__details" },
          h("div", { class: "price-choice__price" }, ((_f = this.price) === null || _f === void 0 ? void 0 : _f.ad_hoc) ? (__('Custom Amount', 'surecart')) : (h(Fragment, null,
            h("sc-format-number", { type: "currency", value: this.price.amount, currency: this.price.currency }),
            intervalString(this.price, {
              showOnce: true,
              abbreviate: true,
              labels: {
                interval: '/',
                period: 
                /** translators: used as in time period: "for 3 months" */
                __('for', 'surecart'),
              },
            })))),
          !!this.price.trial_duration_days && (h("div", { class: "price-choice__trial" }, sprintf(_n('Starting in %s day', 'Starting in %s days', this.price.trial_duration_days, 'surecart'), this.price.trial_duration_days))),
          !!this.price.setup_fee_enabled && ((_g = this.price) === null || _g === void 0 ? void 0 : _g.setup_fee_amount) && (h("div", { class: "price-choice__setup-fee" },
            h("sc-format-number", { type: "currency", value: this.price.setup_fee_amount, currency: this.price.currency }),
            ' ',
            this.price.setup_fee_name || __('Setup Fee', 'surecart'))))))));
  }
  static get is() { return "sc-price-choice"; }
  static get originalStyleUrls() { return {
    "$": ["sc-price-choice.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-price-choice.css"]
  }; }
  static get properties() { return {
    "priceId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Id of the price."
      },
      "attribute": "price-id",
      "reflect": true
    },
    "price": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "Price",
        "resolved": "Price",
        "references": {
          "Price": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Stores the price"
      }
    },
    "loading": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Is this loading"
      },
      "attribute": "loading",
      "reflect": false,
      "defaultValue": "false"
    },
    "label": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Label for the choice."
      },
      "attribute": "label",
      "reflect": false
    },
    "showLabel": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Show the label"
      },
      "attribute": "show-label",
      "reflect": false,
      "defaultValue": "true"
    },
    "showPrice": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Show the price amount"
      },
      "attribute": "show-price",
      "reflect": false,
      "defaultValue": "true"
    },
    "showControl": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Show the radio/checkbox control"
      },
      "attribute": "show-control",
      "reflect": false,
      "defaultValue": "true"
    },
    "description": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Label for the choice."
      },
      "attribute": "description",
      "reflect": false
    },
    "prices": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Prices",
        "resolved": "{ [id: string]: Price; }",
        "references": {
          "Prices": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Price entities"
      },
      "defaultValue": "{}"
    },
    "products": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Products",
        "resolved": "{ [id: string]: Product; }",
        "references": {
          "Products": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Product entity"
      },
      "defaultValue": "{}"
    },
    "order": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Session"
      }
    },
    "quantity": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Default quantity"
      },
      "attribute": "quantity",
      "reflect": false,
      "defaultValue": "1"
    },
    "type": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'checkbox' | 'radio'",
        "resolved": "\"checkbox\" | \"radio\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Choice Type"
      },
      "attribute": "type",
      "reflect": false
    },
    "checked": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Is this checked by default"
      },
      "attribute": "checked",
      "reflect": true,
      "defaultValue": "false"
    },
    "error": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "ResponseError",
        "resolved": "ResponseError",
        "references": {
          "ResponseError": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Errors from response"
      }
    },
    "isAdHoc": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "Boolean",
        "resolved": "Boolean",
        "references": {
          "Boolean": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Is this an ad-hoc price choice"
      }
    },
    "blank": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Is this blank?"
      },
      "attribute": "blank",
      "reflect": false,
      "defaultValue": "false"
    }
  }; }
  static get states() { return {
    "errorMessage": {},
    "adHocErrorMessage": {},
    "product": {}
  }; }
  static get events() { return [{
      "method": "scUpdateLineItem",
      "name": "scUpdateLineItem",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Toggle line item event"
      },
      "complexType": {
        "original": "LineItemData",
        "resolved": "LineItemData",
        "references": {
          "LineItemData": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }, {
      "method": "scRemoveLineItem",
      "name": "scRemoveLineItem",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Toggle line item event"
      },
      "complexType": {
        "original": "LineItemData",
        "resolved": "LineItemData",
        "references": {
          "LineItemData": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }, {
      "method": "scAddEntities",
      "name": "scAddEntities",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Add entities"
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get watchers() { return [{
      "propName": "priceId",
      "methodName": "handlePriceIdChage"
    }, {
      "propName": "prices",
      "methodName": "handlePricesChange"
    }, {
      "propName": "products",
      "methodName": "handlePricesChange"
    }, {
      "propName": "price",
      "methodName": "handlePriseChange"
    }, {
      "propName": "error",
      "methodName": "handleErrorsChange"
    }, {
      "propName": "checked",
      "methodName": "handleCheckedChange"
    }]; }
}
openWormhole(ScPriceChoice, ['prices', 'products', 'order', 'error'], false);
