import { h } from "@stencil/core";
import { InsuranceService } from "../../../api/services/insurance.service";
import { makeGetQuote, makeToggleCoverage } from "../../../actions/insurance/insurance-actions";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../../api/ComponentError";
import JustifiAnalytics from "../../../api/Analytics";
import { checkPkgVersion } from "../../../utils/check-pkg-version";
import { checkoutStore } from "../../../store/checkout.store";
import { addAttribute, formatCurrency, processHTML, removeAttribute } from "../../../utils/utils";
import { insuranceValues, insuranceErrors, validateInsuranceValues } from "../insurance-state";
import { StyledHost, Header2 } from "../../../ui-components";
import { text, textDanger } from "../../../styles/parts";
import SeasonInterruptionInsuranceLoading from "./season-interruption-insurance-loading";
export class JustifiSeasonInterruptionInsurance {
    constructor() {
        this.isLoading = true;
    }
    async validate() {
        return validateInsuranceValues();
    }
    processHTMLContent(html) {
        return processHTML(html, [
            (html) => removeAttribute(html, 'style'),
            (html) => addAttribute(html, 'a', 'part', text),
            (html) => addAttribute(html, 'p', 'part', text),
        ]);
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.initializeServiceMethods();
        if (this.getQuote) {
            this.fetchData();
        }
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    initializeServiceMethods() {
        const authToken = this.authToken || checkoutStore.authToken;
        if (!authToken) {
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: 'Missing authToken',
                severity: ComponentErrorSeverity.ERROR,
            });
            return;
        }
        const service = new InsuranceService();
        const config = { authToken, service };
        this.getQuote = makeGetQuote(config);
        this.toggleCoverage = makeToggleCoverage(config);
    }
    fetchData() {
        this.isLoading = true;
        this.getQuote({
            payload: {
                checkout_id: this.checkoutId || checkoutStore.checkoutId,
                policy_type: "season_interruption",
                primary_identity: {
                    state: this.primaryIdentityState,
                    email: this.primaryIdentityEmailAddress,
                    first_name: this.primaryIdentityFirstName,
                    last_name: this.primaryIdentityLastName,
                    postal_code: this.primaryIdentityPostalCode,
                    country: this.primaryIdentityCountry
                },
                policy_attributes: {
                    insurable_amount: this.policyAttributesInsurableAmount,
                    start_date: this.policyAttributesStartDate,
                    end_date: this.policyAttributesEndDate,
                    covered_identity: {
                        first_name: this.coveredIdentityFirstName,
                        last_name: this.coveredIdentityLastName
                    }
                }
            },
            onSuccess: ({ quote }) => {
                this.quote = quote;
                this.quote.product.description = this.processHTMLContent(this.quote.product.description);
                this.quote.product.legal_disclaimer = this.processHTMLContent(this.quote.product.legal_disclaimer);
                insuranceValues[quote.policy_type] = quote.accepted;
                this.isLoading = false;
            },
            onError: ({ error, code, severity }) => {
                this.isLoading = false;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            }
        });
    }
    onChangeHandler(_name, value) {
        this.accepted = value;
        insuranceErrors[this.quote.policy_type] = false;
        this.toggleCoverage({
            quoteId: this.quote.id,
            payload: { accepted: this.accepted },
            onSuccess: () => {
                this.insuranceUpdated.emit();
                insuranceValues[this.quote.policy_type] = this.accepted;
            },
            onError: ({ error, code, severity }) => {
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            }
        });
    }
    get error() {
        var _a;
        return insuranceErrors[(_a = this.quote) === null || _a === void 0 ? void 0 : _a.policy_type];
    }
    render() {
        var _a, _b, _c, _d;
        if (checkoutStore && checkoutStore.insuranceEnabled === false) {
            console.warn('[justifi-season-interruption-insurance] Insurance is disabled for this checkout (payment_settings.insurance_payments=false).');
            return null;
        }
        if (this.isLoading)
            return (h(StyledHost, null, h(SeasonInterruptionInsuranceLoading, null)));
        return (h(StyledHost, null, h("div", null, h(Header2, { text: (_a = this.quote) === null || _a === void 0 ? void 0 : _a.product.title, class: "fs-5 fw-bold pb-3" }), h("small", { part: text, innerHTML: (_b = this.quote) === null || _b === void 0 ? void 0 : _b.product.description }), h("form-control-radio", { label: `Accept coverage for ${formatCurrency((_c = this.quote) === null || _c === void 0 ? void 0 : _c.total_cents)}`, name: "opt-in", value: 'true', checked: this.accepted === 'true', inputHandler: this.onChangeHandler.bind(this),
            // don't wanna show error message, but need to show the red border
            errorText: this.error ? ' ' : undefined }), h("form-control-radio", { label: "Decline coverage", name: "opt-in", value: 'false', checked: this.accepted === 'false', inputHandler: this.onChangeHandler.bind(this), errorText: this.error ? ' ' : undefined }), h("div", { class: "invalid-feedback", style: { display: this.error ? 'block' : 'none' }, part: textDanger }, "Please select an option"), h("small", { part: text, innerHTML: (_d = this.quote) === null || _d === void 0 ? void 0 : _d.product.legal_disclaimer }))));
    }
    static get is() { return "justifi-season-interruption-insurance"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "authToken": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "auth-token"
            },
            "checkoutId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "checkout-id"
            },
            "primaryIdentityFirstName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "primary-identity-first-name"
            },
            "primaryIdentityLastName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "primary-identity-last-name"
            },
            "primaryIdentityState": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "primary-identity-state"
            },
            "primaryIdentityPostalCode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "primary-identity-postal-code"
            },
            "primaryIdentityCountry": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "primary-identity-country"
            },
            "primaryIdentityEmailAddress": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "primary-identity-email-address"
            },
            "policyAttributesInsurableAmount": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "policy-attributes-insurable-amount"
            },
            "policyAttributesStartDate": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "policy-attributes-start-date"
            },
            "policyAttributesEndDate": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "policy-attributes-end-date"
            },
            "coveredIdentityFirstName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "covered-identity-first-name"
            },
            "coveredIdentityLastName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "covered-identity-last-name"
            }
        };
    }
    static get states() {
        return {
            "getQuote": {},
            "toggleCoverage": {},
            "quote": {},
            "isLoading": {},
            "accepted": {}
        };
    }
    static get events() {
        return [{
                "method": "insuranceUpdated",
                "name": "insurance-updated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "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"
                        }
                    }
                }
            }];
    }
    static get methods() {
        return {
            "validate": {
                "complexType": {
                    "signature": "() => Promise<{ isValid: boolean; }>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<{ isValid: boolean; }>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
}
