import {
    useLayoutEffect,
    useEffect,
    useState,
    type FC,
    useRef
} from "react";
import {
    Platform,
    Animated,
    Easing,
    View
} from "react-native";
import type {
    MenuButton as MenuButtonType
} from "./type";
import type IMenuButton 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: MenuButtonType,
    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 MenuButton: FC<IMenuButton> = ({
    updateMenuButtonCollabs,
    closeAction,
    buttonIndex,
    buttonItem,
    navigation,
    depthMap,
    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);

    return <View
        key={`menu-button-${id}-${buttonIndex}-${navStateTracker.toString()}`}
    >
        <RowCard
            {...buttonItem.props}
            title={buttonItem.isUseLocalize ? localize(buttonItem.title as keyof NCoreUIKit.Translation) : buttonItem.title}
            rightIcon={
                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
            }
            backgroundColor={isPActive ? "primary" : undefined}
            titleColor={isPActive ? "onPrimary" : undefined}
            iconColor={isPActive ? "onPrimary" : undefined}
            icon={buttonItem.icon}
            onPress={() => {
                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();
            }}
        />
        {
            buttonItem.subButtons && buttonItem.subButtons.length ?
                <Animated.View
                    onLayout={buttonItem.isCollapsible ? (event) => {
                        const height = event.nativeEvent.layout.height;

                        if(height !== 0 && measure === null) setMeasure(height);
                    } : undefined}
                    style={[
                        Platform.OS === "web" ? {
                            height: measure === null ? "auto" : animatedCollabs,
                            overflow: "hidden"
                        } : {
                            display: isShowSubs ? "flex" : "none",
                            transform: [{
                                scaleY: animatedCollabs
                            }],
                            transformOrigin: "top",
                            overflow: "hidden"
                        }
                    ]}
                >
                    {buttonItem.subButtons.map((subButtonItem, subButtonIndex) => {
                        return <MenuButton
                            updateMenuButtonCollabs={updateMenuButtonCollabs}
                            key={`menu-sub-button-${id}-${subButtonIndex}`}
                            buttonIndex={subButtonIndex}
                            buttonItem={subButtonItem}
                            closeAction={closeAction}
                            navigation={navigation}
                            depthMap={[
                                ...depthMap,
                                subButtonIndex
                            ]}
                            id={id}
                        />;
                    })}
                </Animated.View>
                :
                null
        }
    </View>;
};
export default MenuButton;
