import { bindQuoteRequest, getApplicationFormState, getCarriersProductsState, getConfigOptions, getEligibleCarriersProducts, getPartnerEngineConfig, getQuotesState, quoteActionBind, setFilteredOfflineQuotes, setFilteredOnlineQuotes, timeoutQuoteState, } from "@boldpenguin/sdk-redux";
import { Attachments } from "@boldpenguin/sdk-requests";
import { AppetiteMarkets, ApplicationFormStates, LoadingStates, SdkAnalyticsVariables, } from "@boldpenguin/sdk-types";
import { Fragment, h } from "@stencil/core";
import isEqual from "lodash/isEqual";
import store from "../../services/redux-store.service";
export class BpSdkQuoteRequestContainer {
    constructor() {
        this.handleSubscriptions = () => {
            this.storeUnsubscribe && this.storeUnsubscribe();
            store.mapDispatchToProps(this, {
                bindQuoteRequest,
                timeoutQuoteState,
                quoteActionBind,
                setFilteredOfflineQuotes,
                setFilteredOnlineQuotes,
            });
            this.storeUnsubscribe = store.mapStateToProps(this, this.mapStateToProps);
        };
        this.mapStateToProps = (state) => {
            return {
                appFormState: state.application.form.state,
                applicationFormResourceState: getApplicationFormState(state),
                config: getPartnerEngineConfig(state),
                configOptions: getConfigOptions(state),
                carriersProducts: getEligibleCarriersProducts(state) || [],
                carriersProductsResourceState: getCarriersProductsState(state),
                quotes: state.application.quotes || [],
                quotesResourceState: getQuotesState(state),
            };
        };
        this.handleQuoteTimeout = () => {
            this.timeoutQuoteState();
        };
        this.handleBind = (quoteId, appFormId, afterResponse) => {
            this.bindQuoteRequest({
                quoteId,
                appFormId,
                afterResponse,
                config: this.config,
            });
        };
        this.handleQuoteActionBind = (action, quote) => {
            // Pay actions have no API to hit and only update internal state logic
            if (action.value === 'pay') {
                this.showQuotePayment = true;
                return;
            }
            this.quoteActionBind({
                action,
                quote,
                config: this.config,
            });
        };
        this.handleDownload = (id, filename) => {
            Attachments.getAttachment(id, this.config).then((data) => {
                const a = document.createElement('a');
                a.href = window.URL.createObjectURL(data.parsedBody);
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                a.remove();
            });
        };
        this.renderQuotes = () => {
            var _a;
            return [
                !this.filteredOnlineQuotes.length && !this.filteredOfflineQuotes.length && [],
                this.filteredOnlineQuotes.map((quote) => {
                    const quoteInfo = {
                        annual_price: quote.annual_price,
                        monthly_price: quote.monthly_price,
                        number_of_installments: quote.number_of_installments,
                        downpayment: quote.downpayment,
                        semiannual_price: quote.semiannual_price,
                        price_details: quote.price_details,
                        quote_number: quote.quote_number,
                    };
                    const quoteStatus = {
                        recommended: quote.recommended,
                        selected: quote.selected,
                        consumer_selected: quote.consumer_selected,
                        focused: quote.focused,
                        expired: quote.expired,
                    };
                    return (h(Fragment, null, h("bp-sdk-quote-request", { actions: quote.actions, appFormId: quote.application_form_id, attachments: quote.attachments, bindable: quote.bindable, carrier: quote.carrier, customLogoBaseUrl: this.customLogoBaseUrl, handleAction: this.handleQuoteActionBind, handleBind: this.handleBind, handleDownload: this.handleDownload, permittedToBind: quote.permitted_to_bind, products: quote.products, quoteId: quote.id, quoteInfo: quoteInfo, quoteStatus: quoteStatus, requestStatus: quote.request_status, satisfiesApplicationFormProductRequest: quote.satisfies_application_form_product_request, showCustomLogo: this.showCustomLogo, showLogo: this.showLogo, translatedMessages: quote.translated_messages, supplierName: quote.supplier_name, supplierLogoUrl: quote.supplier_logo_url, supplierLogoUrlFull: quote.supplier_logo_url_full, supplierCode: quote.supplier_code, parentQuoteRequestId: quote.parentQuoteRequestId }), this.renderQuotePayment(quote)));
                }),
                ((_a = this.configOptions) === null || _a === void 0 ? void 0 : _a.renderOfflineQuotes) &&
                    this.filteredOfflineQuotes.map((offlineQuote) => {
                        return (h("bp-sdk-offline-quote", { carrier: offlineQuote.carrier, product: offlineQuote.product, showLogo: this.showLogo, showCustomLogo: this.showCustomLogo, customLogoBaseUrl: this.customLogoBaseUrl }));
                    }),
                !this.disableSendToExchange && h("bp-sdk-send-to-exchange-container", null),
            ];
        };
        this.showLogo = true;
        this.showCustomLogo = false;
        this.customLogoBaseUrl = '';
        this.disableSendToExchange = false;
        this.quotes = [];
        this.carriersProducts = undefined;
        this.applicationFormResourceState = undefined;
        this.quotesResourceState = undefined;
        this.appFormState = undefined;
        this.config = undefined;
        this.carriersProductsResourceState = undefined;
        this.configOptions = undefined;
        this.quoteTimeout = 90;
        this.showAllQuotes = false;
        this.quotesSortFn = (a, b) => {
            return a.order - b.order;
        };
        this.offlineQuotesSortFn = undefined;
        this.filteredCarrierCodes = [];
        this.useExternal = false;
        this.isReady = true;
        this.showQuotePayment = false;
        this.filteredOnlineQuotes = [];
        this.filteredOfflineQuotes = [];
    }
    resetState() {
        this.showQuotePayment = false;
    }
    connectedCallback() {
        this.resetState();
        this.handleSubscriptions();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-quote-request-container');
        customElements.whenDefined('bp-sdk-external-quote-request-container').then(() => {
            this.useExternal = true;
        });
        this.handleSubscriptions();
        this.onApplicationResourceStateChange(this.applicationFormResourceState);
        this.onQuotesResourceStateChange(this.quotesResourceState);
    }
    disconnectedCallback() {
        this.storeUnsubscribe && this.storeUnsubscribe();
    }
    onCarriersProductsChange(carriersProducts) {
        if (this.useExternal) {
            return;
        }
        const onlineCarrierIds = this.quotes.map((quote) => quote.carrier.id);
        const filteredOfflineQuotes = carriersProducts.filter((offlineQuote) => {
            // TODO(hybrid_appetite): keep market, remove legacy check of `carrier.online`
            // legacy: online vs offline carrier products
            const shouldRenderLegacyOfflineQuote = !onlineCarrierIds.includes(offlineQuote.carrier.id) && !offlineQuote.carrier.online;
            // next gen: market to indicate where carrier can quote
            const shouldRenderNextGenOfflineQuote = offlineQuote.market && offlineQuote.market === AppetiteMarkets.OFFLINE;
            const shouldQuoteCarrierRender = this.filteredCarrierCodes.length > 0 ? this.filteredCarrierCodes.includes(offlineQuote.carrier.code) : true;
            return shouldQuoteCarrierRender && (shouldRenderLegacyOfflineQuote || shouldRenderNextGenOfflineQuote);
        });
        if (this.offlineQuotesSortFn) {
            filteredOfflineQuotes.sort(this.offlineQuotesSortFn);
        }
        this.filteredOfflineQuotes = filteredOfflineQuotes;
        this.setFilteredOfflineQuotes(filteredOfflineQuotes);
    }
    onQuotesChange(quotes, oldQuotes) {
        if (this.useExternal) {
            return;
        }
        const filteredOnlineQuotes = this.quotes.filter((quote) => {
            var _a, _b;
            const shouldQuoteCarrierRender = this.filteredCarrierCodes.length > 0 ? this.filteredCarrierCodes.includes(quote.carrier.code) : true;
            const shouldQuoteStatusRender = ((_b = (_a = this.configOptions) === null || _a === void 0 ? void 0 : _a.quoteStatusFilter) !== null && _b !== void 0 ? _b : []).includes(quote.request_status);
            return (shouldQuoteStatusRender && shouldQuoteCarrierRender) || this.showAllQuotes;
        });
        if (this.quotesSortFn) {
            filteredOnlineQuotes.sort(this.quotesSortFn);
        }
        this.filteredOnlineQuotes = filteredOnlineQuotes;
        this.setFilteredOnlineQuotes(filteredOnlineQuotes);
        if (!isEqual(quotes, oldQuotes)) {
            const label = quotes
                .map((q) => `${q.carrier.name}_${q.annual_price}_${q.bindable ? SdkAnalyticsVariables.additionalQuoteOnline : SdkAnalyticsVariables.additionalQuoteOffline}`)
                .join('; ');
            this.bpAnalyticsTrack.emit({
                eventName: 'Display_Additional',
                eventPayload: {
                    label,
                    value: 0,
                },
            });
        }
    }
    onApplicationResourceStateChange(newState) {
        this.updateResource(newState, this.quotesResourceState);
    }
    onQuotesResourceStateChange(newState, oldState) {
        this.updateResource(this.applicationFormResourceState, newState);
        if (!!oldState && oldState !== LoadingStates.Loading && newState === LoadingStates.Loading) {
            // Kick off timer to automatically set to quoted after timeout expires
            setTimeout(this.handleQuoteTimeout, this.quoteTimeout * 1000);
        }
    }
    updateResource(applicationForm, quotes) {
        this.isReady = applicationForm === LoadingStates.Loading || quotes !== LoadingStates.Loading || this.configOptions.renderQuotesAsync;
    }
    isAppFormReadyToShowQuotes() {
        var _a;
        return ((_a = this.configOptions) === null || _a === void 0 ? void 0 : _a.renderQuotesWithAppState)
            ? this.configOptions.renderQuotesWithAppState.includes(this.appFormState)
            : [ApplicationFormStates.Completed, ApplicationFormStates.Quoted].includes(this.appFormState);
    }
    componentWillUpdate() {
        this.handleSubscriptions();
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (h("bp-sdk-external-quote-request-container", { appFormState: this.appFormState, applicationFormResourceState: this.applicationFormResourceState, config: this.config, configOptions: this.configOptions, customLogoBaseUrl: this.customLogoBaseUrl, disableSendToExchange: this.disableSendToExchange, eligibilityCarrierProducts: this.carriersProducts, carriersProductsResourceState: this.carriersProductsResourceState, quoteTimeout: this.quoteTimeout, quotes: this.quotes, quotesResourceState: this.quotesResourceState, showCustomLogo: this.showCustomLogo, showLogo: this.showLogo, showAllQuotes: this.showAllQuotes, quotesSortFn: this.quotesSortFn, offlineQuotesSortFn: this.offlineQuotesSortFn, filteredCarrierCodes: this.filteredCarrierCodes }));
    }
    renderQuotePayment(quote) {
        var _a;
        if (this.showQuotePayment && ((_a = quote === null || quote === void 0 ? void 0 : quote.actions) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            return h("bp-sdk-quote-payment", { quoteRequest: quote });
        }
    }
    renderInternal() {
        return [!this.isReady && h("bp-sdk-quote-load", null), this.isReady && this.isAppFormReadyToShowQuotes() && this.renderQuotes(), h("slot", null)];
    }
    static get is() { return "bp-sdk-quote-request-container"; }
    static get properties() {
        return {
            "showLogo": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Should show custom logo"
                },
                "attribute": "show-logo",
                "reflect": false,
                "defaultValue": "true"
            },
            "showCustomLogo": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Should show custom logo"
                },
                "attribute": "show-custom-logo",
                "reflect": false,
                "defaultValue": "false"
            },
            "customLogoBaseUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Custom logo base url\n\nIf passed, it will expect a carrier logo to exist at the following URLs:\n\n${baseUrl}${carrier?.name?.toLowerCase()}.png for carrier logos\n\n${baseUrl}${this.quote.supplier_name.toLowerCase()}.png for supplier logos"
                },
                "attribute": "custom-logo-base-url",
                "reflect": false,
                "defaultValue": "''"
            },
            "disableSendToExchange": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Disable send to exchange button being rendered"
                },
                "attribute": "disable-send-to-exchange",
                "reflect": false,
                "defaultValue": "false"
            },
            "quotes": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "IQuotesState[]",
                    "resolved": "IQuotesState[]",
                    "references": {
                        "IQuotesState": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IQuotesState"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Available online quotes on application form injected from redux"
                },
                "defaultValue": "[]"
            },
            "carriersProducts": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "IQuoteableCarriersProduct[]",
                    "resolved": "IQuoteableCarriersProduct[]",
                    "references": {
                        "IQuoteableCarriersProduct": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IQuoteableCarriersProduct"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Available offline quotes injected from redux"
                }
            },
            "applicationFormResourceState": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "LoadingStates",
                    "resolved": "LoadingStates.Error | LoadingStates.Loaded | LoadingStates.Loading | LoadingStates.NotLoaded",
                    "references": {
                        "LoadingStates": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::LoadingStates"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Application form resource state"
                },
                "attribute": "application-form-resource-state",
                "reflect": false
            },
            "quotesResourceState": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "LoadingStates",
                    "resolved": "LoadingStates.Error | LoadingStates.Loaded | LoadingStates.Loading | LoadingStates.NotLoaded",
                    "references": {
                        "LoadingStates": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::LoadingStates"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Available quotes on application form resource state"
                },
                "attribute": "quotes-resource-state",
                "reflect": false
            },
            "appFormState": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "ApplicationFormStates",
                    "resolved": "ApplicationFormStates.Completed | ApplicationFormStates.InProgress | ApplicationFormStates.Incomplete | ApplicationFormStates.Quoted",
                    "references": {
                        "ApplicationFormStates": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::ApplicationFormStates"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Application form state injected from redux"
                },
                "attribute": "app-form-state",
                "reflect": false
            },
            "config": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "IPartnerEngineConfig",
                    "resolved": "IPartnerEngineConfig",
                    "references": {
                        "IPartnerEngineConfig": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IPartnerEngineConfig"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "IPartnerEngineConfig injected from redux"
                }
            },
            "carriersProductsResourceState": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "LoadingStates",
                    "resolved": "LoadingStates.Error | LoadingStates.Loaded | LoadingStates.Loading | LoadingStates.NotLoaded",
                    "references": {
                        "LoadingStates": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::LoadingStates"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "*Deprecated* Use applicationFormResourceState instead.\n\nOffline quotes resources loaded injected from redux"
                },
                "attribute": "carriers-products-resource-state",
                "reflect": false
            },
            "configOptions": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "IConfigOptions",
                    "resolved": "IConfigOptions",
                    "references": {
                        "IConfigOptions": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IConfigOptions"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Web component config options injected from redux"
                }
            },
            "quoteTimeout": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Timer in seconds to use for timing out quoting process"
                },
                "attribute": "quote-timeout",
                "reflect": false,
                "defaultValue": "90"
            },
            "showAllQuotes": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Show all quotes irrespective of status."
                },
                "attribute": "show-all-quotes",
                "reflect": false,
                "defaultValue": "false"
            },
            "quotesSortFn": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(a: IQuotesState, b: IQuotesState) => number",
                    "resolved": "(a: IQuotesState, b: IQuotesState) => number",
                    "references": {
                        "IQuotesState": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IQuotesState"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Optional custom function to sort online quotes, default is quotes are sorted by backend"
                },
                "defaultValue": "(a: IQuotesState, b: IQuotesState) => {\n    return a.order - b.order;\n  }"
            },
            "offlineQuotesSortFn": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(a: IQuoteableCarriersProduct, b: IQuoteableCarriersProduct) => number",
                    "resolved": "(a: IQuoteableCarriersProduct, b: IQuoteableCarriersProduct) => number",
                    "references": {
                        "IQuoteableCarriersProduct": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IQuoteableCarriersProduct"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Optional custom function to sort online quotes, default is quotes are sorted by backend"
                }
            },
            "filteredCarrierCodes": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Optional array of carrier codes to display quotes, if provided quotes will only be shown by carriers in array.\nIf not provided, all carriers will be shown."
                },
                "defaultValue": "[]"
            }
        };
    }
    static get states() {
        return {
            "useExternal": {},
            "isReady": {},
            "showQuotePayment": {},
            "filteredOnlineQuotes": {},
            "filteredOfflineQuotes": {}
        };
    }
    static get events() {
        return [{
                "method": "bpAnalyticsTrack",
                "name": "bpAnalyticsTrack",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "IAnalyticsTrackEventDetail",
                    "resolved": "IAnalyticsTrackEventDetail",
                    "references": {
                        "IAnalyticsTrackEventDetail": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IAnalyticsTrackEventDetail"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "carriersProducts",
                "methodName": "onCarriersProductsChange"
            }, {
                "propName": "quotes",
                "methodName": "onQuotesChange"
            }, {
                "propName": "applicationFormResourceState",
                "methodName": "onApplicationResourceStateChange"
            }, {
                "propName": "quotesResourceState",
                "methodName": "onQuotesResourceStateChange"
            }];
    }
}
