import { h } from "@stencil/core";
import { FormController } from "../../../ui-components/form/form";
import { businessFormSchema } from "../schemas/business-form-schema";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../../api";
import { Business, BusinessFormServerErrors } from "../../../api/Business";
import JustifiAnalytics from "../../../api/Analytics";
import { Button, Header1, StyledHost } from "../../../ui-components";
import { CountryCode } from "../../../utils/country-codes";
import { checkPkgVersion } from "../../../utils/check-pkg-version";
import { BusinessFormLoading } from "./business-form-loading";
import { BusinessFormClickActions } from "../utils";
import { makeGetBusiness, makePatchBusiness } from "../payment-provisioning/payment-provisioning-actions";
import { BusinessService } from "../../../api/services/business.service";
export class JustifiBusinessForm {
    constructor() {
        this.isLoading = false;
        this.isSaving = false;
        this.country = CountryCode.USA;
        this.hideErrors = false;
        this.formTitle = 'Business Information';
        this.removeTitle = false;
        this.instantiateBusiness = (data) => {
            const business = new Business(data);
            this.country = business.country_of_establishment;
            this.formController.setInitialValues(Object.assign({}, business));
        };
        this.sendData = async () => {
            this.isSaving = true;
            const values = this.formController.values.getValue();
            const initialValues = this.formController.getInitialValues();
            const payload = new Business(Object.assign(Object.assign({}, initialValues), values)).payload;
            this.patchBusiness({
                payload,
                onSuccess: (response) => {
                    this.handleReponse(response);
                },
                onError: ({ error, code, severity }) => {
                    this.errorMessage = error.message;
                    this.errorEvent.emit({ errorCode: code, message: error.message, severity });
                },
                final: () => {
                    this.isSaving = false;
                }
            });
        };
        this.validateAndSubmit = (event) => {
            event.preventDefault();
            this.formController.validateAndSubmit(this.sendData);
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.formController = new FormController(businessFormSchema);
        this.initializeApi();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    ;
    get title() {
        return this.removeTitle ? '' : this.formTitle;
    }
    get disabledState() {
        return this.isSaving;
    }
    get businessEndpoint() {
        return `entities/business/${this.businessId}`;
    }
    initializeApi() {
        if (this.authToken && this.businessId) {
            this.getBusiness = makeGetBusiness({
                authToken: this.authToken,
                businessId: this.businessId,
                service: new BusinessService()
            });
            this.patchBusiness = makePatchBusiness({
                authToken: this.authToken,
                businessId: this.businessId,
                service: new BusinessService()
            });
            this.getBusiness({
                onSuccess: (response) => {
                    this.instantiateBusiness(response.data);
                },
                onError: ({ error, code, severity }) => {
                    this.errorMessage = error.message;
                    this.errorEvent.emit({ errorCode: code, message: error.message, severity });
                },
                final: () => {
                    this.isLoading = false;
                }
            });
        }
        else {
            this.errorEvent.emit({
                message: 'auth-token and business-id are required',
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    handleReponse(response) {
        if (response.error) {
            this.errorMessage = BusinessFormServerErrors.patchData;
        }
        this.submitEvent.emit({ response });
        this.instantiateBusiness(response.data);
    }
    render() {
        if (this.isLoading) {
            return h(StyledHost, null, h(BusinessFormLoading, null));
        }
        return (h(StyledHost, null, h("form", { onSubmit: this.validateAndSubmit }, h("div", { class: "row gap-3" }, h(Header1, { text: this.title }), h("form-alert", { text: this.errorMessage, hideAlert: this.hideErrors }), h("div", { class: "col-12 mb-4" }, h("business-core-info", { formController: this.formController, country: this.country })), h("div", { class: "col-12 mb-4" }, h("legal-address-form", { formController: this.formController, country: this.country })), h("div", { class: "col-12 mb-4" }, h("additional-questions", { formController: this.formController })), h("div", { class: "col-12 mb-4" }, h("business-representative", { formController: this.formController, country: this.country })), h("div", { class: "col-12 d-flex flex-row-reverse" }, h(Button, { type: "submit", disabled: this.disabledState, variant: 'primary', onClick: () => this.clickEvent.emit({ name: BusinessFormClickActions.submit }), isLoading: this.isSaving }, "Submit"))))));
    }
    static get is() { return "justifi-business-form"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "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"
            },
            "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"
            },
            "hideErrors": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "hide-errors",
                "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'"
            },
            "removeTitle": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "remove-title",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "isSaving": {},
            "errorMessage": {},
            "country": {}
        };
    }
    static get events() {
        return [{
                "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"
                        }
                    }
                }
            }, {
                "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"
                        }
                    }
                }
            }];
    }
}
