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 { CountryCode } from "../../../../utils/country-codes";
import { businessCoreInfoSchemaUSA, businessCoreInfoSchemaCAN } from "../../schemas/business-core-info-schema";
import { FormController } from "../../../../ui-components/form/form";
import { CoreBusinessInfo } from "../../../../api/Business";
import { BusinessFormStep, businessClassificationOptions } from "../../utils";
import { PHONE_MASKS } from "../../../../utils/form-input-masks";
import { heading2, label, inputDisabled, buttonSecondary } from "../../../../styles/parts";
import { PaymentProvisioningLoading } from "../payment-provisioning-loading";
import { countryLabels } from "../../utils/country-config";
export class BusinessCoreInfoFormStep {
    constructor() {
        this.errors = {};
        this.coreInfo = {};
        this.isLoading = false;
        this.isEditingTaxId = false;
        this.getData = () => {
            if (!this.getBusiness)
                return;
            this.formLoading.emit(true);
            this.isLoading = true;
            this.getBusiness({
                onSuccess: (response) => {
                    this.coreInfo = new CoreBusinessInfo(response.data);
                    this.formController.setInitialValues(Object.assign({}, this.coreInfo));
                },
                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();
                    // after successful patch, revert back to read-only for tax id
                    this.isEditingTaxId = false;
                },
                onError: ({ error, code, severity, rawError }) => {
                    submittedData = error;
                    // Set field-specific error if param exists
                    if (rawError && typeof rawError === 'object' && rawError.param) {
                        this.formController.setFieldError(rawError.param, rawError.message);
                    }
                    // Still emit component-level error
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.stepCompleteEvent.emit({ response: submittedData, formStep: BusinessFormStep.businessInfo });
                    this.formLoading.emit(false);
                }
            });
        };
        this.inputHandler = (name, value) => {
            // Clear backend error when user edits field
            if (this.errors[name]) {
                this.formController.clearFieldError(name);
            }
            this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { [name]: value }));
        };
    }
    propChanged() {
        this.initializeApi();
    }
    async validateAndSubmit({ onSuccess }) {
        this.formController.validateAndSubmit(() => this.sendData(onSuccess));
    }
    get patchPayload() {
        const formValues = new CoreBusinessInfo(this.formController.values.getValue()).payload;
        return formValues;
    }
    componentWillLoad() {
        this.initializeApi();
        const schema = (this.country === CountryCode.CAN)
            ? businessCoreInfoSchemaCAN(this.allowOptionalFields)
            : businessCoreInfoSchemaUSA(this.allowOptionalFields);
        this.formController = new FormController(schema);
        this.getData();
    }
    componentDidLoad() {
        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;
        const coreInfoDefaultValue = 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 }, "Business Information")), h("hr", { class: "mt-2" }), h("div", { class: "row gy-3" }, h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "legal_name", label: "Business Name", defaultValue: coreInfoDefaultValue.legal_name, errorText: this.errors.legal_name, inputHandler: this.inputHandler, helpText: "Enter this exactly as it appears on your tax records (don't use acronyms or abbreviations unless you registered that way)." })), h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "doing_business_as", label: "Doing Business As (DBA)", defaultValue: coreInfoDefaultValue.doing_business_as, errorText: this.errors.doing_business_as, inputHandler: this.inputHandler, helpText: "Enter this exactly as it appears on your tax records (leave blank if you don't have a registered DBA/trade name)" })), h("div", { class: "col-12 col-md-8" }, h("form-control-select", { name: "classification", label: "Business Classification", options: businessClassificationOptions, defaultValue: coreInfoDefaultValue.classification, errorText: this.errors.classification, inputHandler: this.inputHandler })), h("div", { class: "col-12 col-md-4" }, h("form-control-date", { name: "date_of_incorporation", label: "Date of Registration", defaultValue: coreInfoDefaultValue.date_of_incorporation, errorText: this.errors.date_of_incorporation, inputHandler: this.inputHandler })), h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "industry", label: "Industry", defaultValue: coreInfoDefaultValue.industry, errorText: this.errors.industry, inputHandler: this.inputHandler, helpText: "Describe what you sell" })), h("div", { class: "col-12 col-md-6" }, (!((_a = this.coreInfo) === null || _a === void 0 ? void 0 : _a.tax_id_last4) || this.isEditingTaxId) ? (h("form-control-number-masked", { name: "tax_id", label: countryLabels[this.country].taxIdLabelOptional || countryLabels[this.country].taxIdLabel, defaultValue: this.isEditingTaxId ? '' : coreInfoDefaultValue.tax_id, errorText: this.errors.tax_id, inputHandler: this.inputHandler, mask: '000000000', helpText: countryLabels[this.country].taxIdHelpText })) : (h("div", null, h("label", { class: "form-label", part: label }, countryLabels[this.country].taxIdLabel), h("div", { class: "input-group mb-3" }, h("input", { type: "text", class: "form-control", part: inputDisabled, value: `****${(_b = this.coreInfo) === null || _b === void 0 ? void 0 : _b.tax_id_last4}`, disabled: true }), h("button", { class: "btn btn-secondary", type: "button", part: buttonSecondary, onClick: () => {
                this.isEditingTaxId = true;
                // Clear last4-equivalent and current value if any future conditional validation depends on it
                this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { tax_id: '', tax_id_last4: null }));
            } }, "Change"))))), h("div", { class: "col-12" }, h("form-control-text", { name: "website_url", label: "Business Website URL", defaultValue: coreInfoDefaultValue.website_url, errorText: this.errors.website_url, inputHandler: this.inputHandler, helpText: "Don't have a live website? You can use your social media business page, app store link, or staging site URL." })), h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "email", label: "Business Email Address", defaultValue: coreInfoDefaultValue.email, errorText: this.errors.email, inputHandler: this.inputHandler })), h("div", { class: "col-12 col-md-6" }, h("form-control-number-masked", { name: "phone", label: "Business Phone Number", defaultValue: coreInfoDefaultValue.phone, errorText: this.errors.phone, inputHandler: this.inputHandler, mask: PHONE_MASKS.US }))))));
    }
    static get is() { return "business-core-info-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"
            },
            "country": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "CountryCode",
                    "resolved": "CountryCode.CAN | CountryCode.USA",
                    "references": {
                        "CountryCode": {
                            "location": "import",
                            "path": "../../../../utils/country-codes",
                            "id": "src/utils/country-codes.ts::CountryCode"
                        }
                    }
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "country"
            }
        };
    }
    static get states() {
        return {
            "getBusiness": {},
            "patchBusiness": {},
            "formController": {},
            "errors": {},
            "coreInfo": {},
            "isLoading": {},
            "isEditingTaxId": {}
        };
    }
    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"
            }];
    }
}
