import { isDemo } from "@saasquatch/component-boilerplate";
import { withHooks } from "@saasquatch/stencil-hooks";
import { useEffect, useMemo, useReducer } from "@saasquatch/universal-hooks";
import { Component, h, Prop } from "@stencil/core";
import deepmerge from "deepmerge";
import { GenericTableView, } from "../../tables/GenericTableView";
import { useRequestRerender, useRerenderListener, } from "../../tables/re-render";
import { useChildElements } from "../../tables/useChildElements";
import mockInvoiceData from "./mockInvoiceData";
import { InvoiceTableView } from "./sqm-invoice-table-view";
import { tryMethod, useInvoiceTable } from "./useInvoiceTable";
/**
 * @uiName Invoice Table
 * @exampleGroup Invoices
 * @validParents ["sqm-portal-container","div","sqm-divided-layout","template","sqm-tab","sqb-program-section","sqb-conditional-section"]
 * @validChildren ["p","div","h1","h2","h3","h4","h5","span"]
 * @slots [{"name":"", "title":"Table Row"},{"name":"empty", "title":"Empty"},{"name":"loading","title":"Loading"}]
 * @example Invoice Table - <sqm-invoice-table per-page="4" hidden-columns="2" more-label="Next" prev-label="Prev" sm-breakpoint="599" md-breakpoint="799" ><sqm-invoice-table-download-column></sqm-invoice-table-download-column><sqm-invoice-table-date-column column-title="Date"></sqm-invoice-table-date-column><sqm-invoice-table-data-column column-title="Invoice" property="invoiceId"></sqm-invoice-table-data-column><sqm-invoice-table-data-column column-title="Earnings" property="earnings"></sqm-invoice-table-data-column><sqm-invoice-table-data-column column-title="Indirect tax" property="indirectTax"></sqm-invoice-table-data-column><sqm-invoice-table-data-column column-title="Earnings after tax" property="netEarnings"></sqm-invoice-table-data-column><sqm-empty empty-state-image="https://res.cloudinary.com/saasquatch/image/upload/v1710363322/squatch-assets/invoice-table-empty.png" empty-state-header="View your invoice details" empty-state-text="Refer a friend to view the status of your invoices and rewards earned" slot="empty" ></sqm-empty ></sqm-invoice-table> */
export class InvoiceTable {
  constructor() {
    /**
     * Number of invoices displayed per page
     *
     * @uiName Invoices per page
     */
    this.perPage = 4;
    /** @uiName Hide column labels */
    this.hideLabels = false;
    /** @uiName Invoice table previous page button label  */
    this.prevLabel = "Prev";
    /** @uiName Invoice table next page button label */
    this.moreLabel = "Next";
    /**
     * Provide the column numbers (0 indexed) that should not be displayed in mobile views. Ex. 0,2,3
     *
     * @uiName Hidden mobile columns
     */
    this.hiddenColumns = "0";
    /** @uiName Mobile breakpoint  */
    this.smBreakpoint = 599;
    /** @uiName Tablet breakpoint  */
    this.mdBreakpoint = 799;
    /** @uiName Invoice table title */
    this.header = "Invoices";
    /** @uiName Invoice table description  */
    this.description = "View and download your invoices to report your earnings and stay tax compliant.";
    /** @uiName Empty invoice table header  */
    this.emptyStateHeader = "View your invoice details";
    /** @uiName Empty invoice table description */
    this.emptyStateText = "Refer a friend to view the status of your invoices and rewards earned";
    withHooks(this);
  }
  disconnectedCallback() { }
  render() {
    const empty = (h(EmptySlot, { emptyStateHeader: this.emptyStateHeader, emptyStateText: this.emptyStateText }));
    const loading = h(LoadingSlot, null);
    const { states, data, callbacks, elements } = isDemo()
      ? useInvoiceTableDemo(this, empty, loading)
      : useInvoiceTable(this, empty, loading);
    useRequestRerender([this.perPage]);
    return (h(InvoiceTableView, { header: this.header, description: this.description },
      h(GenericTableView, { states: states, data: data, callbacks: callbacks, elements: elements })));
  }
  static get is() { return "sqm-invoice-table"; }
  static get encapsulation() { return "shadow"; }
  static get properties() { return {
    "programId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "text": "Program",
            "name": "uiName"
          }, {
            "text": "programSelector",
            "name": "uiWidget"
          }],
        "text": "Filters to only show invoices in this program. Will default to filtering by the program context where\nthis table lives. If no program ID is set or provided by context, then shows all invoices from all programs.\nIf program ID is \"classic\", shows classic-only invoices"
      },
      "attribute": "program-id",
      "reflect": false
    },
    "perPage": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "text": "Invoices per page",
            "name": "uiName"
          }],
        "text": "Number of invoices displayed per page"
      },
      "attribute": "per-page",
      "reflect": false,
      "defaultValue": "4"
    },
    "hideLabels": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Hide column labels",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "hide-labels",
      "reflect": false,
      "defaultValue": "false"
    },
    "prevLabel": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Invoice table previous page button label",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "prev-label",
      "reflect": false,
      "defaultValue": "\"Prev\""
    },
    "moreLabel": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Invoice table next page button label",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "more-label",
      "reflect": false,
      "defaultValue": "\"Next\""
    },
    "hiddenColumns": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Hidden mobile columns",
            "name": "uiName"
          }],
        "text": "Provide the column numbers (0 indexed) that should not be displayed in mobile views. Ex. 0,2,3"
      },
      "attribute": "hidden-columns",
      "reflect": false,
      "defaultValue": "\"0\""
    },
    "smBreakpoint": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Mobile breakpoint",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "sm-breakpoint",
      "reflect": false,
      "defaultValue": "599"
    },
    "mdBreakpoint": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Tablet breakpoint",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "md-breakpoint",
      "reflect": false,
      "defaultValue": "799"
    },
    "header": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Invoice table title",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "header",
      "reflect": false,
      "defaultValue": "\"Invoices\""
    },
    "description": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": "Invoice table description",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "description",
      "reflect": false,
      "defaultValue": "\"View and download your invoices to report your earnings and stay tax compliant.\""
    },
    "emptyStateHeader": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "text": "Empty invoice table header",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "empty-state-header",
      "reflect": false,
      "defaultValue": "\"View your invoice details\""
    },
    "emptyStateText": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [{
            "text": "Empty invoice table description",
            "name": "uiName"
          }],
        "text": ""
      },
      "attribute": "empty-state-text",
      "reflect": false,
      "defaultValue": "\"Refer a friend to view the status of your invoices and rewards earned\""
    },
    "demoData": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "DemoData<GenericTableViewProps> & {\n    mockData?: { data: Invoice[] };\n  }",
        "resolved": "Partial<Pick<GenericTableViewProps, \"states\" | \"data\" | \"elements\">> & { mockData?: { data: Invoice[]; }; }",
        "references": {
          "DemoData": {
            "location": "import",
            "path": "../../global/demo"
          },
          "GenericTableViewProps": {
            "location": "import",
            "path": "../../tables/GenericTableView"
          },
          "Invoice": {
            "location": "import",
            "path": "../../saasquatch"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [{
            "text": undefined,
            "name": "undocumented"
          }, {
            "text": "object",
            "name": "uiType"
          }],
        "text": ""
      }
    }
  }; }
}
function EmptySlot(props) {
  return (h("slot", { name: "empty" },
    h("sqm-empty", { "empty-state-image": "https://res.cloudinary.com/saasquatch/image/upload/v1710363322/squatch-assets/invoice-table-empty.png", "empty-state-header": props.emptyStateHeader, "empty-state-text": props.emptyStateText })));
}
function LoadingSlot() {
  return (h("slot", { name: "loading" },
    h(LoadingRow, null),
    h(LoadingRow, null),
    h(LoadingRow, null),
    h(LoadingRow, null)));
}
function LoadingRow() {
  return (h("sqm-table-row", null,
    h("sqm-table-cell", { colspan: 6 },
      h("sqm-skeleton", null))));
}
function useInvoiceTableDemo(props, emptyElement, loadingElement) {
  const [content, setContent] = useReducer((state, next) => ({
    ...state,
    ...next,
  }), {
    columns: [],
    rows: [],
    loading: false,
    page: 0,
  });
  const tick = useRerenderListener();
  const mockData = useMemo(() => { var _a; return ((_a = props.demoData) === null || _a === void 0 ? void 0 : _a.mockData) || mockInvoiceData(props.perPage); }, [props.perPage]);
  const components = useChildElements();
  async function getComponentData(components) {
    const componentData = mockData.data.slice(0, props.perPage);
    // filter out loading and empty states from columns array
    const columnComponents = components.filter((component) => {
      var _a, _b;
      return component.slot !== "loading" &&
        component.slot !== "empty" &&
        ((_a = component === null || component === void 0 ? void 0 : component.firstElementChild) === null || _a === void 0 ? void 0 : _a.getAttribute("slot")) !== "loading" &&
        ((_b = component === null || component === void 0 ? void 0 : component.firstElementChild) === null || _b === void 0 ? void 0 : _b.getAttribute("slot")) !== "empty";
    });
    // get the column titles (renderLabel is asynchronous)
    const columnsPromise = columnComponents === null || columnComponents === void 0 ? void 0 : columnComponents.map(async (c, idx) => {
      var _a;
      const slot = (_a = c === null || c === void 0 ? void 0 : c.firstElementChild) === null || _a === void 0 ? void 0 : _a.getAttribute("slot");
      // Custom plop targets
      if (c.tagName === "RAISINS-PLOP-TARGET" &&
        slot !== "loading" &&
        slot !== "empty") {
        c.setAttribute("slot", "column-" + idx);
        c.style.position = "absolute";
        // Replace add text with a simple + button
        const plopTarget = c.firstElementChild.childNodes[1];
        plopTarget.innerHTML = "＋";
        plopTarget.style.lineHeight = "20px";
        return tryMethod(c, () => c.renderLabel(idx));
      }
      return tryMethod(c, () => c.renderLabel());
    });
    // get the column cells (renderCell is asynchronous)
    const cellsPromise = componentData === null || componentData === void 0 ? void 0 : componentData.map(async (r) => {
      const cellPromise = columnComponents === null || columnComponents === void 0 ? void 0 : columnComponents.map(async (c) => tryMethod(c, () => c.renderCell(r, {})));
      const cells = (await Promise.all(cellPromise));
      return cells;
    });
    const cells = await Promise.all(cellsPromise);
    const rows = cells.filter((value) => value);
    setContent({ rows });
    const columns = columnsPromise && (await Promise.all(columnsPromise));
    // Set the content to render and finish loading components
    setContent({ columns, loading: false, page: 0 });
  }
  useEffect(() => {
    setContent({ loading: true });
    (mockData === null || mockData === void 0 ? void 0 : mockData.data) && getComponentData(components);
  }, [mockData === null || mockData === void 0 ? void 0 : mockData.data, components, tick]);
  const demoProps = deepmerge({
    states: {
      hasPrev: false,
      hasNext: false,
      loading: false,
      show: "rows",
    },
    callbacks: {
      prevPage: () => console.log("Prev"),
      nextPage: () => console.log("Next"),
    },
    data: {
      textOverrides: {
        showLabels: !props.hideLabels,
        prevLabel: props.prevLabel,
        moreLabel: props.moreLabel,
      },
      hiddenColumns: props.hiddenColumns,
      invoiceData: [],
      mdBreakpoint: 799,
      smBreakpoint: 599,
    },
    elements: {
      columns: content.columns,
      rows: content.rows,
      emptyElement,
      loadingElement,
    },
  }, props.demoData || {}, { arrayMerge: (_, a) => a });
  return demoProps;
}
