import { h } from "@stencil/core";
import { ComponentErrorCodes, ComponentErrorSeverity, BankAccount } from "../../../../api";
import { makeGetBusiness, makePostBankAccount } from "../payment-provisioning-actions";
import { BusinessService, BusinessBankAccountService } from "../../../../api/services/business.service";
import { CountryCode } from "../../../../utils/country-codes";
import { bankAccountSchemaByCountry } from "../../schemas/business-bank-account-schema";
import { FormController } from "../../../../ui-components/form/form";
import { BusinessFormStep } from "../../utils";
import { heading2, buttonSecondary, buttonLink } from "../../../../styles/parts";
import { PaymentProvisioningLoading } from "../payment-provisioning-loading";
import { Button } from "../../../../ui-components";
export class BusinessBankAccountFormStep {
    constructor() {
        this.errors = {};
        this.bankAccount = {};
        this.isLoading = false;
        this.viewMode = 'manual';
        this.bankAccountVerification = false;
        this.platformAccountId = null;
        this.getSchema = () => {
            const schema = bankAccountSchemaByCountry[this.country];
            return schema(this.allowOptionalFields);
        };
        this.initializeFormController = () => {
            this.formController = new FormController(this.getSchema());
            if (this.viewMode === 'readonly') {
                this.formController.setInitialValues(Object.assign({}, this.bankAccount));
            }
            else {
                this.formController.setInitialValues({ business_id: this.businessId });
            }
            this.formController.errors.subscribe(errors => {
                this.errors = Object.assign({}, errors);
            });
        };
        this.inputHandler = (name, value) => {
            this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { [name]: value }));
        };
        this.getData = () => {
            this.isLoading = true;
            this.getBusiness({
                onSuccess: (response) => {
                    this.processBusinessResponse(response.data);
                    this.determineViewMode();
                },
                onError: ({ error, code, severity }) => {
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.initializeFormController();
                    this.isLoading = false;
                }
            });
        };
        this.handleChangeBankAccount = () => {
            this.viewMode = this.plaidAvailable ? 'plaid' : 'manual';
            this.initializeFormController();
        };
        this.handleCancel = () => {
            this.viewMode = this.existingBankAccount ? 'readonly' : 'plaid';
            this.initializeFormController();
        };
        this.handleToggleToManualEntry = () => {
            this.viewMode = 'manual';
        };
        this.handleToggleToPlaidVerification = () => {
            this.viewMode = 'plaid';
        };
        this.handleSaveBankAccount = async () => {
            this.formController.validateAndSubmit(() => {
                this.sendData(() => {
                    // Success callback - form will refresh automatically
                });
            });
        };
    }
    propChanged() {
        this.initializeApi();
    }
    watchHandler(newValue) {
        this.formLoading.emit(newValue);
    }
    async validateAndSubmit({ onSuccess }) {
        if (this.viewMode === 'readonly') {
            this.sendData(onSuccess);
        }
        else {
            this.formController.validateAndSubmit(() => this.sendData(onSuccess));
        }
    }
    componentWillLoad() {
        this.initializeApi();
        if (this.getBusiness) {
            this.getData();
        }
        this.formController = new FormController(this.getSchema());
    }
    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.postBankAccount = makePostBankAccount({
                authToken: this.authToken,
                service: new BusinessBankAccountService()
            });
        }
        else {
            this.errorEvent.emit({
                message: 'Missing required props',
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    get postPayload() {
        const values = this.formController.values.getValue();
        const formValues = new BankAccount(values).payload;
        return formValues;
    }
    get existingBankAccount() {
        var _a;
        return !!((_a = this.bankAccount) === null || _a === void 0 ? void 0 : _a.id);
    }
    get plaidAvailable() {
        return this.bankAccountVerification && !!this.platformAccountId;
    }
    get showCancel() {
        return this.bankAccountVerification || this.existingBankAccount;
    }
    processBusinessResponse(data) {
        const { bank_accounts, settings, platform_account_id } = data;
        if (bank_accounts.length > 0) {
            this.bankAccount = new BankAccount(bank_accounts[bank_accounts.length - 1]);
        }
        else {
            this.bankAccount = new BankAccount({});
            this.bankAccount.business_id = this.businessId;
        }
        this.bankAccountVerification = settings.bank_account_verification === true;
        this.platformAccountId = platform_account_id;
    }
    determineViewMode() {
        if (this.existingBankAccount) {
            this.viewMode = 'readonly';
        }
        else if (this.plaidAvailable) {
            this.viewMode = 'plaid';
        }
        else {
            this.viewMode = 'manual';
        }
    }
    async sendData(onSuccess) {
        try {
            if (this.viewMode === 'manual') {
                const bankAccountPosted = await this.postBankAccountData();
                if (!bankAccountPosted)
                    return;
                this.viewMode = 'readonly';
                await this.refreshBankAccountData();
            }
            onSuccess();
        }
        catch (error) {
            this.errorEvent.emit({
                message: error,
                errorCode: ComponentErrorCodes.POST_ERROR,
                severity: ComponentErrorSeverity.ERROR
            });
        }
    }
    async postBankAccountData() {
        let submittedData;
        this.isLoading = true;
        return new Promise((resolve) => {
            let success = false;
            this.postBankAccount({
                payload: this.postPayload,
                onSuccess: (response) => {
                    submittedData = response;
                    success = true;
                },
                onError: ({ error, code, severity }) => {
                    success = false;
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.stepCompleteEvent.emit({ response: submittedData, formStep: BusinessFormStep.bankAccount });
                    this.isLoading = false;
                    resolve(success);
                }
            });
        });
    }
    async refreshBankAccountData() {
        return new Promise((resolve) => {
            this.isLoading = true;
            this.getBusiness({
                onSuccess: (response) => {
                    this.processBusinessResponse(response.data);
                    this.determineViewMode();
                    this.initializeFormController();
                },
                onError: ({ error, code, severity }) => {
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.isLoading = false;
                    resolve();
                }
            });
        });
    }
    renderBankAccountInputs(disabled) {
        const defaultValue = this.formController.getInitialValues();
        return this.country === CountryCode.CAN ? (h("bank-account-form-inputs-canada", { defaultValue: defaultValue, errors: this.errors, inputHandler: this.inputHandler, formDisabled: disabled })) : (h("bank-account-form-inputs", { defaultValue: defaultValue, errors: this.errors, inputHandler: this.inputHandler, formDisabled: disabled }));
    }
    renderReadonlyView() {
        return (h("div", null, this.renderBankAccountInputs(true), h("div", { class: "mt-3" }, h(Button, { variant: "secondary", type: "button", onClick: this.handleChangeBankAccount, disabled: this.isLoading, part: buttonSecondary }, "Change Bank Account"))));
    }
    renderPlaidView() {
        return (h("div", { class: "mt-3" }, h("plaid-verification", { authToken: this.authToken, accountId: this.platformAccountId, businessId: this.businessId, onPlaidVerificationSuccess: () => {
                this.viewMode = 'readonly';
                this.refreshBankAccountData();
            } }), h("div", { class: "mt-3" }, h(Button, { type: "button", variant: "link", className: "p-0", onClick: this.handleToggleToManualEntry, disabled: this.isLoading, part: buttonLink }, "Enter bank details manually (document upload required)"))));
    }
    renderManualEntryView() {
        return (h("div", null, this.plaidAvailable && (h("div", { class: "mb-3" }, h(Button, { type: "button", variant: "secondary", onClick: this.handleToggleToPlaidVerification, disabled: this.isLoading, part: buttonSecondary }, "Link bank account with Plaid instead"))), this.renderBankAccountInputs(false), h("div", { class: "mt-3 d-flex gap-2" }, this.showCancel && (h(Button, { variant: "secondary", type: "button", onClick: this.handleCancel, disabled: this.isLoading, part: buttonSecondary }, "Cancel")), h(Button, { variant: "primary", type: "button", onClick: this.handleSaveBankAccount, disabled: this.isLoading, isLoading: this.isLoading }, "Save Bank Account"))));
    }
    render() {
        if (this.isLoading) {
            return h(PaymentProvisioningLoading, null);
        }
        return (h("form", null, h("fieldset", { class: "mb-4" }, h("div", { class: "d-flex align-items-center gap-2" }, h("legend", { class: "mb-0", part: heading2 }, "Bank Account Info"), h("form-control-tooltip", { helpText: "This direct deposit account is the designated bank account where incoming funds will be deposited. The name of this account must match the registered business name exactly. We are not able to accept personal accounts unless your business is a registered sole proprietorship." })), h("hr", { class: "mt-2" }), this.viewMode === 'readonly' && this.renderReadonlyView(), this.viewMode === 'plaid' && this.renderPlaidView(), this.viewMode === 'manual' && this.renderManualEntryView())));
    }
    static get is() { return "business-bank-account-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 {
            "formController": {},
            "errors": {},
            "bankAccount": {},
            "isLoading": {},
            "viewMode": {},
            "getBusiness": {},
            "postBankAccount": {},
            "bankAccountVerification": {},
            "platformAccountId": {}
        };
    }
    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",
                            "id": "src/api/index.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",
                            "id": "src/api/index.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": "isLoading",
                "methodName": "watchHandler"
            }];
    }
}
