import { h } from "@stencil/core";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../../../api/ComponentError";
import { makeGetBusiness, makePatchBusiness } from "../payment-provisioning-actions";
import { BusinessService } from "../../../../api/services/business.service";
import { additionalQuestionsSchema } from "../../schemas/business-additional-questions-schema";
import { FormController } from "../../../../ui-components/form/form";
import { AdditionalQuestions } from "../../../../api/Business";
import { CURRENCY_MASK } from "../../../../utils/form-input-masks";
import { heading2 } from "../../../../styles/parts";
import { PaymentProvisioningLoading } from "../payment-provisioning-loading";
import { BusinessFormStep, businessServiceReceivedOptions } from "../../utils";
export class AdditionalQuestionsFormStep {
    constructor() {
        this.errors = {};
        this.additional_questions = {};
        this.recurringPayments = false;
        this.isLoading = false;
        this.getData = () => {
            this.formLoading.emit(true);
            this.isLoading = true;
            this.getBusiness({
                onSuccess: (response) => {
                    this.additional_questions = new AdditionalQuestions(response.data.additional_questions || {});
                    this.formController.setInitialValues(Object.assign({}, this.additional_questions));
                },
                onError: ({ error, code, severity }) => {
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.formLoading.emit(false);
                    this.isLoading = false;
                }
            });
        };
        this.sendData = (onSuccess) => {
            let submittedData;
            this.formLoading.emit(true);
            this.patchBusiness({
                payload: this.patchPayload,
                onSuccess: (response) => {
                    submittedData = response;
                    onSuccess();
                },
                onError: ({ error, code, severity }) => {
                    submittedData = error;
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.stepCompleteEvent.emit({ response: submittedData, formStep: BusinessFormStep.additionalQuestions });
                    this.formLoading.emit(false);
                }
            });
        };
        this.inputHandler = (name, value) => {
            this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { [name]: value }));
            this.additional_questions = new AdditionalQuestions(Object.assign(Object.assign({}, this.formController.values.getValue()), { [name]: value }));
        };
    }
    propChanged() {
        this.initializeApi();
    }
    recurringPaymentsWatcher(newValue) {
        if ((newValue === null || newValue === void 0 ? void 0 : newValue.business_recurring_payments) === 'Yes') {
            this.recurringPayments = true;
        }
        else {
            this.recurringPayments = false;
        }
    }
    async validateAndSubmit({ onSuccess }) {
        this.formController.validateAndSubmit(() => this.sendData(onSuccess));
    }
    get patchPayload() {
        const formValues = new AdditionalQuestions(this.formController.values.getValue()).payload;
        return { additional_questions: formValues };
    }
    componentWillLoad() {
        this.initializeApi();
        this.formController = new FormController(additionalQuestionsSchema(this.allowOptionalFields));
    }
    componentDidLoad() {
        this.getBusiness && this.getData();
        this.formController.errors.subscribe(errors => {
            this.errors = Object.assign({}, errors);
        });
    }
    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()
            });
        }
        else {
            this.errorEvent.emit({
                message: 'Missing required props',
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    render() {
        var _a, _b, _c, _d, _e;
        const additionalQuestionsDefaultValue = this.formController.getInitialValues();
        if (this.isLoading) {
            return h(PaymentProvisioningLoading, null);
        }
        return (h("form", null, h("fieldset", null, h("div", { class: "d-flex align-items-center gap-2" }, h("legend", { class: "mb-0", part: heading2 }, "Additional Questions"), h("form-control-tooltip", { helpText: "This information helps us understand the business and identify and monitor trends to safeguard you and your customers." })), h("hr", { class: "mt-2" }), h("div", { class: "row gy-3" }, h("div", { class: "col-12 col-md-6" }, h("form-control-monetary-provisioning", { name: "business_revenue", label: "What is your business' estimated annual revenue from its primary business activities?", inputHandler: this.inputHandler, errorText: (_a = this.errors) === null || _a === void 0 ? void 0 : _a.business_revenue, defaultValue: additionalQuestionsDefaultValue === null || additionalQuestionsDefaultValue === void 0 ? void 0 : additionalQuestionsDefaultValue.business_revenue, maskOptions: CURRENCY_MASK.WHOLE })), h("div", { class: "col-12 col-md-6" }, h("form-control-monetary-provisioning", { name: "business_payment_volume", label: "What is your business' annual credit card & ACH volume anticipated to process?", inputHandler: this.inputHandler, errorText: (_b = this.errors) === null || _b === void 0 ? void 0 : _b.business_payment_volume, defaultValue: additionalQuestionsDefaultValue === null || additionalQuestionsDefaultValue === void 0 ? void 0 : additionalQuestionsDefaultValue.business_payment_volume, maskOptions: CURRENCY_MASK.WHOLE })), h("div", { class: "col-12" }, h("form-control-number", { name: "business_average_transaction_amount", label: "What is your average transaction size?", inputHandler: this.inputHandler, errorText: (_c = this.errors) === null || _c === void 0 ? void 0 : _c.business_average_transaction_amount, defaultValue: additionalQuestionsDefaultValue === null || additionalQuestionsDefaultValue === void 0 ? void 0 : additionalQuestionsDefaultValue.business_average_transaction_amount })), h("div", { class: "col-12" }, h("form-control-select", { name: "business_when_service_received", label: "On average, how long after paying will your customers typically receive their goods or services?", inputHandler: this.inputHandler, errorText: (_d = this.errors) === null || _d === void 0 ? void 0 : _d.business_when_service_received, options: businessServiceReceivedOptions, defaultValue: additionalQuestionsDefaultValue === null || additionalQuestionsDefaultValue === void 0 ? void 0 : additionalQuestionsDefaultValue.business_when_service_received })), h("div", { class: "col-12" }, h("form-control-text", { name: "business_other_payment_details", label: "Is there anything else you would like us to know about how your customers pay the business? (optional)", inputHandler: this.inputHandler, errorText: (_e = this.errors) === null || _e === void 0 ? void 0 : _e.business_other_payment_details, defaultValue: additionalQuestionsDefaultValue === null || additionalQuestionsDefaultValue === void 0 ? void 0 : additionalQuestionsDefaultValue.business_other_payment_details }))))));
    }
    static get is() { return "additional-questions-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 {
            "getBusiness": {},
            "patchBusiness": {},
            "formController": {},
            "errors": {},
            "additional_questions": {},
            "recurringPayments": {},
            "isLoading": {}
        };
    }
    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/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentErrorEvent"
                        }
                    }
                }
            }, {
                "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": "formLoading",
                "name": "formLoading",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "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": []
                }
            }
        };
    }
    static get watchers() {
        return [{
                "propName": "authToken",
                "methodName": "propChanged"
            }, {
                "propName": "businessId",
                "methodName": "propChanged"
            }, {
                "propName": "additional_questions",
                "methodName": "recurringPaymentsWatcher"
            }];
    }
}
