import React, {FC, useLayoutEffect, useRef, useState} from "react";
import {__} from "../globals";
import {RightContextButton, RightContextButtonProps} from "./RightContextButton";
import {TestableCompositeData} from "./store";
import {useChildrenIds} from "./testables";
import classNames from "classnames";
import {ColorOptionWithCustomTint} from "./Color";
import {
    PopupWindowStateContext,
    TestableGroupModePopupWindowContextData,
    TestableGroupModePopupWindowStateAtom
} from "./atoms";
import {useSuggestedScopeForTestableId} from "./getSuggestedScopeForTestable";
import {useSetAtom} from "jotai";
import {TestableGroupTypeId} from "./testableGroupTypes";

export let rightContextButtonWidth = 56;
const buttonWidthRegistry = new Map<string, number>();

export function getRightContextButtonWidth(widthId?: string): number {
    if (widthId && buttonWidthRegistry.has(widthId)) {
        return buttonWidthRegistry.get(widthId)!;
    }
    for (const width of buttonWidthRegistry.values()) {
        return width;
    }
    return rightContextButtonWidth;
}

export type RightContextButtonsProps =
    ColorOptionWithCustomTint
    & Pick<RightContextButtonProps, 'onRightButtonHoverStart' | 'onRightButtonHoverEnd'>
    & {
    widthId?: string,
    contextID: TestableCompositeData['id'],
    displayType?: 'always' | 'hover',
    isOpened?: boolean,
    parentData: TestableCompositeData,
    onClick?: (type: string) => void,
    showLabel?: boolean
}

export const RightContextButtons: FC<RightContextButtonsProps> = ({
                                                                      widthId,
                                                                      contextID,
                                                                      displayType,
                                                                      isOpened,
                                                                      parentData,
                                                                      color,
                                                                      onRightButtonHoverStart,
                                                                      onRightButtonHoverEnd,
                                                                      onClick,
                                                                      showLabel = true,
                                                                  }) => {
    const conditionOrFilterIds = useChildrenIds(contextID)
    const isClosed = displayType === 'hover' && !isOpened;
    const ref = useRef<HTMLDivElement>(null);
    const [, setCalculatedWidth] = useState<number | undefined>(undefined);
    const setTestableGroupModePopupWindowState = useSetAtom(TestableGroupModePopupWindowStateAtom)
    const suggestedScope = useSuggestedScopeForTestableId(contextID)
    const componentType = parentData?.mode === 'test' ? 'condition' : 'filter'

    useLayoutEffect(() => {
        const width = ref.current?.offsetWidth;
        if (width) {
            rightContextButtonWidth = width;
            if (widthId) {
                buttonWidthRegistry.set(widthId, width);
            }
        }
        setCalculatedWidth(width);
    }, [ref, widthId]);

    const openGroupModePopup = () => {
        const context: PopupWindowStateContext<TestableGroupModePopupWindowContextData> = {
            id: `testable-group-mode-${contextID}`,
            scope: 'tree-node',
            data: {
                targetId: contextID,
                componentType,
                suggestedScope,
            }
        }

        setTestableGroupModePopupWindowState({
            isOpen: true,
            context,
        })
    }

    return <div className={classNames('cp-right-context-buttons', {})}>
        <div ref={ref} className={classNames({
            'z-1000 transition-all duration-500': true,
            'space-y-1': conditionOrFilterIds.length === 1,
            'space-y-2': conditionOrFilterIds.length > 1,
            'opacity-0 group-hover:opacity-100 overflow-hidden': isClosed,
        })} style={{
            width: 'auto'
        }}>
            <RightContextButton type={TestableGroupTypeId.AND}
                                 color={color}
                                label={() => showLabel && <div className="flex items-center gap-1">
                                    <span>{__('AND')}</span>
                                    <div className="min-w-[6px] min-h-[6px] max-w-[6px] max-h-[6px] bg-purple-tint- rounded-full"></div>
                                    <span>{__('OR')}</span>
                                </div>}
                                onClick={onClick ? () => onClick(TestableGroupTypeId.AND) : openGroupModePopup}
                                onRightButtonHoverStart={onRightButtonHoverStart}
                                onRightButtonHoverEnd={onRightButtonHoverEnd}
            />
{/*
            <SuggestedWrapper show={suggestedScope === 'or_inclusive'}>
                <RightContextButton type={'OR'}
                                    color={color}
                                    label={__('OR')}
                                    onClick={onClick? () => onClick('OR') : openPopup('OR')}
                                    onRightButtonHoverStart={onRightButtonHoverStart}
                                    onRightButtonHoverEnd={onRightButtonHoverEnd}
                />
            </SuggestedWrapper>
*/}
        </div>
    </div>;
}
