import {useSetAtom} from "jotai/index";
import {
    BuyXGetYSpecificProductWindowContextData,
    BuyXGetYSpecificProductWindowStateAtom,
    GetYProductDataToSave
} from "../atoms";
import type {ProductData} from "./BuyXGetY";
import {useOpenEditOfferPopup} from "../hooks";
import {useEffect} from "react";

const buyXGetYProductPopupResultHandlers = new Map<string, (newData: GetYProductDataToSave) => void>()

export const applyGetYProductDataUpdate = (
    existingData: ProductData,
    newData: GetYProductDataToSave,
): ProductData => {
    if (!Array.isArray(existingData)) {
        existingData = []
    }

    if (!newData?.data) {
        console.error('BuyXGetY: missing product data on save')
        return existingData
    }

    if (typeof newData.index === "undefined") {
        return [...existingData, newData.data]
    }

    return existingData.map((item, index) => {
        if (index === newData.index) {
            return newData.data
        }

        return item
    })
}

export const useOpenBuyXGetYProductPopupFlow = ({
    offerId,
    openOfferEditorFirst = false,
    onSuccess,
}: {
    offerId: string,
    openOfferEditorFirst?: boolean,
    onSuccess?: (newData: GetYProductDataToSave) => void
}) => {
    const openProductSettingsWindow = useSetAtom(BuyXGetYSpecificProductWindowStateAtom)
    const openEditOfferPopup = useOpenEditOfferPopup(offerId)

    return (windowContext: Omit<BuyXGetYSpecificProductWindowContextData, 'onClose'> = {}) => {
        const openProductPopupWindow = () => {
            openProductSettingsWindow({
                ...windowContext,
                onClose: (status, updatedData) => {
                    if (status !== 'success') {
                        return
                    }

                    const normalizedData = typeof updatedData.index === "undefined" && typeof windowContext.index !== "undefined"
                        ? {
                            ...updatedData,
                            index: windowContext.index,
                        }
                        : updatedData

                    const onPopupSuccess = onSuccess || buyXGetYProductPopupResultHandlers.get(offerId)
                    if (!onPopupSuccess) {
                        console.error('BuyXGetY: no popup result handler registered', offerId)
                        return
                    }

                    onPopupSuccess(normalizedData)
                }
            })
        }

        if (openOfferEditorFirst) {
            openEditOfferPopup()
            window.setTimeout(openProductPopupWindow, 400)
            return
        }

        openProductPopupWindow()
    }
}

export const useRegisterBuyXGetYProductPopupResultHandler = ({
    offerId,
    onSuccess,
}: {
    offerId: string,
    onSuccess: (newData: GetYProductDataToSave) => void
}) => {
    useEffect(() => {
        buyXGetYProductPopupResultHandlers.set(offerId, onSuccess)

        return () => {
            if (buyXGetYProductPopupResultHandlers.get(offerId) === onSuccess) {
                buyXGetYProductPopupResultHandlers.delete(offerId)
            }
        }
    }, [offerId, onSuccess])
}
