import React, { FunctionComponent, useEffect, useState } from 'react';
import {
    Image,
    ImageStyle,
    Text,
    TextStyle,
    View,
    ViewStyle,
} from 'react-native';
import { IStyledProps } from './types';

export interface IImageHolderStyle {
    thumbnail?: ImageStyle;
    thumbnailContainer?: ViewStyle;
    imageTextStyle?: TextStyle
}
export interface IProps extends IStyledProps<IImageHolderStyle> {
    url?: string;
    name?: string;
}

export const ImageHolder: FunctionComponent<IProps> = ({
    url,
    name,
    style,
}) => {
    const mergedStyle = { ...imageHolderStyle, ...style };
    const [displayName, setDisplayName] = useState<string>('');

    useEffect(() => {
        const initials = calculateInitialName(name)
        setDisplayName(initials)
    }, [name]);

    const getColorValueFromDisplayName = (str: string) => {
        const textAvatarColors: string[] = [
            '#ca8741',
            '#e44647',
            '#c62582',
            '#9b4ce7',
            '#6573ee',
            '#1b70e0',
            '#6ec7d9',
            '#98d1b1',
            '#7fbd40',
            '#b2d334',
            '#dcd232',
            '#f1be00'];
        const upperCaseDisplayName = str.toUpperCase();
        let sum: number = 0;
        for (let charCtr = 0; charCtr < upperCaseDisplayName.length; charCtr++) {
            sum += upperCaseDisplayName.charCodeAt(charCtr);
        }
        // get the color from the array
        return textAvatarColors[(sum % 12)];
    }

    const calculateInitialName = (nameString: string = '') => {
        const fullName = nameString.split(' ');
        let initials = ''
        fullName.map((item) => {
            initials += item[0]
        });
        return initials.toUpperCase()
    }


    if (url) {
        const profileUrl = { uri: url };
        return <Image source={profileUrl} style={mergedStyle.thumbnail} />
    }
    else if (name) {
        const generatedBackground = getColorValueFromDisplayName(name);
        const profilePicStyle = { ...mergedStyle.thumbnailContainer, backgroundColor: generatedBackground };
        return <View style={profilePicStyle}>
            <Text style={mergedStyle.imageTextStyle}>{displayName}</Text>
        </View>
    } else {
        return null
    }
};

const imageHolderStyle: IImageHolderStyle = {
    thumbnail: {
        position: 'absolute',
        zIndex: 2,
        width: 60,
        height: 60,
        borderRadius: 60
    },
    thumbnailContainer: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center', borderRadius: 30, padding: 10 },
    imageTextStyle: {
        color: 'white',
        fontSize: 20,
        fontWeight: 'bold'
    }
}
