import React, {FC, ReactNode, useEffect, useLayoutEffect} from "react";
import {PopupWindow, ScreenProps} from "../PopupWindow";
import {PopupWindowState, SelectActionContext, SelectActionPopupWindowStateAtom} from "./atoms";
import {__} from "../globals";
import {SelectOffers} from "./actions/SelectOffers";
import {useAtom} from "jotai";
import {useCloseSelectActionsPopupWindow, useNavigationActions, useScreenNavigation} from "./hooks";
import {SelectTier} from "./actions/SelectTier";
import {SelectOffersNew} from "./actions/SelectOffersNew";
import {selectTierNew} from "./actions/SelectTierNew";
import classNames from "classnames";
import {ProBadge} from "../ProBadge";

export type SelectActionPopupWindowProps = {}

export type Action = {
    id: string,
    data: {
        name: string,
        icon?: ReactNode,
    };
    screens: ScreenProps[] | ((popupWindowState: PopupWindowState<SelectActionContext>) => ScreenProps[]),
    reset?: () => void,
    onOpen?: (context: SelectActionContext, setCurrentScreenId: ReturnType<typeof useSetCurrentScreenId>) => void,
    isNotImplemented?: boolean,
};
const actions: Action[] = [
    //SelectOffers,
    SelectOffersNew,
    selectTierNew,
];

/**
 * Do ont put this in the same file as the Testable popup window because on update this will update too causing nasty bugs
 */
export const SelectActionPopupWindow: FC<SelectActionPopupWindowProps> = ({}) => {
    const [{isOpen, context}] = /*[{
        isOpen: true,
        context: {
            action: null,
            targetBranchId: 'SPkgzpjlW->branch',
        },
    } as PopupWindowState<SelectActionContext>] */ useAtom(SelectActionPopupWindowStateAtom)
    const [currentScreenId, setCurrentScreenId, navigationactions] = useScreenNavigation()
    const [selectedAction, setSelectedAction] = React.useState<Action | null>(null)
    const screensForCurrentAction = (typeof selectedAction?.screens === 'function' ? selectedAction.screens({
        isOpen,
        context
    }) : selectedAction?.screens) || []
    // @ts-ignore
    const canHaveFirstScreen = /*IT HAS TO BE CHECKED USING CONTEXT.ACTION BECAUSE THIS IS SET BY THE POPUP OPENER, THE selectedAction IS PART OF THE STATE AND IT MAY BE SET MANUALLY BY THE USER. IN OTHER WORDS, DON'T CHANGE THIS OR THERE WILL BE BUGS */context.action ? (typeof context?.data?.canChangeAction === 'boolean' && context.data.canChangeAction) : true;
    const defaultScreenId = 1;

    const closePopup = useCloseSelectActionsPopupWindow()

    const reset = () => {
        setSelectedAction(null)
        setCurrentScreenId(defaultScreenId)
    }

    const close = () => {
        closePopup()
        reset();
    }

    // @ts-ignore
    if ((context.action !== null) && (context.action !== selectedAction?.id)) {
        setSelectedAction(
            actions.find((action) => action.id === context.action) || null
        )
    }
    useLayoutEffect(() => {
        if (selectedAction !== null) {
            setCurrentScreenId(2)
        }
    }, [selectedAction === null])

    useLayoutEffect(() => {
        if (selectedAction && (currentScreenId || defaultScreenId) < 2) {
            setCurrentScreenId(2)
        }
    }, [selectedAction])

    useLayoutEffect(() => {
        if (isOpen) {
            selectedAction?.onOpen?.(context, setCurrentScreenId)
        }

    }, [isOpen]);

    useEffect(() => {
        if (!isOpen) {
            // reset
            if (selectedAction) {
                selectedAction.reset?.()
            }

            reset()
        }
    }, [isOpen])

    return <PopupWindow
        id={'select-action'}
        screenId={currentScreenId}
        setCurrentScreenId={setCurrentScreenId}
        defaultScreenId={defaultScreenId}
        canGoBack={(to: number): boolean => {
            if (canHaveFirstScreen) {
                return true;
            }

            return to !== 1;
        }}
        screens={[
            ({
                id: 1,
                title: __('Select action'),
                description: __('You can add offers to the filtered items, for example, to create a BOGO offer or to apply discounts directly to the filtered items or the cart subtotal. Or you can add tiers to create bulk discounts or tiered offers.'),
                content: () => {
                    return <div className="flex gap-3">
                        {actions.map((action) => {
                            return <button className={classNames("text-gray-700 flex flex-col items-start gap-2 rounded-1 border-[2px] border-gray-150 px-6 py-5 w-68", {
                                'opacity-50 cursor-not-allowed': action.isNotImplemented
                            })}
                                           onClick={() => {
                                               setSelectedAction(action)

                                               setCurrentScreenId(2)
                                           }}>
                                {action.data.icon}
                                <h1 className={'text-3x  text-gray-700 text-left'}>{action.data.name} {action.isNotImplemented && <ProBadge /> }</h1>
                            </button>
                        })}
                    </div>
                },
                onBackToThisScreen: () => {
                    selectedAction?.reset?.()
                },
                showBottomNavigation: false
            }),
            ...screensForCurrentAction
        ]}
        isOpen={isOpen}
        onClose={close}
    />
}
