import {Action} from "../SelectActionPopupWindow";
import {atom, useAtom} from "jotai";
import {ComponentRuntimeDataWithParentType} from "../components";
import React from "react";
import {Note} from "../cards";
import {cloneDeep, set, unset, get} from "lodash";
import {produce} from "immer";
import {OfferData, TestablePartial, useNodesStore} from "../store";
import {
    atomsStore, PopupWindowState,
    PopupWindowStateContext, SelectActionContextOffers, SelectActionPopupWindowStateAtom, TreeContextData
} from "../atoms";
import {useOpenTestablesPopupWindow} from "../useOpenTestablesPopupWindow";
import {getOffersPopupWindowContext} from "../../OffersBranch";
import {FALSE} from "sass";
import {generateIdForType} from "../NodeHelpers";
import {equals, TierType} from "../tiers";
import {AmountValidatorOptions} from "../cards/filterinterfaces";
import {QuantityMeta} from "../cards/Quantity";
import {ComponentMeta, ComponentsMeta, getComponentMeta, getComponentMetaData} from "../ComponentsMeta";
import {__, CouponsPlus} from "../../globals";
import {NonImplementedMessage} from "./NonImplementedMessage";
import {getOpenPopupsCount} from "../hooks";
import {getPopupStackDimensionCalculators} from "../ulitilies";


const SelectedOfferAtom = atom<OfferData | Omit<OfferData, 'id'> | null>(null)
const SelectedOffersAtom = atom<ComponentRuntimeDataWithParentType[] | []>([])
atomsStore.set(SelectedOfferAtom, null)
atomsStore.set(SelectedOffersAtom, [])

function isEditMode(): boolean {
    const {context: {data}} = atomsStore.get(SelectActionPopupWindowStateAtom) as PopupWindowState<SelectActionContextOffers>

    // @ts-ignore
    return !!data?.offerId
}

const getDefaultOptionsForFirstTierSubchild = (meta: ComponentMeta): Record<any, any> => {
    const tiertype = meta?.tierType || TierType.Numeric
    let options: Record<any, any> = cloneDeep(getComponentMetaData(meta).defaultOptions) || {}

    if (meta?.tierDefaultOptions?.first) {
        options = meta.tierDefaultOptions.first()
    } else if (tiertype === TierType.Numeric) {
        // as a self-invoking anonymous function to create a new instance each time
        options = (() => ({
                quantity: equals(1)
            }) as AmountValidatorOptions
        )()
    }

    return pickByPaths(options, meta.tierFields || [])

}

export const pickByPaths = (obj: any, pathsToInclude: string[]): any => {
    const result = {};
    pathsToInclude.forEach(path => {
        const value = get(obj, path);
        if (value !== undefined) {
            set(result, path, value);
        }
    });
    return result;
}

let testableisOpen = false
const isNotImplemented = CouponsPlus.implementations.branches.tiered === false
// @ts-ignore
export const selectTierNew: Action = {
    id: 'select-tier',
    isNotImplemented,
    data: {
        name: __('Add Path/Tiered/Bulk Offers'),
        icon: <svg width="78" height="81" viewBox="0 0 78 81" fill="none" xmlns="http://www.w3.org/2000/svg" className="min-w-10 min-h-10 max-w-10 max-h-10 ">
            <path d="M76.9 78.7H68.2V69.742L72.272 66.039C72.68 65.667 72.71 65.035 72.339 64.626C71.968 64.218 71.334 64.189 70.926 64.559L68.2 67.039V61.3C68.2 60.747 67.753 60.3 67.2 60.3C66.647 60.3 66.2 60.747 66.2 61.3V71.371L61.679 65.773C61.331 65.342 60.702 65.275 60.273 65.623C59.844 65.971 59.776 66.6 60.123 67.029L66.201 74.554V78.7H59.981C59.124 73.452 54.604 69.6 49.1 69.6C47.958 69.6 46.821 69.791 45.701 70.149V61.6H54.501C54.767 61.6 55.021 61.495 55.208 61.307L65.208 51.307C65.396 51.119 65.501 50.866 65.501 50.6C65.501 50.334 65.396 50.08 65.208 49.893L55.208 39.893C55.02 39.706 54.766 39.6 54.5 39.6H45.7V32.5H59.5C60.053 32.5 60.5 32.052 60.5 31.5V11.5C60.5 10.948 60.053 10.5 59.5 10.5H45.7V1C45.7 0.448 45.253 0 44.7 0H34.3C33.748 0 33.3 0.448 33.3 1V10.5H23.5C23.235 10.5 22.98 10.605 22.793 10.793L12.793 20.793C12.402 21.184 12.402 21.816 12.793 22.207L22.793 32.207C22.98 32.395 23.235 32.5 23.5 32.5H33.3V39.6H18.5C17.948 39.6 17.5 40.048 17.5 40.6V60.6C17.5 61.153 17.948 61.6 18.5 61.6H33.3V68.831C31.682 68.022 29.88 67.6 28 67.6C23.485 67.6 19.303 70.219 17.287 74.218C16.312 73.811 15.214 73.6 14 73.6C10.508 73.6 7.405 75.589 5.879 78.701H1C0.448 78.701 0 79.148 0 79.701C0 80.254 0.448 80.701 1 80.701H76.9C77.453 80.701 77.9 80.254 77.9 79.701C77.9 79.148 77.453 78.7 76.9 78.7ZM49.1 71.6C53.491 71.6 57.114 74.586 57.945 78.701H45.7V72.275C46.821 71.835 47.961 71.6 49.1 71.6ZM14.914 21.5L23.914 12.5H58.5V30.5H23.914L14.914 21.5ZM19.5 41.601H54.086L63.086 50.6L54.086 59.6H19.5V41.601ZM28 69.6C29.926 69.6 31.745 70.133 33.3 71.136V78.7H18.042C18.119 77.855 18.317 77.028 18.636 76.144C18.638 76.141 18.642 76.139 18.644 76.135C18.722 76.012 18.766 75.878 18.786 75.742C20.32 72.064 24.002 69.6 28 69.6ZM14 75.6C14.959 75.6 15.813 75.759 16.551 76.072C16.276 76.96 16.109 77.824 16.042 78.701H8.179C9.481 76.787 11.624 75.6 14 75.6Z" fill="currentColor"/>
        </svg>
    },
    reset: () => {
        atomsStore.set(SelectedOfferAtom, null)
        atomsStore.set(SelectedOffersAtom, [])
    },
    // @ts-ignore
    screens: ({context: {targetBranchId}}) => [
        {
            id: 2, // BECAUSE 1 IS THE MAIN SELECT ACTIONS SCREEN
            title: '',
            showBottomNavigation: () => !isNotImplemented,
            content: ({screenNavigation, close, width}) => {
                if (testableisOpen) {
                    return
                }
                const openTestablesPopup = useOpenTestablesPopupWindow();

                if (isNotImplemented) {
                    return <div className="max-w-100">
                        <NonImplementedMessage />
                    </div>
                }
                //const addBranchOffer = useNodesStore(store => store.addBranchOffer)
                // @ts-ignore
                const context = {
                    id: 'tier-new',
                    scope: 'tier-base',
                    data: {
                        supportedComponentTypes: ['filter', 'condition'],
                        componentType: 'filter',
                        targetType: 'testableComposite', //
                        supportsOptionalQuantity: false,
                        supportsMultipleComponents: false,
                        targetId: targetBranchId, // string id if testableComposite, index if root (eg: 0 for the first root, 1 for the second root, etc.)
                        mainWindow: {
                            title: __('What will the tiers be based on?'),
                            description: '',
                        },
                        ...getPopupStackDimensionCalculators(getOpenPopupsCount())
                    }
                } as PopupWindowStateContext<TreeContextData>;

                testableisOpen = true
                // we need: component type: filter, condition, etc
                openTestablesPopup({
                    // @ts-ignore
                    context,

                    onClose: (data) => {
                        const {addTreeNode} = useNodesStore.getState()
                        const {status, components, componentType} = data
                        const meta = getComponentMeta(`${componentType}s`, components?.[0]?.type)
                        // code is repeated from select-offers, should ideally be refactored to remove duplication
                        if (status === 'success' && components?.length > 0) {
                            const baseTestableId = generateIdForType('testable');

                            addTreeNode(
                                {
                                    parentBranchTestableId: baseTestableId,
                                    testable: {
                                        id: generateIdForType('testable.partial'),
                                        options: getDefaultOptionsForFirstTierSubchild(meta!)
                                    } as Omit<TestablePartial<Record<any, any>>, 'id'>,
                                    branch: {
                                        id: generateIdForType('branch'),
                                        type: 'select-action',
                                        children: []
                                    }
                                },
                                {
                                    parentBranchId: targetBranchId,
                                    newTieredBranchData: {
                                        baseTestable: {
                                            ...components[0]!,
                                            testableType: componentType as 'filter' | 'condition'
                                        },
                                        tierType: meta?.tierType || TierType.Numeric,
                                    }
                                }
                            )

                            close(status)
                        } else {
                            // failed, so go back to the previous screen
                            // this usually happens when the user hit "back" or the "x" button on the popup
                            screenNavigation.prev()
                        }
                        setTimeout(() => {
                            testableisOpen = false
                        }, 500)
                    }
                })
                return
            },
        }
    ],
}