import { h, } from "@stencil/core";
import JustifiAnalytics from "../../../api/Analytics";
import { ComponentErrorCodes, ComponentErrorSeverity, } from "../../../api/ComponentError";
import { makeGetBusiness, makePostProvisioning, } from "./payment-provisioning-actions";
import { BusinessService } from "../../../api/services/business.service";
import { ProvisionService } from "../../../api/services/provision.service";
import { checkPkgVersion } from "../../../utils/check-pkg-version";
import { isTokenExpired } from "../../../utils/utils";
import { checkProvisioningStatus } from "../utils/helpers";
import { Header1, StyledHost } from "../../../ui-components";
import { text } from "../../../styles/parts";
import { BusinessFormClickActions } from "../utils/event-types";
import { CountryCode } from "../../../utils/country-codes";
import { Business } from "../../../api/Business";
import { PaymentProvisioningLoading } from "./payment-provisioning-loading";
import { PaymentProvisioningAlreadyProvisioned } from "./payment-provisioning-already-provisioned";
import { PaymentProvisioningSubmissionComplete } from "./payment-provisioning-submission-complete";
import { PaymentProvisioningSubmissionFailed } from "./payment-provisioning-submission-failed";
export class JustifiPaymentProvisioning {
    constructor() {
        this.loading = false;
        this.businessLoading = true;
        this.businessProvisioned = false;
        this.formSubmitted = false;
        this.submissionFailed = false;
        this.currentStep = 0;
        this.country = CountryCode.USA;
        this.allowOptionalFields = false;
        this.formTitle = 'Business Information';
        this.refs = [];
        this.setBusinessProvisioned = () => {
            return new Promise((resolve) => {
                this.getBusiness({
                    onSuccess: (response) => {
                        const business = new Business(response.data);
                        this.businessProvisioned = checkProvisioningStatus(business);
                        this.country = business.country_of_establishment;
                        if (this.businessProvisioned) {
                            this.errorEvent.emit({
                                message: 'A request to provision payments for this business has already been submitted.',
                                errorCode: ComponentErrorCodes.PROVISIONING_REQUESTED,
                                severity: ComponentErrorSeverity.INFO,
                            });
                        }
                        this.businessLoading = false;
                        resolve();
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            message: error,
                            errorCode: code,
                            severity: severity,
                        });
                        this.businessLoading = false;
                        resolve();
                    },
                });
            });
        };
        this.postProvisioningData = () => {
            this.postProvisioning({
                onSuccess: (response) => {
                    this.formSubmitted = true;
                    this.submitEvent.emit({ response: response });
                },
                onError: ({ error, code, severity }) => {
                    this.submissionFailed = true;
                    this.submitEvent.emit({ response: { error } });
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity,
                    });
                },
            });
        };
        this.incrementSteps = () => {
            if (this.currentStep < this.totalSteps) {
                return this.currentStep++;
            }
        };
        this.decrementSteps = () => {
            if (this.currentStep > 0) {
                this.currentStep -= 1;
            }
        };
        this.previousStepButtonOnClick = () => {
            this.clickEvent.emit({ name: BusinessFormClickActions.previousStep });
            this.decrementSteps();
        };
        this.nextStepButtonOnClick = (e, clickEventName) => {
            e.preventDefault();
            this.clickEvent.emit({ name: clickEventName });
            const currentStep = this.refs[this.currentStep];
            currentStep.validateAndSubmit({ onSuccess: this.incrementSteps });
        };
    }
    propChanged() {
        this.initializeApi();
    }
    handleFormCompleted() {
        this.postProvisioningData();
    }
    handleFormLoading(event) {
        this.loading = event.detail;
    }
    async componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.initializeApi();
        if (this.getBusiness) {
            await this.setBusinessProvisioned();
        }
        else {
            this.businessLoading = false;
        }
        this.refs = new Array(8);
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    initializeApi() {
        if (!this.authToken || !this.businessId) {
            this.errorEvent.emit({
                message: 'auth-token and business-id are required',
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
            return;
        }
        if (isTokenExpired(this.authToken)) {
            this.errorEvent.emit({
                message: 'auth-token is expired',
                errorCode: ComponentErrorCodes.NOT_AUTHENTICATED,
                severity: ComponentErrorSeverity.ERROR,
            });
            return;
        }
        this.getBusiness = makeGetBusiness({
            authToken: this.authToken,
            businessId: this.businessId,
            service: new BusinessService(),
        });
        this.postProvisioning = makePostProvisioning({
            authToken: this.authToken,
            businessId: this.businessId,
            product: 'payment',
            service: new ProvisionService(),
        });
    }
    get formDisabled() {
        return this.loading || this.businessProvisioned;
    }
    get totalSteps() {
        return this.refs.length - 1;
    }
    get stepCounter() {
        return `Step ${this.currentStep + 1} of ${this.totalSteps + 1}`;
    }
    render() {
        if (this.businessLoading) {
            return (h(StyledHost, null, h(PaymentProvisioningLoading, null)));
        }
        if (this.businessProvisioned) {
            return (h(StyledHost, null, h(PaymentProvisioningAlreadyProvisioned, null)));
        }
        if (this.formSubmitted) {
            return (h(StyledHost, null, h(PaymentProvisioningSubmissionComplete, null)));
        }
        if (this.submissionFailed) {
            return (h(StyledHost, null, h(PaymentProvisioningSubmissionFailed, null)));
        }
        return (h(StyledHost, null, h("div", { class: "row gap-3" }, h(Header1, { text: this.formTitle }), h("payment-provisioning-form-steps", { businessId: this.businessId, authToken: this.authToken, refs: this.refs, currentStep: this.currentStep, allowOptionalFields: this.allowOptionalFields, country: this.country, handleFormLoading: this.handleFormLoading }), h("div", { class: "d-flex justify-content-between align-items-center" }, h("div", { class: "d-flex align-items-center", part: text }, this.stepCounter), h("payment-provisioning-form-buttons", { currentStep: this.currentStep, totalSteps: this.totalSteps, formLoading: this.loading, formDisabled: this.formDisabled, previousStepButtonOnClick: this.previousStepButtonOnClick, nextStepButtonOnClick: this.nextStepButtonOnClick })))));
    }
    static get is() { return "justifi-payment-provisioning"; }
    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"
            },
            "allowOptionalFields": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "allow-optional-fields",
                "defaultValue": "false"
            },
            "formTitle": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "form-title",
                "defaultValue": "'Business Information'"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "businessLoading": {},
            "businessProvisioned": {},
            "formSubmitted": {},
            "submissionFailed": {},
            "currentStep": {},
            "errorMessage": {},
            "country": {}
        };
    }
    static get events() {
        return [{
                "method": "clickEvent",
                "name": "click-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentClickEvent",
                    "resolved": "ComponentClickEvent",
                    "references": {
                        "ComponentClickEvent": {
                            "location": "import",
                            "path": "../../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentClickEvent"
                        }
                    }
                }
            }, {
                "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/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentErrorEvent"
                        }
                    }
                }
            }, {
                "method": "submitEvent",
                "name": "submit-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentSubmitEvent",
                    "resolved": "ComponentSubmitEvent",
                    "references": {
                        "ComponentSubmitEvent": {
                            "location": "import",
                            "path": "../../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentSubmitEvent"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "authToken",
                "methodName": "propChanged"
            }, {
                "propName": "businessId",
                "methodName": "propChanged"
            }];
    }
    static get listeners() {
        return [{
                "name": "formCompleted",
                "method": "handleFormCompleted",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "formLoading",
                "method": "handleFormLoading",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
