import React, {FC} from "react";
import {convertTestableData, useNodesStore} from "./store";
import {NoPreconditions} from "./NoPreconditions";
import {Testables} from "./testables";
import {Context} from "./Context";
import {__} from "../globals";
import {RightContextButton} from "./RightContextButton";
import {getColorForComponentType} from "./Colors";
import {useOpenTestablesPopupWindow} from "./useOpenTestablesPopupWindow";
import {PopupWindowStateContext, TreeContextData} from "./atoms";
import {VerticalOrConnector} from "./VerticalOrConnector";

export type TreePreconditionsProps = {}

export const TreePreconditions: FC<TreePreconditionsProps> = () => {
    const color = getColorForComponentType('condition')
    const openTestablesPopupWindow = useOpenTestablesPopupWindow()
    const preconditionsID = useNodesStore(store => store.preconditionsID)
    const addTestables = useNodesStore(store => store.addTestables)
    const testablesManagerRef = React.useRef<Testables>()
    const preconditionsContextIDs: string[] = useNodesStore(({
                                                                 preconditionsID,
                                                                 testables,
                                                                 testableRelations,
                                                                 testablePartials
                                                             }) => {
        if (!preconditionsID) {
            return []
        }

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

        testablesManagerRef.current = testablesManager
        return testablesManager.getChildren(preconditionsID).map(({id}) => id)
    })
/*
    if (testablesManagerRef.current) {
        const testable = new Testable(testablesManagerRef.current, preconditionsID || '')
        if (!testable.exists()) {
            testablesManagerRef.current.remove(preconditionsID!)
        }
    }
*/

    if (preconditionsContextIDs.length === 0) {
        return <NoPreconditions/>
    }

    const openTestables = () => {
        // @ts-ignore
        const context = {
            id: 'preconditions-or-add',
            scope: 'preconditions',
            data: {
                componentType: 'condition',
                targetType: 'testableComposite',
                targetId: preconditionsID, // this is the main preconditions 'OR' group
                showTabs: false
            }
        } as PopupWindowStateContext<TreeContextData>

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

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

    return <div className={'grid grid-cols-1 gap-0 max-w-74'}>
        <div className={'flex gap-1 items-center text-gray-500 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">
                <path d="M10.5 1.875a1.125 1.125 0 0 1 2.25 0v8.219c.517.162 1.02.382 1.5.659V3.375a1.125 1.125 0 0 1 2.25 0v10.937a4.505 4.505 0 0 0-3.25 2.373 8.963 8.963 0 0 1 4-.935A.75.75 0 0 0 18 15v-2.266a3.368 3.368 0 0 1 .988-2.37 1.125 1.125 0 0 1 1.591 1.59 1.118 1.118 0 0 0-.329.79v3.006h-.005a6 6 0 0 1-1.752 4.007l-1.736 1.736a6 6 0 0 1-4.242 1.757H10.5a7.5 7.5 0 0 1-7.5-7.5V6.375a1.125 1.125 0 0 1 2.25 0v5.519c.46-.452.965-.832 1.5-1.141V3.375a1.125 1.125 0 0 1 2.25 0v6.526c.495-.1.997-.151 1.5-.151V1.875Z" />
            </svg>
            <h1 className={'text-gray-550 text-smaller-1 font-medium'}>{__('Preconditions')}</h1>
        </div>
        <div className="grid grid-cols-1 gap-0">
            {preconditionsContextIDs.map((id, index) => <div key={id}>
                <Context id={id} color={color} popupScope={'preconditions'} buttonsAreEnabled={false} fullWidth={true} showRemoveButtonLabel={false} />
                {index + 1 < preconditionsContextIDs.length &&
                    <VerticalOrConnector color={color} label={__('OR')} />}
                {(index + 1 === preconditionsContextIDs.length) && (
                    <div className="mt-[-5px]">
                        <RightContextButton onClick={openTestables} type={'OR'} color={color} label={__('OR')}
                                            direction={'vertical'}/>
                    </div>
                )}
            </div>)}
        </div>
    </div>
};
