import {
    useLayoutEffect,
    useState,
    Fragment
} from "react";
import {
    View
} from "react-native";
import type IHeaderProps from "./type";
import type {
    NavigationType
} from "./type";
import stylesheet, {
    useStyles
} from "./stylesheet";
import {
    NCoreUIKitTheme
} from "../../core/hooks";
import {
    ChevronLeftIcon
} from "lucide-react-native";
import {
    SafeAreaView
} from "react-native-safe-area-context";
import Button from "../button";
import Text from "../text";

const Header = <T extends NavigationType>({
    backgroundColor = "default" as keyof NCoreUIKit.ContainerContentColors,
    isWrapSafeareaContext = true,
    isWorkWithHeaderSpace = true,
    renderTitle: renderTitleProp,
    renderRight: renderRightProp,
    safeAreaViewBackgroundColor,
    renderLeft: renderLeftProp,
    safeAreaViewStyle,
    isGoBackEnable,
    customTheme,
    headerSpace,
    titleProps,
    navigation,
    children,
    actions,
    title,
    style,
    ...props
}: IHeaderProps<T>) => {
    const {
        configs,
        colors,
        spaces
    } = NCoreUIKitTheme.useContext(customTheme);

    const [
        opacity,
        setOpacity
    ] = useState(false);

    const [
        leftContainerWidth,
        setLeftContainerWidth
    ] = useState<null | number>(null);

    const [
        rightContainerWidth,
        setRightContainerWidth
    ] = useState<null | number>(null);

    useLayoutEffect(() => {
        if(!opacity && leftContainerWidth !== null && rightContainerWidth !== null) {
            setOpacity(true);
        }
    }, [
        rightContainerWidth,
        leftContainerWidth
    ]);

    const {
        safeAreaView: safeAreaViewDynamicStyle,
        content: contentDynamicStyle
    } = useStyles({
        safeAreaViewBackgroundColor,
        isWorkWithHeaderSpace,
        backgroundColor,
        headerSpace,
        configs,
        spaces,
        colors
    });

    const renderLeft = () => {
        if(renderLeftProp) {
            return <View
                onLayout={(event) => {
                    const xW = event.nativeEvent.layout.width;

                    setLeftContainerWidth(xW);
                }}
                style={[
                    stylesheet.leftContainer
                ]}
            >
                {renderLeftProp({
                    navigation
                })}
            </View>;
        }

        if(!isGoBackEnable || !navigation) {
            if(leftContainerWidth === null) setLeftContainerWidth(0);
            return <View/>;
        }

        return <View
            onLayout={(event) => {
                const xW = event.nativeEvent.layout.width;

                setLeftContainerWidth(xW);
            }}
            style={[
                stylesheet.leftContainer
            ]}
        >
            <Button
                spreadBehaviour="free"
                variant="ghost"
                type="neutral"
                size="small"
                icon={({
                    color,
                    size
                }) => {
                    return <ChevronLeftIcon
                        color={colors.content.icon[color]}
                        size={size + 15}
                    />;
                }}
                onPress={() => {
                    if(navigation) {
                        (navigation as unknown as { goBack: () => void }).goBack();
                    }
                }}
            />
        </View>;
    };

    const renderRight = () => {
        if(renderRightProp) {
            return <View
                onLayout={(event) => {
                    const xW = event.nativeEvent.layout.width;

                    setRightContainerWidth(xW);
                }}
                style={[
                    stylesheet.rightContainer
                ]}
            >
                {renderRightProp({
                    navigation
                })}
            </View>;
        }

        if(!actions || !actions.length) {
            if(rightContainerWidth === null) setRightContainerWidth(0);
            return <View/>;
        }

        return <View
            onLayout={(event) => {
                const xW = event.nativeEvent.layout.width;

                setRightContainerWidth(xW);
            }}
            style={[
                stylesheet.rightContainer
            ]}
        >
            {actions.map((actionItem) => {
                return <Button
                    spreadBehaviour="free"
                    variant="ghost"
                    type="neutral"
                    size="small"
                    {...actionItem}
                />;
            })}
        </View>;
    };

    const renderTitle = () => {
        if(renderTitleProp) {
            return renderTitleProp({
                navigation
            });
        }

        if(!title) {
            return null;
        }

        if(leftContainerWidth === null || rightContainerWidth === null) {
            return null;
        }

        const sideWidth = leftContainerWidth > rightContainerWidth ? leftContainerWidth : rightContainerWidth;

        return <View
            style={[
                stylesheet.titleContainer,
                {
                    padding: spaces.spacingMd,
                    opacity: opacity ? 1 : 0
                }
            ]}
        >
            {<View
                style={{
                    width: sideWidth,
                    height: 40
                }}
            />}
            <Text
                variant="headlineSmallSize"
                numberOfLines={2}
                {...titleProps}
                style={{
                    ...stylesheet.title,
                    ...titleProps?.style
                }}
            >
                {title}
            </Text>
            {<View
                style={{
                    width: sideWidth,
                    height: 40
                }}
            />}
        </View>;
    };

    const renderContent = () => {
        return <View
            {...props}
            style={[
                contentDynamicStyle,
                stylesheet.container,
                style
            ]}
        >
            {renderTitle()}
            <View
                style={[
                    stylesheet.contentContainer
                ]}
            >
                {renderLeft()}
                {renderRight()}
            </View>
        </View>;
    };

    const renderWithSafeareaView = () => {
        return <SafeAreaView
            style={[
                safeAreaViewStyle,
                safeAreaViewDynamicStyle,
                stylesheet.safeAreaViewContainer
            ]}
        >
            {children ? children : renderContent()}
        </SafeAreaView>;
    };

    const renderSafeareaContext = () => {
        return isWrapSafeareaContext && !isWorkWithHeaderSpace ? renderWithSafeareaView() : <Fragment>
            {children ? children : renderContent()}
        </Fragment>;
    };

    return renderSafeareaContext();
};
export default Header;
