import { Component, Event, Fragment, h, Host, Prop, State, Watch } from '@stencil/core';
import { __ } 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;
  }
  /** 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];
  }
  handlePriscChange() {
    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;
  }
  renderAdHoc() {
    var _a, _b;
    return (h("sc-price-input", { ref: el => (this.adHocInput = el), required: true, label: 'Enter an amount', value: (((_a = this.getLineItem()) === null || _a === void 0 ? void 0 : _a.ad_hoc_amount) || ((_b = this.getLineItem()) === null || _b === void 0 ? void 0 : _b.total_amount)).toString(), onScChange: e => this.onChangeAdHoc(e), min: this.price.ad_hoc_min_amount, max: this.price.ad_hoc_max_amount }));
  }
  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("span", { slot: "price" },
        h("sc-format-number", { type: "currency", value: this.price.amount, currency: this.price.currency })),
      h("span", { slot: "per" }, intervalString(this.price, { labels: { interval: '/', period: __('for', 'surecart') } }))));
  }
  render() {
    var _a, _b, _c, _d;
    if (this.loading) {
      return (h("sc-choice", { name: "loading", showLabel: this.showLabel, showPrice: this.showPrice, showControl: this.showControl, disabled: true },
        h("sc-skeleton", { style: { width: '60px', display: 'inline-block' } }),
        h("sc-skeleton", { style: { width: '80px', display: 'inline-block' }, slot: "price" }),
        this.description && h("sc-skeleton", { style: { width: '120px', display: 'inline-block' }, slot: "description" })));
    }
    // 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(Fragment, null,
      h("sc-choice", { ref: el => (this.choice = el), value: this.priceId, type: this.type, showLabel: this.showLabel, showPrice: this.showPrice, showControl: this.showControl, checked: this.isChecked() },
        this.label || ((_d = this === null || this === void 0 ? void 0 : this.product) === null || _d === void 0 ? void 0 : _d.name),
        this.description && h("span", { slot: "description" }, this.description),
        this.renderPrice())));
  }
  static get is() { return "sc-price-choice"; }
  static get originalStyleUrls() { return {
    "$": ["sc-price-choice.css"]
  }; }
  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": "Order",
        "resolved": "Order",
        "references": {
          "Order": {
            "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"
      }
    }
  }; }
  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": "handlePriscChange"
    }, {
      "propName": "error",
      "methodName": "handleErrorsChange"
    }, {
      "propName": "checked",
      "methodName": "handleCheckedChange"
    }]; }
}
openWormhole(ScPriceChoice, ['prices', 'products', 'order', 'error'], false);
