import { h } from "@stencil/core";
import { StyledHost } from "../../ui-components";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import JustifiAnalytics from "../../api/Analytics";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../api/ComponentError";
import { BusinessService } from "../../api/services/business.service";
import { Business } from "../../api/Business";
import { makeGetBusiness } from "../../actions/business/get-business";
import { OrderTerminalsLoading } from "./order-terminals-loading";
import { buttonPrimary, heading4, heading5, text } from "../../styles/parts";
import { TerminalSelectorLoading } from "./terminal-quantity-selector/terminal-quantity-selector-loading";
import { makeGetTerminalModels } from "../../actions/terminal/get-terminal-models";
import { TerminalService } from "../../api/services/terminal.service";
import { TerminalOrder, TerminalOrderType } from "../../api/TerminalOrder";
import { makeOrderTerminals } from "../../actions/terminal/order-terminals";
import { formatPhoneNumber } from "../../utils/utils";
export class JustifiOrderTerminals {
    constructor() {
        this.shipping = false;
        this.submitButtonText = 'Submit Order';
        this.loading = {
            business: true,
            terminals: true,
        };
        this.submitting = false;
        this.error = null;
        this.totalQuantity = 0;
    }
    componentWillLoad() {
        this.order = new TerminalOrder({
            business_id: this.businessId,
            sub_account_id: this.accountId,
            order_type: this.shipping ? TerminalOrderType.boardingShipping : TerminalOrderType.boardingOnly,
        });
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.loadData();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    ;
    handleError(errorMessage, code, severity) {
        this.error = { message: errorMessage, code, severity };
        this.errorEvent.emit({ errorCode: code, message: errorMessage, severity });
    }
    loadData() {
        if (!this.businessId || !this.authToken) {
            this.handleError("Invalid business id or auth token", ComponentErrorCodes.MISSING_PROPS, ComponentErrorSeverity.ERROR);
            return;
        }
        this.initializeGetBusiness();
        this.initializeGetTerminalModels();
    }
    initializeGetBusiness() {
        makeGetBusiness({
            id: this.businessId,
            authToken: this.authToken,
            service: new BusinessService()
        })({
            onSuccess: ({ business }) => {
                this.business = new Business(business);
            },
            onError: ({ error, code, severity }) => {
                this.handleError(error, code, severity);
            },
            final: () => {
                this.loading.business = false;
            },
        });
    }
    initializeGetTerminalModels() {
        makeGetTerminalModels({
            id: this.accountId,
            authToken: this.authToken,
            service: new TerminalService()
        })({
            onSuccess: ({ terminals, orderLimit }) => {
                this.terminalModels = terminals;
                this.orderLimit = orderLimit;
                this.loading.terminals = false;
            },
            onError: ({ error, code, severity }) => {
                this.handleError(error, code, severity);
                this.loading.terminals = false;
            }
        });
    }
    submitOrder() {
        const orderTerminals = makeOrderTerminals({
            authToken: this.authToken,
            service: new TerminalService()
        });
        this.submitting = true;
        orderTerminals({
            terminalOrder: this.order.payload,
            onSuccess: ({ data }) => {
                this.submitted.emit(data);
                this.submitting = false;
            },
            onError: ({ error, code, severity }) => {
                this.handleError(error, code, severity);
                this.submitting = false;
            }
        });
    }
    onSelectedQuantityChange(event) {
        this.order.updateTerminal(event.detail.modelName, event.detail.quantity);
        this.totalQuantity = this.order.totalQuantity;
    }
    renderLoading() {
        return (h("div", null, this.loading.business && h(OrderTerminalsLoading, null), this.loading.terminals && (h("div", { class: "mt-5" }, h(TerminalSelectorLoading, null), h(TerminalSelectorLoading, null), h(TerminalSelectorLoading, null)))));
    }
    renderBusinessDetails() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        if (!this.loading.business && this.business) {
            return (h("div", { class: "d-flex flex-column gap-4 mb-5 pt-5" }, h("div", { class: "row" }, h("div", { class: "col-12" }, h("h2", { part: heading4 }, this.business.legal_name))), h("div", { class: "row" }, h("div", { class: "col-6" }, h("h5", { part: heading5 }, "Representative:"), h("div", null, h("div", null, (_b = (_a = this.business) === null || _a === void 0 ? void 0 : _a.representative) === null || _b === void 0 ? void 0 : _b.name), h("div", null, (_d = (_c = this.business) === null || _c === void 0 ? void 0 : _c.representative) === null || _d === void 0 ? void 0 : _d.title), h("div", null, (_f = (_e = this.business) === null || _e === void 0 ? void 0 : _e.representative) === null || _f === void 0 ? void 0 : _f.email), h("div", null, formatPhoneNumber((_h = (_g = this.business) === null || _g === void 0 ? void 0 : _g.representative) === null || _h === void 0 ? void 0 : _h.phone)))), h("div", { class: "col-6" }, h("h5", { part: heading5 }, this.shipping ? "Shipping Address:" : "Business Address:"), h("div", null, this.business.legal_address.line1, this.business.legal_address.line2 ? `, ${this.business.legal_address.line2}` : "", h("br", null), this.business.legal_address.city, ", ", this.business.legal_address.state, " ", this.business.legal_address.postal_code)))));
        }
    }
    renderTerminals() {
        if (!this.loading.terminals && this.terminalModels) {
            return (h("div", { class: "d-flex flex-column gap-2 mt-5" }, this.terminalModels.map((terminal) => (h("terminal-quantity-selector", { modelName: terminal.model_name, description: terminal.description, imageUrl: terminal.image_url, helpUrl: terminal.help_url, limit: this.orderLimit - this.order.totalQuantity, onSelectedQuantityChange: this.onSelectedQuantityChange.bind(this) })))));
        }
    }
    renderOrderSection() {
        return (h("div", { class: "mt-3" }, h("div", { class: "text-end" }, "Order limit: ", this.orderLimit), h("div", { class: "d-flex justify-content-end mt-3" }, h("button", { class: "btn btn-primary submit-btn", onClick: this.submitOrder.bind(this), disabled: this.order.totalQuantity === 0 || this.submitting, part: buttonPrimary }, this.submitting ? 'Submitting...' : this.submitButtonText))));
    }
    render() {
        return (h(StyledHost, { key: '1fd8c50ac4e22bb2aac46ed0379f4740737e9760' }, h("div", { key: 'caed839c05af25c7bcd6599c45cd5058491a1ba9', part: text }, this.renderLoading(), this.renderBusinessDetails(), this.renderTerminals(), this.renderOrderSection())));
    }
    static get is() { return "justifi-order-terminals"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "businessId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "business-id"
            },
            "authToken": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "auth-token"
            },
            "accountId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "account-id"
            },
            "shipping": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "shipping",
                "defaultValue": "false"
            },
            "submitButtonText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "submit-button-text",
                "defaultValue": "'Submit Order'"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "submitting": {},
            "error": {},
            "business": {},
            "terminalModels": {},
            "orderLimit": {},
            "order": {},
            "totalQuantity": {}
        };
    }
    static get events() {
        return [{
                "method": "errorEvent",
                "name": "error-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentErrorEvent",
                    "resolved": "ComponentErrorEvent",
                    "references": {
                        "ComponentErrorEvent": {
                            "location": "import",
                            "path": "../../api",
                            "id": "src/api/index.ts::ComponentErrorEvent"
                        }
                    }
                }
            }, {
                "method": "submitted",
                "name": "submit-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
}
