import { Component, Element, h, Prop, State } from '@stencil/core';
import { __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
import apiFetch from '../../../../functions/fetch';
import { onFirstVisible } from '../../../../functions/lazy';
export class ScSubscriptionsList {
  constructor() {
    /** Customer id to fetch subscriptions */
    this.query = {
      page: 1,
      per_page: 10,
    };
    this.cancelBehavior = 'period_end';
    this.subscriptions = [];
    this.pagination = {
      total: 0,
      total_pages: 0,
    };
  }
  componentWillLoad() {
    onFirstVisible(this.el, () => {
      this.initialFetch();
    });
  }
  async initialFetch() {
    try {
      this.loading = true;
      await this.getSubscriptions();
    }
    catch (e) {
      console.error(this.error);
      this.error = (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.loading = false;
    }
  }
  async fetchSubscriptions() {
    try {
      this.busy = true;
      await this.getSubscriptions();
    }
    catch (e) {
      console.error(this.error);
      this.error = (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.busy = false;
    }
  }
  /** Get all subscriptions */
  async getSubscriptions() {
    if (!this.isCustomer) {
      return;
    }
    const response = (await await apiFetch({
      path: addQueryArgs(`surecart/v1/subscriptions/`, {
        expand: ['price', 'price.product', 'current_period', 'period.checkout', 'purchase', 'purchase.license', 'license.activations', 'discount', 'discount.coupon'],
        ...this.query,
      }),
      parse: false,
    }));
    this.pagination = {
      total: parseInt(response.headers.get('X-WP-Total')),
      total_pages: parseInt(response.headers.get('X-WP-TotalPages')),
    };
    this.subscriptions = (await response.json());
    return this.subscriptions;
  }
  nextPage() {
    this.query.page = this.query.page + 1;
    this.fetchSubscriptions();
  }
  prevPage() {
    this.query.page = this.query.page - 1;
    this.fetchSubscriptions();
  }
  renderEmpty() {
    return (h("div", null,
      h("sc-divider", { style: { '--spacing': '0' } }),
      h("slot", { name: "empty" },
        h("sc-empty", { icon: "repeat" }, __("You don't have any subscriptions.", 'surecart')))));
  }
  renderLoading() {
    return (h("sc-card", { "no-padding": true, style: { '--overflow': 'hidden' } },
      h("sc-stacked-list", null,
        h("sc-stacked-list-row", { style: { '--columns': '2' }, "mobile-size": 0 },
          h("div", { style: { padding: '0.5em' } },
            h("sc-skeleton", { style: { width: '30%', marginBottom: '0.75em' } }),
            h("sc-skeleton", { style: { width: '20%', marginBottom: '0.75em' } }),
            h("sc-skeleton", { style: { width: '40%' } }))))));
  }
  renderList() {
    return this.subscriptions.map(subscription => {
      return (h("sc-stacked-list-row", { href: addQueryArgs(window.location.href, {
          action: 'edit',
          model: 'subscription',
          id: subscription.id,
        }), key: subscription.id, "mobile-size": 0 },
        h("sc-subscription-details", { subscription: subscription }),
        h("sc-icon", { name: "chevron-right", slot: "suffix" })));
    });
  }
  renderContent() {
    var _a;
    if (this.loading) {
      return this.renderLoading();
    }
    if (((_a = this.subscriptions) === null || _a === void 0 ? void 0 : _a.length) === 0) {
      return this.renderEmpty();
    }
    return (h("sc-card", { "no-padding": true, style: { '--overflow': 'hidden' } },
      h("sc-stacked-list", null, this.renderList())));
  }
  render() {
    var _a, _b;
    return (h("sc-dashboard-module", { class: "subscriptions-list", error: this.error },
      h("span", { slot: "heading" },
        h("slot", { name: "heading" }, this.heading || __('Subscriptions', 'surecart'))),
      !!this.allLink && !!((_a = this.subscriptions) === null || _a === void 0 ? void 0 : _a.length) && (h("sc-button", { type: "link", href: this.allLink, slot: "end" },
        __('View all', 'surecart'),
        h("sc-icon", { name: "chevron-right", slot: "suffix" }))),
      this.renderContent(),
      !this.allLink && (h("sc-pagination", { page: this.query.page, perPage: this.query.per_page, total: this.pagination.total, totalPages: this.pagination.total_pages, totalShowing: (_b = this === null || this === void 0 ? void 0 : this.subscriptions) === null || _b === void 0 ? void 0 : _b.length, onScNextPage: () => this.nextPage(), onScPrevPage: () => this.prevPage() })),
      this.busy && h("sc-block-ui", null)));
  }
  static get is() { return "sc-subscriptions-list"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["sc-subscriptions-list.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-subscriptions-list.css"]
  }; }
  static get properties() { return {
    "query": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "{\n    page: number;\n    per_page: number;\n  }",
        "resolved": "{ page: number; per_page: number; }",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Customer id to fetch subscriptions"
      },
      "defaultValue": "{\n    page: 1,\n    per_page: 10,\n  }"
    },
    "allLink": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "all-link",
      "reflect": false
    },
    "heading": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "heading",
      "reflect": false
    },
    "isCustomer": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "is-customer",
      "reflect": false
    },
    "cancelBehavior": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'period_end' | 'immediate'",
        "resolved": "\"immediate\" | \"period_end\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "cancel-behavior",
      "reflect": false,
      "defaultValue": "'period_end'"
    }
  }; }
  static get states() { return {
    "subscriptions": {},
    "loading": {},
    "busy": {},
    "error": {},
    "pagination": {}
  }; }
  static get elementRef() { return "el"; }
}
