import {
    useLayoutEffect,
    useEffect,
    useState,
    type FC,
    useRef
} from "react";
import {
    Platform,
    Animated,
    Easing,
    View
} from "react-native";
import type {
    EmbeddedMenuButton as EmbeddedMenuButtonType
} from "./type";
import type IEmbeddedMenuButton from "./type";
import {
    NCoreUIKitLocalize,
    NCoreUIKitTheme
} from "../../../../core/hooks";
import {
    ChevronRightIcon,
    ChevronDownIcon,
    ChevronLeftIcon
} from "lucide-react-native";
import RowCard from "../../../rowCard";

const getDeepActiveRouteName = (state: NCoreUIKit.NavigationState): string | undefined => {
    if (!state?.routes?.length) return undefined;

    const activeIndex = state.index ?? 0;
    const activeRoute = state.routes[activeIndex];

    if (!activeRoute) return undefined;

    if (activeRoute.state) {
        return getDeepActiveRouteName(activeRoute.state);
    }
    return activeRoute.name;
};

const isPageActive = (
    buttonItem: EmbeddedMenuButtonType,
    navigation: NCoreUIKit.Navigation
): boolean => {
    if (!navigation) return false;

    const state = typeof navigation.getRootState === "function"
        ? navigation.getRootState()
        : typeof navigation.getState === "function"
            ? navigation.getState()
            : null;

    if (!state?.routes) return false;

    const activeRouteName = getDeepActiveRouteName(state);
    const targetName = buttonItem.redirectSub ?? buttonItem.redirectMain;

    if (targetName && activeRouteName === targetName) return true;

    if (buttonItem.subButtons?.length) {
        return buttonItem.subButtons.some(sub => isPageActive(sub, navigation));
    }

    return false;
};

const EmbeddedMenuButton: FC<IEmbeddedMenuButton> = ({
    updateMenuButtonCollabs,
    isMenuCollabs,
    buttonIndex,
    closeAction,
    buttonItem,
    navigation,
    depthMap,
    openMenu,
    id
}) => {
    const {
        colors
    } = NCoreUIKitTheme.useContext();

    const {
        localize
    } = NCoreUIKitLocalize.useContext();

    const [
        measure,
        setMeasure
    ] = useState<null | number>(null);

    const [
        navStateTracker,
        setNavStateTracker
    ] = useState(Date.now());

    const [
        isShowSubs,
        setIsShowSubs
    ] = useState(buttonItem.isCollapse);

    const animatedCollabs = useRef(new Animated.Value(0)).current;

    useEffect(() => {
        if (!navigation || typeof navigation.addListener !== "function") return;

        const unsubscribeState = navigation.addListener("state", () => {
            setNavStateTracker(Date.now());
        });

        const unsubscribeFocus = navigation.addListener("focus", () => {
            setNavStateTracker(Date.now());
        });

        return () => {
            if (unsubscribeState) unsubscribeState();
            if (unsubscribeFocus) unsubscribeFocus();
        };
    }, [
        navigation
    ]);

    useLayoutEffect(() => {
        if(isShowSubs) {
            Animated.timing(animatedCollabs, {
                toValue: Platform.OS === "web" ? Number(measure) : 1,
                useNativeDriver: Platform.OS !== "web",
                easing: Easing.linear,
                duration: 150
            }).start();
        }
    }, [
        isShowSubs
    ]);

    useLayoutEffect(() => {
        if(!buttonItem.isCollapsible) return;

        if(Platform.OS === "web" && measure === null) return;

        if(buttonItem.isCollapse) {
            setIsShowSubs(true);
        } else {
            Animated.timing(animatedCollabs, {
                useNativeDriver: Platform.OS !== "web",
                easing: Easing.linear,
                duration: 150,
                toValue: 0
            }).start(({
                finished
            }) => {
                if(finished) {
                    setIsShowSubs(false);
                }
            });
        }
    }, [
        buttonItem.isCollapse,
        measure
    ]);

    const isPActive = isPageActive(buttonItem, navigation);

    if(!isMenuCollabs && !buttonItem.icon) {
        return null;
    }

    return <View
        key={`menu-button-${id}-${buttonIndex}-${navStateTracker.toString()}`}
    >
        <RowCard
            {...buttonItem.props}
            title={isMenuCollabs ? buttonItem.isUseLocalize ? localize(buttonItem.title as keyof NCoreUIKit.Translation) : buttonItem.title : ""}
            rightIcon={
                isMenuCollabs && (buttonItem.isCollapsible || buttonItem.isShowRedirectIcon) ?
                    () => {
                        if(buttonItem.isCollapsible) {
                            if(buttonItem.isCollapse) {
                                return <ChevronDownIcon
                                    color={isPActive ? colors.content.icon.onPrimary : colors.content.icon.low}
                                    size={18}
                                />;
                            } else {
                                return <ChevronLeftIcon
                                    color={isPActive ? colors.content.icon.onPrimary : colors.content.icon.low}
                                    size={18}
                                />;
                            }
                        } else {
                            return <ChevronRightIcon
                                color={isPActive ? colors.content.icon.onPrimary : colors.content.icon.low}
                                size={18}
                            />;
                        }
                    }
                    :
                    undefined
            }
            onPress={() => {
                if(!isMenuCollabs && buttonItem.subButtons && buttonItem.subButtons.length) {
                    openMenu();
                    updateMenuButtonCollabs({
                        status: true,
                        buttonItem,
                        depthMap
                    });
                    return;
                }

                if(buttonItem.isCollapsible) {
                    updateMenuButtonCollabs({
                        status: !buttonItem.isCollapse,
                        buttonItem,
                        depthMap
                    });
                } else {
                    if(buttonItem.redirectMain || buttonItem.redirectSub) {
                        if(buttonItem.redirectMain && buttonItem.redirectSub) {
                            navigation.navigate(buttonItem.redirectMain, {
                                screen: buttonItem.redirectSub
                            });
                        } else if(buttonItem.redirectMain) {
                            navigation.navigate(buttonItem.redirectMain);
                        }
                    }

                    if(buttonItem.props?.onPress) buttonItem.props.onPress();
                }

                if(closeAction && !buttonItem.isCollapsible) closeAction();
            }}
            backgroundColor={isPActive ? "primary" : undefined}
            titleColor={isPActive ? "onPrimary" : undefined}
            iconColor={isPActive ? "onPrimary" : undefined}
            icon={buttonItem.icon}
        />
        {
            buttonItem.subButtons && buttonItem.subButtons.length ?
                <Animated.View
                    style={[
                        Platform.OS === "web" ? {
                            height: !isMenuCollabs ? 0 : (measure === null ? "auto" : animatedCollabs),
                            overflow: "hidden"
                        } : {
                            display: (!isMenuCollabs || !isShowSubs) ? "none" : "flex",
                            transform: [
                                {
                                    scaleY: animatedCollabs
                                }
                            ],
                            transformOrigin: "top",
                            overflow: "hidden"
                        }
                    ]}
                    onLayout={buttonItem.isCollapsible ? (event) => {
                        const height = event.nativeEvent.layout.height;

                        if(height !== 0 && measure === null) setMeasure(height);
                    } : undefined}
                >
                    {buttonItem.subButtons.map((subButtonItem, subButtonIndex) => {
                        return <EmbeddedMenuButton
                            key={`embedded-menu-sub-button-${id}-${subButtonIndex}`}
                            updateMenuButtonCollabs={updateMenuButtonCollabs}
                            isMenuCollabs={isMenuCollabs}
                            buttonIndex={subButtonIndex}
                            buttonItem={subButtonItem}
                            closeAction={closeAction}
                            navigation={navigation}
                            openMenu={openMenu}
                            depthMap={[
                                ...depthMap,
                                subButtonIndex
                            ]}
                            id={id}
                        />;
                    })}
                </Animated.View>
            :
                null
        }
    </View>;
};
export default EmbeddedMenuButton;
