import { h } from "@stencil/core";
import { FormController } from "../../../../ui-components/form/form";
import { businessTermsConditionsSchema } from "../../schemas/business-terms-conditions-schema";
import { Api } from "../../../../api";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../../../api/ComponentError";
import { heading2 } from "../../../../styles/parts";
import { BusinessFormStep } from "../../utils";
export class BusinessTermsConditionsFormStep {
    constructor() {
        this.errors = {};
        this.fetchData = async () => {
            this.formLoading.emit(true);
            try {
                const response = await this.api.get({ endpoint: this.businessEndpoint, authToken: this.authToken });
                this.acceptedTermsBefore = response.data.terms_conditions_accepted;
            }
            catch (error) {
                this.errorEvent.emit({
                    errorCode: ComponentErrorCodes.FETCH_ERROR,
                    message: error.message,
                    severity: ComponentErrorSeverity.ERROR,
                    data: error,
                });
            }
            finally {
                this.formLoading.emit(false);
            }
        };
        this.sendData = async (onSuccess) => {
            this.formLoading.emit(true);
            try {
                const payload = this.termsPayload;
                const response = await this.api.post({ endpoint: this.termsConditionsEndpoint, body: payload, authToken: this.authToken });
                this.handleResponse(response, onSuccess);
            }
            catch (error) {
                this.errorEvent.emit({
                    errorCode: ComponentErrorCodes.POST_ERROR,
                    message: error.message,
                    severity: ComponentErrorSeverity.ERROR,
                    data: error,
                });
            }
            finally {
                this.formLoading.emit(false);
            }
        };
        this.inputHandler = (name, value) => {
            this.acceptedTerms = value;
            this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { [name]: value }));
        };
    }
    get businessEndpoint() {
        return `entities/business/${this.businessId}`;
    }
    get termsConditionsEndpoint() {
        return 'entities/terms_and_conditions';
    }
    get formHelperText() {
        return this.acceptedTermsBefore ? 'You have already accepted the terms and conditions.' : null;
    }
    get termsPayload() {
        return {
            business_id: this.businessId,
            accepted: this.formController.values.getValue().accepted,
            user_agent: window.navigator.userAgent
        };
    }
    async componentWillLoad() {
        this.api = Api();
        this.formController = new FormController(businessTermsConditionsSchema(this.allowOptionalFields));
        if (this.businessId && this.authToken) {
            this.fetchData();
        }
    }
    handleResponse(response, onSuccess) {
        if (response.error) {
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.POST_ERROR,
                message: response.error.message,
                severity: ComponentErrorSeverity.ERROR,
                data: response.error,
            });
        }
        else {
            onSuccess();
        }
        this.stepCompleteEvent.emit({ response: response, formStep: BusinessFormStep.termsAndConditions });
        this.formCompleted.emit();
    }
    async validateAndSubmit({ onSuccess }) {
        if (this.acceptedTermsBefore) {
            this.stepCompleteEvent.emit({ response: null, formStep: BusinessFormStep.termsAndConditions, metadata: 'no data submitted' });
            this.formCompleted.emit();
            onSuccess();
        }
        else {
            this.formController.validateAndSubmit(() => this.sendData(onSuccess));
        }
    }
    ;
    componentDidLoad() {
        this.formController.errors.subscribe(errors => {
            this.errors = Object.assign({}, errors);
        });
    }
    get merchantAgreementLink() {
        return (h("a", { href: "https://justifi.tech/merchant-agreement/", target: "_blank", rel: "noopener noreferrer" }, "merchant agreement"));
    }
    render() {
        return (h("form", { key: '24b0a8ff0187894cf5e0f56e9e4b28c378e720cb' }, h("fieldset", { key: '26fa9159dd6d61edd28b9443a10eeb981f150308' }, h("legend", { key: '103bdecbc51f2cccd9105e2f9b271b60760618ec', part: heading2 }, "Terms and Conditions"), h("hr", { key: 'dfd29fbe609a57d8160df7980ed0e63e75934a86' }), h("div", { key: '61e06597ec652c1d7c6e7e2bd8c9b653d061d076' }, h("p", { key: 'cd4def71580cd14d6edb5887221ebf6aa80cc2ea' }, "Please read and accept the ", this.merchantAgreementLink, " to submit your provisioning request.")), h("br", { key: 'e3c64733f11a4f702e686e6c5ae7acd7e6bd1c34' }), h("div", { key: '71bd74de3aee69805a2aa1297356ff8b8db3c76c', class: "row-gy-3" }, h("div", { key: '94a28c13e3bbc1c89cd1b5ebde2e1732b48f99ea', class: "col-12" }, h("form-control-checkbox", { key: 'fee95fa42192fee1bbfd544307b4e1c11c0d97f4', name: "accepted", label: "I agree to the terms and conditions", inputHandler: this.inputHandler, errorText: this.errors.accepted, disabled: this.acceptedTermsBefore, helpText: this.formHelperText, checked: this.acceptedTerms }))))));
    }
    static get is() { return "business-terms-conditions-form-step"; }
    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"
            },
            "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"
            }
        };
    }
    static get states() {
        return {
            "formController": {},
            "errors": {},
            "acceptedTermsBefore": {},
            "acceptedTerms": {}
        };
    }
    static get events() {
        return [{
                "method": "stepCompleteEvent",
                "name": "complete-form-step-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentFormStepCompleteEvent",
                    "resolved": "ComponentFormStepCompleteEvent",
                    "references": {
                        "ComponentFormStepCompleteEvent": {
                            "location": "import",
                            "path": "../../../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentFormStepCompleteEvent"
                        }
                    }
                }
            }, {
                "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": "formLoading",
                "name": "formLoading",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                }
            }, {
                "method": "formCompleted",
                "name": "formCompleted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "validateAndSubmit": {
                "complexType": {
                    "signature": "({ onSuccess }: { onSuccess: any; }) => Promise<void>",
                    "parameters": [{
                            "name": "__0",
                            "type": "{ onSuccess: any; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
}
