import {
    useState
} from "react";
import {
    TouchableOpacity,
    Image,
    View
} from "react-native";
import type IAvatarProps from "./type";
import stylesheet, {
    getAvatarSize,
    useStyles
} from "./stylesheet";
import {
    NCoreUIKitTheme
} from "../../core/hooks";
import {
    UserRound as UserRoundIcon
} from "lucide-react-native";
import Loading from "../loading";
import Text from "../text";

const Avatar = ({
    titleAbbreviationType = "first-last",
    isShowStatusIndicatorSplicer = true,
    avatarBackgroundColor = "default",
    statusIndicatorType = "online",
    titleColor = "onPrimary",
    isShowBorder = false,
    isStatusIndicator,
    isWorkWithAction,
    image: ImageProp,
    backgroundColor,
    size = "medium",
    icon: IconProp,
    imageSource,
    customTheme,
    borderColor,
    isDisabled,
    imageProps,
    isLoading,
    iconColor,
    imageUrl,
    onPress,
    title,
    style
}: IAvatarProps) => {
    const {
        borders,
        colors,
        spaces
    } = NCoreUIKitTheme.useContext(customTheme);

    const currentSize = getAvatarSize({
        spaces,
        size
    });

    const [
        imageLoadError,
        setImageLoadError
    ] = useState(false);

    const {
        statusIndicator: statusIndicatorDynamicStyle,
        container: containerDynamicStyle,
        image: imageDynamicStyle,
        icon: iconDynamicStyle
    } = useStyles({
        isShowStatusIndicatorSplicer,
        avatarBackgroundColor,
        statusIndicatorType,
        image: ImageProp,
        backgroundColor,
        isShowBorder,
        borderColor,
        currentSize,
        isDisabled,
        isLoading,
        imageUrl,
        borders,
        colors,
        title
    });

    const calculateShortTitle = () => {
        if(!title) {
            return "";
        }

        const allWords: Array<string> = title.split(" ");

        if(titleAbbreviationType === "every-first") {
            let newString = "";

            allWords.forEach((wordItem, wordIndex) => {
                if(wordIndex < 3) newString += wordItem[0];
            });

            return newString;
        }

        if(titleAbbreviationType === "first-last") {
            let newString = "";

            if(allWords[0]) newString += allWords[0][0];

            if(allWords.length > 1 && allWords[allWords.length - 1]) newString += allWords[allWords.length - 1]?.[0];

            return newString;
        }

        if(titleAbbreviationType === "first-next") {
            let newString = "";

            if(allWords[0]) newString += allWords[0][0];

            if(allWords[1]) newString += allWords[1][0];

            return newString;
        }

        return title;
    };

    const renderIcon = () => {
        if(IconProp) {
            return <IconProp
                size={currentSize.iconSize}
                customColor={iconColor}
                color="default"
                style={{
                    ...iconDynamicStyle
                }}
            />;
        }

        return <UserRoundIcon
            color={iconColor ? iconColor : colors.content.icon.default}
            size={currentSize.iconSize}
            style={{
                ...iconDynamicStyle
            }}
        />;
    };

    const renderStatusIndicator = () => {
        if(!isStatusIndicator) {
            return null;
        }

        return <View
            style={[
                stylesheet.statusIndicator,
                statusIndicatorDynamicStyle
            ]}
        />;
    };

    const renderLoading = () => {
        let loadingColor: keyof NCoreUIKit.IconContentColors = "default";

        if(title) {
            loadingColor = "onPrimary";
        } else if(imageUrl || ImageProp) {
            loadingColor = "mid";
        }

        return <Loading
            color={loadingColor}
        />;
    };

    const renderContent = () => {
        if(isLoading) {
            return renderLoading();
        }

        if(IconProp) {
            return renderIcon();
        }

        if(!title && !ImageProp && !imageUrl) {
            return renderIcon();
        }

        if((imageUrl || ImageProp) && imageLoadError) {
            if(title) {
                return <Text
                    variant={currentSize.fontSize}
                    color={titleColor}
                >
                    {calculateShortTitle()}
                </Text>;
            } else {
                return renderIcon();
            }
        }

        if(ImageProp) {
            return <ImageProp
                {...imageProps}
                onError={() => setImageLoadError(true)}
                height={currentSize.size}
                width={currentSize.size}
                style={[
                    stylesheet.image,
                    imageDynamicStyle,
                    imageProps?.style
                ]}
            />;
        }

        if(imageUrl) {
            return <Image
                {...imageProps}
                onError={() => setImageLoadError(true)}
                height={currentSize.size}
                width={currentSize.size}
                source={{
                    uri: imageUrl,
                    ...imageSource
                }}
                style={[
                    stylesheet.image,
                    imageDynamicStyle,
                    imageProps?.style
                ]}
            />;
        }

        return <Text
            variant={currentSize.fontSize}
            color={titleColor}
        >
            {calculateShortTitle()}
        </Text>;
    };

    return <TouchableOpacity
        disabled={!isWorkWithAction || isDisabled || isLoading}
        onPress={!isWorkWithAction || isDisabled || isLoading ? undefined : () => {
            if(onPress) onPress();
        }}
        style={[
            style,
            stylesheet.container,
            containerDynamicStyle
        ]}
    >
        {renderContent()}
        {renderStatusIndicator()}
    </TouchableOpacity>;
};
export default Avatar;
