import {
    useState,
    Fragment
} from "react";
import {
    TouchableOpacity,
    View
} from "react-native";
import type IUserShortcutProps from "./type";
import stylesheet, {
    useStyles
} from "./stylesheet";
import {
    NCoreUIKitLocalize,
    NCoreUIKitTheme
} from "../../core/hooks";
import {
    useContext as useCoreComplexContext
} from "../../core/contexts/coreComplex";
import {
    ChevronDown as ChevronDownIcon,
    ChevronLeft as ChevronLeftIcon,
    UserPlus as UserPlusIcon,
    LogIn as LogInIcon
} from "lucide-react-native";
import {
    STATUS_CHEAT_SHEET
} from "../../utils";
import BottomSheet from "../bottomSheet";
import Avatar from "../avatar";
import Button from "../button";
import Text from "../text";

const UserShortcut = ({
    isShowLoginButtonWhenNoSession = true,
    isShowRegisterButton = false,
    isWorkWithCoreComplex = true,
    spreadBehaviour = "baseline",
    isShowLogoutButton = true,
    isShowArrowButton = true,
    backgroundColor = "mid",
    isSessionActive = true,
    variant = "default",
    onRegisterPress,
    actionButtons,
    onLogoutPress,
    onLoginPress,
    avatarProps,
    customTheme,
    statusColor,
    isDisabled,
    statusText,
    maxWidth,
    subTitle,
    onPress,
    badges,
    title,
    style
}: IUserShortcutProps) => {
    const [
        isBottomSheetOpen,
        setIsBottomSheetOpen
    ] = useState(false);

    const {
        client: coreComplexClient
    } = useCoreComplexContext();

    const {
        radiuses,
        spaces,
        colors
    } = NCoreUIKitTheme.useContext(customTheme);

    const {
        localize
    } = NCoreUIKitLocalize.useContext();

    const resolvedStatusText = statusText || (
        avatarProps?.statusIndicatorType ?
            localize(`activity-status-${avatarProps.statusIndicatorType}` as keyof NCoreUIKit.Translation)
        :
            undefined
    );

    const resolvedStatusColor = statusColor || (
        avatarProps?.statusIndicatorType ?
            STATUS_CHEAT_SHEET[avatarProps.statusIndicatorType].text as keyof NCoreUIKit.TextContentColors
        :
            "success"
    );

    const resolvedIsSessionActive = isWorkWithCoreComplex ?
        !!coreComplexClient?.variables?.accessToken
    :
        isSessionActive;

    const isNoSession = !resolvedIsSessionActive;

    const {
        subTitleContainer: subTitleContainerDynamicStyle,
        actionContainer: actionContainerDynamicStyle,
        dotSeperator: dotSeperatorDynamicStyle,
        container: containerDynamicStyle
    } = useStyles({
        spreadBehaviour,
        backgroundColor,
        isDisabled,
        maxWidth,
        radiuses,
        colors,
        spaces
    });

    const renderSubTitle = () => {
        if(isNoSession || (!subTitle && !resolvedStatusText)) {
            return null;
        }

        return <View
            style={[
                stylesheet.subTitleContainer,
                subTitleContainerDynamicStyle
            ]}
        >
            {
                resolvedStatusText ?
                    <Text
                        color={resolvedStatusColor}
                        variant="labelSmallSize"
                        ellipsizeMode="tail"
                        numberOfLines={1}
                        style={{
                            flexShrink: 1
                        }}
                    >
                        {resolvedStatusText}
                    </Text>
                :
                    null
            }
            {
                subTitle ?
                    <Fragment>
                        <Text
                            style={{
                                ...dotSeperatorDynamicStyle
                            }}
                            variant="labelSmallSize"
                            color="low"
                        >
                            •
                        </Text>
                        <Text
                            style={stylesheet.subTitle}
                            variant="labelSmallSize"
                            ellipsizeMode="tail"
                            numberOfLines={1}
                            color="low"
                        >
                            {subTitle}
                        </Text>
                    </Fragment>
                :
                    null
            }
        </View>;
    };

    const renderContent = () => {
        if(isNoSession || variant === "compact") {
            return null;
        }

        return <View
            style={stylesheet.contentContainer}
        >
            <Text
                variant="labelLargeSize"
                ellipsizeMode="tail"
                numberOfLines={1}
                color="high"
            >
                {title}
            </Text>
            {renderSubTitle()}
        </View>;
    };

    const renderAction = () => {
        if(variant === "compact") {
            return null;
        }

        if(isNoSession) {
            if(!isShowLoginButtonWhenNoSession && !isShowRegisterButton) {
                return null;
            }

            return <View
                style={[
                    stylesheet.actionContainer,
                    actionContainerDynamicStyle,
                    {
                        marginLeft: spaces.spacingXs,
                        gap: spaces.spacingMd,
                        flexDirection: "row"
                    }
                ]}
            >
                {
                    isShowLoginButtonWhenNoSession ?
                        <Button
                            icon={({
                                color,
                                size
                            }) => {
                                return <LogInIcon
                                    color={colors.content.icon[color]}
                                    size={size + 2}
                                />;
                            }}
                            onPress={() => onLoginPress?.()}
                            title={localize("login")}
                            spreadBehaviour="free"
                            type="neutral"
                            size="small"
                        />
                    :
                        null
                }
                {
                    isShowRegisterButton ?
                        <Button
                            icon={({
                                color,
                                size
                            }) => {
                                return <UserPlusIcon
                                    color={colors.content.icon[color]}
                                    size={size + 2}
                                />;
                            }}
                            onPress={() => onRegisterPress?.()}
                            title={localize("register")}
                            spreadBehaviour="free"
                            type="neutral"
                            size="small"
                        />
                    :
                        null
                }
            </View>;
        }

        if(!isShowArrowButton) {
            return null;
        }

        return <View
            style={[
                stylesheet.actionContainer,
                actionContainerDynamicStyle
            ]}
        >
            <Button
                icon={({
                    color,
                    size
                }) => {
                    if(isBottomSheetOpen) {
                        return <ChevronDownIcon
                            color={colors.content.icon[color]}
                            size={size + 5}
                        />;
                    }

                    return <ChevronLeftIcon
                        color={colors.content.icon[color]}
                        size={size + 5}
                    />;
                }}
                onPress={() => {
                    setIsBottomSheetOpen(!isBottomSheetOpen);
                }}
                isDisabled={isDisabled}
                spreadBehaviour="free"
                type="neutral"
                size="small"
            />
        </View>;
    };

    const renderBadges = () => {
        if(isNoSession || !badges || badges.length === 0) {
            return null;
        }

        return badges.map((badge, index) => {
            return <View
                style={[
                    stylesheet.badgeContainer,
                    {
                        zIndex: index + 1
                    }
                ]}
                pointerEvents="none"
                key={index}
            >
                {badge}
            </View>;
        });
    };

    const renderBottomSheet = () => {
        if(isNoSession || !isShowArrowButton) {
            return null;
        }

        return <BottomSheet
            onClose={() => setIsBottomSheetOpen(false)}
            isActive={isBottomSheetOpen}
            isWorkWithAnimation={true}
        >
            <View
                style={{
                    padding: spaces.spacingLg,
                    gap: spaces.spacingMd
                }}
            >
                {
                    actionButtons?.map((buttonProps, index) => {
                        return <Button
                            spreadBehaviour="stretch"
                            type="neutral"
                            key={index}
                            {...buttonProps}
                        />;
                    })
                }
                {
                    isShowLogoutButton ?
                        <Button
                            title={localize("logout" as keyof NCoreUIKit.Translation)}
                            onPress={async () => {
                                setIsBottomSheetOpen(false);

                                let response;
                                let error;

                                if(isWorkWithCoreComplex && coreComplexClient) {
                                    try {
                                        response = await (
                                            coreComplexClient.NAuth as unknown as {
                                                logout: () => Promise<unknown>;
                                            }
                                        ).logout();
                                    } catch(e) {
                                        error = e;
                                    }
                                }

                                if(onLogoutPress) {
                                    onLogoutPress(response, error);
                                }
                            }}
                            spreadBehaviour="stretch"
                            type="danger"
                        />
                    :
                        null
                }
            </View>
        </BottomSheet>;
    };

    return <Fragment>
        <TouchableOpacity
            activeOpacity={isNoSession && (isShowLoginButtonWhenNoSession || isShowRegisterButton) ? 1 : 0.2}
            onPress={isDisabled ? undefined : () => {
                if(isNoSession && (isShowLoginButtonWhenNoSession || isShowRegisterButton)) {
                    return;
                }

                if(onPress) onPress();

                if(variant === "compact" && isShowArrowButton && !isNoSession) {
                    setIsBottomSheetOpen(!isBottomSheetOpen);
                }
            }}
            style={[
                style,
                stylesheet.container,
                containerDynamicStyle
            ]}
            disabled={isDisabled}
        >
            <View
                style={stylesheet.avatarContainer}
            >
                <Avatar
                    {...(isNoSession ? {
                        ...avatarProps,
                        isStatusIndicator: false,
                        title: undefined,
                        url: undefined
                    } : {
                        ...avatarProps,
                        isStatusIndicator: avatarProps?.isStatusIndicator ?? !!resolvedStatusText
                    })}
                    size="medium"
                />
                {renderBadges()}
            </View>
            {renderContent()}
            {renderAction()}
        </TouchableOpacity>
        {renderBottomSheet()}
    </Fragment>;
};
export default UserShortcut;
