import { SafeDictionary } from "@insite/client-framework/Common/Types";
import { addOdpEvent } from "@insite/client-framework/ServerSideRendering";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getCurrentPage } from "@insite/client-framework/Store/Data/Pages/PageSelectors";
import PageProps from "@insite/client-framework/Types/PageProps";

export interface OdpEvent {
    name: string;
    basics: EventBasics;
    properties: SafeDictionary<unknown>;
}

interface EventBasics {
    is_business_tracking_by_ship_to_enabled: boolean;
    bill_to_business_id: string | undefined;
    ship_to_business_id: string | undefined;
    website_language: string | undefined;
    website_id: string;
    page_id: string;
}

export const createEvent = (name: string, state: ApplicationState): OdpEvent => {
    const { shipToId, billToId, language } = state.context.session;
    const enableTrackingAtCustomerShipToLevel =
        state.context.settings.settingsCollection.websiteSettings.enableOdpStorefrontEvents &&
        state.context.settings.settingsCollection.websiteSettings.enableOdpTrackingAtCustomerShipToLevel;

    return {
        name,
        basics: {
            is_business_tracking_by_ship_to_enabled: enableTrackingAtCustomerShipToLevel,
            bill_to_business_id: billToId,
            ship_to_business_id: shipToId,
            website_language: language?.languageTag ?? language?.languageCode,
            website_id: state.context.website.key,
            page_id: getCurrentPage(state).nodeId,
        },
        properties: {},
    };
};

export const sendEvent = (event: OdpEvent, state: ApplicationState) => {
    if (!state.context.settings.settingsCollection.websiteSettings.enableOdpStorefrontEvents) {
        return;
    }

    if (IS_SERVER_SIDE) {
        addOdpEvent(event);
        return;
    }

    const dataToSend = {
        ...event.basics,
        ...event.properties,
    };

    let zaius = (window as any).zaius;

    if (localStorage.getItem("logOdp") === "true") {
        let logEvent = () => {
            // eslint-disable-next-line no-console
            console.log(
                JSON.stringify(
                    {
                        event: event.name,
                        ...dataToSend,
                        vuid: zaius.VUID?.replaceAll("-", ""),
                    },
                    null,
                    "  ",
                ),
            );
        };
        if (!zaius.VUID) {
            setTimeout(logEvent, 500);
        } else {
            logEvent();
        }
    }

    zaius.event(event.name, dataToSend);
};
