import {
    useEffect,
    useMemo,
    useRef,
    useState,
} from 'react';

import jsonLogic from 'json-logic-js';

import { EventEmitter } from '@/utils/event';

import { ItemDataProps } from './types';

const HideData = (props: ItemDataProps & { children?: React.ReactNode }) => {

    const [logicHide, setLogicHide] = useState(false);

    // Используем ref для хранения актуальных функций и условий
    const propsRef = useRef(props);
    const globalCondsRef = useRef(props.structure.cond ?? []);
    const localCondsRef = useRef(props.structure.localCond ?? []);

    // Обновляем ref при изменении props
    useEffect(() => {
        propsRef.current = props;
        globalCondsRef.current = props.structure.cond ?? [];
        localCondsRef.current = props.structure.localCond ?? [];
    }, [props]);

    const globalConds = useMemo(() => props.structure.cond ?? [], [props.structure.cond]);
    const localConds = useMemo(() => props.structure.localCond ?? [], [props.structure.localCond]);

    const checkVisibility = () => {
        // Получаем актуальные данные через ref, чтобы избежать замыкания на старые значения
        const currentProps = propsRef.current;
        const valueData = currentProps?.getDataValue?.() ?? {};
        const parentData = currentProps?.getParentValue?.() ?? {};
        const currentGlobalConds = globalCondsRef.current;
        const currentLocalConds = localCondsRef.current;



        const allConditions = [
            ...currentGlobalConds.map((c: any) => ({ condition: c, context: valueData })),
            ...currentLocalConds.map((c: any) => ({ condition: c, context: parentData }))
        ];

        const shouldHide = allConditions.some(({ condition, context }) =>
            !jsonLogic.apply(condition, context as any)
        );

        setLogicHide(shouldHide);
    };

    useEffect(() => {
        if (globalConds.length === 0 && localConds.length === 0) {
            setLogicHide(false);
            return;
        }

        checkVisibility();

        const unsubscribe = EventEmitter.subscribe("updateField", () => {
            checkVisibility();
        });

        return () => {
            unsubscribe();
        };
    }, [globalConds, localConds]);

    if (logicHide) return null;

    return <>{props.children}</>;
};

export default HideData;