import React, {FC} from "react";
import {ConditionColorPalette, getConditionColorPalette} from "./Colors";
import {useOpenTestablesPopupWindow} from "./useOpenTestablesPopupWindow";
import {convertTestableData, useNodesStore} from "./store";
import {Testables} from "./testables";
import {PopupWindowStateContext, TreeContextData} from "./atoms";
import {Context} from "./Context";
import {__, CouponsPlus} from "../globals";
import {RightContextButton} from "./RightContextButton";
import {NoPredates} from "./NoPredates";
import {WeeklyScheduleMeta} from "./cards/conditions/WeeklySchedule";
import {HolidaysMeta} from "./cards/conditions/Holidays";
import {predatesConditionPalette} from "./predatesPalette";
import {VerticalOrConnector} from "./VerticalOrConnector";

export type TreePredatesProps = {
}

type PredatesAccentTheme = {
    headingIcon: string,
    headingTitle: string,
}

const getPredatesAccentTheme = (palette: ConditionColorPalette): PredatesAccentTheme => ({
    headingIcon: `text-${palette}-normal`,
    headingTitle: `text-${palette}-shade-100`,
})

/**
 * I know the name makes no sense but i kind of want to keep it the same as "predates", a better name couldve been "scheduling". This naming convention will be applied to "prefilters" too which themselves could be called something like "excluded products"
 * so:
 * preconditions
 * predates
 * prefilters
 *
 * Very self-explanatory when you read them this way (they will be executed before the main grove)
 */
export const TreePredates: FC<TreePredatesProps> = ({}) => {
    const predatesAccentTheme = getPredatesAccentTheme(predatesConditionPalette)
    const color = getConditionColorPalette(predatesConditionPalette)
    const predatesSupportedComponents = [
        CouponsPlus?.components?.conditions?.Date?.type,
        CouponsPlus?.components?.conditions?.WeeklySchedule?.type ?? WeeklyScheduleMeta.id,
        CouponsPlus?.components?.conditions?.Holidays?.type ?? HolidaysMeta.id
    ]
    const openTestablesPopupWindow = useOpenTestablesPopupWindow()
    const predatesID = useNodesStore(store => store.predatesID)
    const addTestables = useNodesStore(store => store.addTestables)
    const predatesContextIDs: string[] = useNodesStore(({
                                                                 predatesID,
                                                                 testables,
                                                                 testableRelations,
                                                                 testablePartials
                                                             }) => {
        if (!predatesID) {
            return []
        }

        const testablesManager = new Testables({testables, testableRelations, testablePartials})

        return testablesManager.getChildren(predatesID).map(({id}) => id)
    })

    if (predatesContextIDs.length === 0) {
        return <NoPredates/>
    }

    /**
     * This has a lot of repetition with the testable popup of NoPredates
     */
    const openTestables = () => {
        // @ts-ignore
        const context = {
            id: 'predates-or-add',
            scope: 'predates',
            data: {
                componentType: 'condition',
                conditionColorPalette: predatesConditionPalette,
                targetType: 'testableComposite',
                supportedComponents: predatesSupportedComponents,
                supportsMultipleComponents: false,
                showTabs: false,
                targetId: predatesID, // this is the main predates 'OR' group
            }
        } as PopupWindowStateContext<TreeContextData>

        openTestablesPopupWindow({
            // @ts-ignore
            context,
            onClose: (data) => {
                if (data.status !== 'success' || !data.components) {
                    return
                }

                addTestables([
                    convertTestableData(data.components),
                    predatesID,
                    true // wrap in group
                ], (addedIds, testablesManager, writeableStore) => {
                })
            }
        })
    }

    return <div className="grid grid-cols-1 gap-0 w-full max-w-74">
        <div className={'flex gap-1 items-center pl-2 mb-1'}>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className={`min-w-4 min-h-4 max-w-4 max-h-4 ${predatesAccentTheme.headingIcon}`}>
                <path fillRule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25ZM12.75 6a.75.75 0 0 0-1.5 0v6c0 .414.336.75.75.75h4.5a.75.75 0 0 0 0-1.5h-3.75V6Z" clipRule="evenodd" />
            </svg>
            <h1 className={`text-smaller-1 font-medium ${predatesAccentTheme.headingTitle}`}>{__('Available')}</h1>
        </div>
        <div className={'grid grid-cols-1 gap-0'}>
            {predatesContextIDs.map((id, index) => <div key={id} className="w-full">
                <Context id={id}
                         color={color}
                         conditionColorPalette={predatesConditionPalette}
                         popupScope={'predates'}
                         popupSupportedComponents={predatesSupportedComponents}
                         popupConditionColorPalette={predatesConditionPalette}
                         popupShowTabs={false}
                         buttonsAreEnabled={false}
                         fullWidth={true}
                         supportsMultipleComponents={false}
                         showRemoveButtonLabel={false}
                />
                {index + 1 < predatesContextIDs.length &&
                    <VerticalOrConnector color={color} label={__('OR')} />}
                {(index + 1 === predatesContextIDs.length) && (
                    <div className="mt-[-5px]">
                        <RightContextButton onClick={openTestables} type={'OR'} color={color} label={__('OR')}
                                            direction={'vertical'}/>
                    </div>
                )}
            </div>)}
        </div>
    </div>

}
