import {Action} from "../SelectActionPopupWindow";
import {atom, useAtom} from "jotai";
import {ComponentRuntimeDataWithParentType} from "../components";
import React from "react";
import {Note} from "../cards";
import {merge, set} from "lodash";
import {produce} from "immer";
import {OfferData, useNodesStore} from "../store";
import {atomsStore, PopupWindowState, SelectActionContextOffers, SelectActionPopupWindowStateAtom} from "../atoms";
import {useOpenTestablesPopupWindow} from "../useOpenTestablesPopupWindow";
import {getOffersPopupWindowContext} from "../../OffersBranch";
import {useBranch} from "../TreeHooks";
import {BuyXGetXMeta} from "../cards/BuyXGetX";
import {__} from "../../globals";
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
}

export const incompatibleOffersFromInsideTiers = [
    BuyXGetXMeta.id
];

let offersTestableisOpen = false
// @ts-ignore
export const SelectOffersNew: Action = {
    id: 'select-offers',
    data: {
        name: __('Apply Offers'),
        icon: <svg width="74" height="53" viewBox="0 0 74 53" fill="none" xmlns="http://www.w3.org/2000/svg" className="min-w-10 min-h-10 max-w-10 max-h-10">
            <path d="M62.2002 0C68.2651 0.000107606 73.2002 4.93507 73.2002 11C73.2002 15.185 70.8503 18.8304 67.4004 20.6895V42.0986C67.2744 45.3686 64.684 47.9004 61.5 47.9004H59.9004V48.0996C59.9004 50.6996 57.6996 52.9004 55.0996 52.9004H4.7998C2.0999 52.9003 0 50.6995 0 48.0996V21.7002C0 19.1003 2.19989 16.9005 4.7998 16.9004H5.40039V15.7002C5.40039 12.5022 8.0022 9.90039 11.2002 9.90039H51.2559C51.8089 4.34939 56.5062 0 62.2002 0ZM11.2002 11.9004C9.1052 11.9004 7.40039 13.6042 7.40039 15.7002V42.0996C7.40039 44.1606 9.1402 45.9014 11.2002 45.9014H61.5C63.604 45.9014 65.3174 44.2135 65.4014 42.0605L65.4004 21.5225C64.3875 21.8314 63.3131 22 62.2002 22C56.4393 22 51.7063 17.5452 51.2461 11.9004H11.2002ZM10.999 31.7998C11.5509 31.7998 11.9989 32.2479 11.999 32.7998V36.3818C14.503 36.7958 16.4851 38.7412 16.9131 41.2002H20.5996C21.1516 41.2002 21.5986 41.6472 21.5986 42.2002C21.5985 42.7531 21.1506 43.2002 20.5986 43.2002H15.999C15.4471 43.2002 14.9991 42.7531 14.999 42.2002C14.999 40.0132 13.242 38.2998 10.999 38.2998C10.447 38.2998 9.99902 37.8518 9.99902 37.2998V32.7998C9.99913 32.2479 10.4471 31.7998 10.999 31.7998ZM61.7998 31.7998C62.3527 31.7998 62.7997 32.2479 62.7998 32.7998V37.2998C62.7998 37.8518 62.3528 38.2998 61.7998 38.2998C59.6319 38.2999 57.7998 40.0863 57.7998 42.2002C57.7997 42.7531 57.3527 43.2002 56.7998 43.2002H52.2002C51.6473 43.2002 51.2003 42.7531 51.2002 42.2002C51.2002 41.6472 51.6472 41.2002 52.2002 41.2002H55.8906C56.3306 38.7792 58.3349 36.8118 60.7998 36.3857V32.7998C60.7999 32.248 61.247 31.7999 61.7998 31.7998ZM36.2998 20.9004C40.7181 20.9004 44.2998 24.4821 44.2998 28.9004C44.2996 33.3185 40.718 36.9004 36.2998 36.9004C31.8817 36.9003 28.3 33.3184 28.2998 28.9004C28.2998 24.4822 31.8816 20.9005 36.2998 20.9004ZM20.7002 14.7002C21.2521 14.7003 21.7002 15.1483 21.7002 15.7002C21.7001 16.252 21.252 16.7001 20.7002 16.7002H17.0098C16.5687 19.1211 14.5635 21.0877 12.0996 21.5137V25.0996C12.0996 25.6516 11.6516 26.0996 11.0996 26.0996C10.5478 26.0994 10.0996 25.6515 10.0996 25.0996V20.5996C10.0998 20.0479 10.5479 19.5998 11.0996 19.5996C13.2675 19.5996 15.0995 17.8141 15.0996 15.7002C15.0996 15.1483 15.5478 14.7004 16.0996 14.7002H20.7002ZM62.2002 2C57.2372 2 53.2002 6.038 53.2002 11C53.2002 15.962 57.2372 20 62.2002 20C67.1631 19.9999 71.2002 15.9619 71.2002 11C71.2002 6.03807 67.1631 2.00011 62.2002 2ZM65.9932 7.29297C66.3842 6.90207 67.0163 6.902 67.4072 7.29297C67.7981 7.68394 67.7981 8.31606 67.4072 8.70703L61.4072 14.707C61.2123 14.902 60.9561 14.9999 60.7002 15C60.4442 15 60.1882 14.902 59.9932 14.707L56.9932 11.707C56.6022 11.316 56.6022 10.684 56.9932 10.293C57.3842 9.90207 58.0163 9.902 58.4072 10.293L60.7002 12.5859L65.9932 7.29297Z" 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: '',
            content: ({screenNavigation, close}) => {
                if (offersTestableisOpen ) {
                    return
                }
                const openTestablesPopup = useOpenTestablesPopupWindow();
                const branch = useBranch(targetBranchId)
                const addBranchOffer = useNodesStore(store => store.addBranchOffer)

                offersTestableisOpen = true
                // @ts-ignore
                openTestablesPopup({
                    // @ts-ignore
                    context: merge(
                        {

                            data: getPopupStackDimensionCalculators( getOpenPopupsCount())
                        },
                        getOffersPopupWindowContext([
                            // exclude get x if innside another branch (aka in tiers) bc get x is not supported in tiers currently
                            ...(branch?.isInsideAnotherBranch() ? incompatibleOffersFromInsideTiers : [])
                        ])
                    ),
                    onClose: (data) => {
                        const {status, components} = data

                        if (status === 'success' && components?.length > 0) {
                            // let's js ad the offer to the branch, the grove will handle the necessary logic for converting the branch if necessary, adding the offer to the store, etc.
                            addBranchOffer(components[0], targetBranchId)
                            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()
                        }
                        offersTestableisOpen = false
                        /*// @ts-ignore
                        const saver = new TestablesSaver(context)
                        // @ts-ignore
                        saver.add(data.components)*/
                    }
                })
                return
                // alight so here we'll open the testables popup window set to offers
                // then we'll add a handler so that we can talk to it after its been closed
                // there are two possible outcomes after closing:
                // 1- offers have been seected
                // 2- no offers have been selected, the user quit the popup

                // lets just first open it
                // @ts-ignore
                /*const context = {
                    id: 'offers-new',
                    scope: 'tree-node',
                    data: {
                        componentType: 'filter',
                        targetType: 'root', // root | testableComposite
                        targetId: null, // string id if testableComposite, index if root (eg: 0 for the first root, 1 for the second root, etc)
                    }
                } as PopupWindowStateContext<TreeContextData>*/

                /*openTestablesPopup({
                    // @ts-ignore
                    context,
                    onClose: (data) => {
                        console.log('got a request to close the popup wit: ', data)
                        /!*!// @ts-ignore
                        const saver = new TestablesSaver(context)
                        // @ts-ignore
                        saver.add(data.components)*!/
                    }
                })*/
                /**
                 * const openNewTestablesPopupWindow = useNewTestablesPopupWindow({
                 *     onClose: () => {} // here we'll handle the offers that were selected
                 * })
                 *
                 * opennewNewTestablesPopupWindow({
                 *      //here we'll set the data for the popup window (context, etc.)
                 * })
                 */
            },
        }
    ],
}