import { h } from "@stencil/core";
import { checkPkgVersion } from "../../../utils/check-pkg-version";
import { makeCreateDisputeEvidence, makeUpdateDisputeResponse, makeSubmitDisputeResponse, } from "./dispute-response-actions";
import JustifiAnalytics from "../../../api/Analytics";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../../api/ComponentError";
import { DisputeService } from "../../../api/services/dispute.service";
import { DisputeManagementClickActions } from "../event-types";
import { heading4 } from "../../../styles/parts";
import { Button } from "../../../ui-components/button";
export class DisputeResponse {
    constructor() {
        this.errorMessage = null;
        this.disputeResponse = {};
        this.apiOrigin = PROXY_API_ORIGIN;
        this.isLoading = false;
        this.documentList = [];
        this.documentErrors = {};
        this.currentStep = 0;
        this.componentStepMapping = [
            () => (h("product-or-service", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("customer-details", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("cancellation-policy", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("refund-policy", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("duplicate-charge", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("electronic-evidence", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("shipping-details", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("additional-statement", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
        ];
        this.saveData = async (formData, formStep) => {
            const hasFormData = Object.keys(formData).length;
            if (!hasFormData) {
                this.stepCompleteEvent.emit({ response: null, formStep: formStep });
                return;
            }
            if (this.isLastStep) {
                return this.submitDisputeResponse({
                    payload: formData,
                    onSuccess: (response) => {
                        this.submitEvent.emit({ response: response });
                        this.stepCompleteEvent.emit({ response: response, formStep: formStep });
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            errorCode: code,
                            message: error,
                            severity,
                        });
                    },
                });
            }
            else {
                return this.updateDisputeResponse({
                    payload: formData,
                    onSuccess: (response) => {
                        this.disputeResponse = Object.assign({}, response.data);
                        this.stepCompleteEvent.emit({ response: response, formStep: formStep });
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            errorCode: code,
                            message: error,
                            severity,
                        });
                    },
                });
            }
        };
        this.initializeMakePresignedURLs = async () => {
            const presignedUrlPromises = this.documentList.map((document) => {
                return this.getPresignedFileUrl(document);
            });
            return await Promise.all(presignedUrlPromises);
        };
        this.initializeFileUploads = async () => {
            const uploadDocumentPromises = this.documentList.map((document) => {
                return this.uploadDocument(document);
            });
            return Promise.all(uploadDocumentPromises);
        };
        this.getPresignedFileUrl = async (document) => {
            return this.createDisputeEvidence({
                payload: {
                    file_name: document.file_name,
                    file_type: document.file_type,
                    dispute_evidence_type: document.dispute_evidence_type,
                },
                onSuccess: (response) => {
                    document.presignedUrl = response.data.presigned_url;
                },
                onError: ({ error, code, severity }) => {
                    const errors = { [document.dispute_evidence_type]: error };
                    this.documentErrors = Object.assign(Object.assign({}, this.documentErrors), errors);
                    this.errorEvent.emit({
                        errorCode: code,
                        message: error,
                        severity,
                    });
                },
            });
        };
        this.uploadDocument = async (document) => {
            const fileData = await document.getFileString();
            if (!document.presignedUrl) {
                throw new Error('Presigned URL is not set');
            }
            const response = await fetch(document.presignedUrl, {
                method: 'PUT',
                body: fileData,
            });
            return response;
        };
        this.handleSubmit = async (formData, documentList, formStep) => {
            this.isLoading = true;
            if (documentList.length) {
                this.documentErrors = {};
                this.documentList = documentList;
                await this.initializeMakePresignedURLs();
                const hasPresigningErrors = Object.keys(this.documentErrors).length;
                if (hasPresigningErrors) {
                    this.isLoading = false;
                    throw new Error('Could not presign all documents');
                }
                await this.initializeFileUploads();
            }
            await this.saveData(formData, formStep);
            this.isLoading = false;
        };
        this.onCancel = () => {
            this.clickEvent.emit({ name: DisputeManagementClickActions.cancelDispute });
        };
        this.onBack = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: DisputeManagementClickActions.previousStep });
                await this.handleSubmit(formData, documentList, formStep);
                this.currentStep--;
            });
        };
        this.onNext = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: DisputeManagementClickActions.nextStep });
                await this.handleSubmit(formData, documentList, formStep);
                this.currentStep++;
            });
        };
        this.onSubmit = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: DisputeManagementClickActions.submit });
                const submitData = Object.assign(Object.assign({}, formData), { forfeit: false });
                await this.handleSubmit(submitData, documentList, formStep);
            });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.initializeDisputeServiceMethods();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    propChanged() {
        this.initializeDisputeServiceMethods();
    }
    initializeDisputeServiceMethods() {
        if (this.disputeId && this.authToken) {
            this.updateDisputeResponse = makeUpdateDisputeResponse({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new DisputeService(),
            });
            this.createDisputeEvidence = makeCreateDisputeEvidence({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new DisputeService(),
            });
            this.submitDisputeResponse = makeSubmitDisputeResponse({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new DisputeService(),
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    get currentStepComponent() {
        return this.componentStepMapping[this.currentStep]();
    }
    get isLastStep() {
        return this.currentStep === this.componentStepMapping.length - 1;
    }
    get isFirstStep() {
        return this.currentStep === 0;
    }
    render() {
        return (h("div", { key: '7f9c8d56cfb86cea73ab2f299b83ff0de28f5c3e', class: "dispute-response-root" }, h("div", { key: 'a805bf54df79453127557bf651c3d776a381241f', class: "row gy-3" }, h("div", { key: '2e6bc9cbe369e0ea5d200bc0934b4cad50f3c76f', class: "col-12" }, h("h1", { key: '9876e9c87c6dfb405e7bad46d64fdb40ad048142', class: "h4", part: heading4 }, "Counter dispute")), h("div", { key: '045028232da5331c7041ad222c4e98364674ace3', class: "col-12" }, this.currentStepComponent), h("div", { key: '0455c4856a44340ce25c1c4c8f776abb197f919f', class: "col-12" }, h("div", { key: '5b990cc1d41b3a7152d727c941e9758ed70f75a1', class: "d-flex gap-2 mt-4 justify-content-end" }, this.isFirstStep ? (h(Button, { variant: "secondary", onClick: () => this.onCancel(), disabled: this.isLoading, isLoading: this.isLoading }, "Cancel")) : (h(Button, { variant: "secondary", onClick: () => this.onBack(), disabled: this.isLoading, isLoading: this.isLoading }, "Back")), this.isLastStep ? (h(Button, { variant: "primary", onClick: () => this.onSubmit(), disabled: this.isLoading, isLoading: this.isLoading }, "Submit Counter Dispute")) : (h(Button, { variant: "primary", onClick: () => this.onNext(), disabled: this.isLoading, isLoading: this.isLoading }, "Next")))))));
    }
    static get is() { return "dispute-response"; }
    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"
            },
            "disputeId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "dispute-id"
            },
            "disputeResponse": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "ApiDisputeResponse | any",
                    "resolved": "any",
                    "references": {
                        "ApiDisputeResponse": {
                            "location": "import",
                            "path": "../../../api",
                            "id": "src/api/index.ts::DisputeResponse"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "dispute-response",
                "defaultValue": "{}"
            },
            "apiOrigin": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "api-origin",
                "defaultValue": "PROXY_API_ORIGIN"
            }
        };
    }
    static get states() {
        return {
            "updateDisputeResponse": {},
            "submitDisputeResponse": {},
            "createDisputeEvidence": {},
            "errorMessage": {},
            "isLoading": {},
            "documentList": {},
            "documentErrors": {},
            "currentStep": {},
            "currentStepComponentRef": {}
        };
    }
    static get events() {
        return [{
                "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"
                        }
                    }
                }
            }, {
                "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": "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"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "disputeId",
                "methodName": "propChanged"
            }, {
                "propName": "authToken",
                "methodName": "propChanged"
            }];
    }
}
