import React, { useState, useEffect } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { Avatar, Card, Title, Paragraph } from 'react-native-paper';
import API from './../API.js';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png";

const storeName = async (key, value) => {
    try {
        const jsonValue = JSON.stringify(value)
        await AsyncStorage.setItem('Name_' + key, jsonValue)
    } catch (e) {
    }
}

const getName = async (key) => {
    try {
        const value = await AsyncStorage.getItem('Name_' + key)
        if (value !== null) {
            return JSON.parse(value);
        }
    } catch (e) {
        return []
    }
}

let CourseCard = ({ profileid, hideIcon, profileObj, twoCols }) => {
    let [profile, setProfile] = useState(profileObj || {});
    const safeProfile = profile || {};
    const safeProfileInfo = safeProfile.profile || {};
    const safeProfileObj = profileObj || {};
    const safeProfileObjInfo = safeProfileObj.profile || {};
    const navigation = useNavigation();

    useEffect(() => {
        let subscribed = true;
        const getData = async () => {
            if (safeProfileObj._id) return 0;
            let cacheProfile = await getName(profileid);
            if (cacheProfile && cacheProfile.profile) setProfile(cacheProfile);
            let p = await API.getUserProfile(profileid).catch(() => { return {} });
            if(subscribed) setProfile(p);
            storeName(profileid, p);
        }
        getData();
        return () => {
            subscribed = false;
        }
    }, [profileid]);

    let icon = safeProfile._id ? (!safeProfile.isGroup ? "person-outline" : "group") : '';
    icon = icon === "person-outline" && safeProfile.subscription && safeProfile.subscription > (new Date() - 0) ? "assignment-ind" : icon;
    icon = icon === "group" && safeProfile.isCourse ? "subscriptions" : icon;
    let photoUrl = safeProfile.data && safeProfile.data.profileImg ? safeProfile.data.profileImg : DefaultPhoto;

    const onPress = () => {
        return navigation.navigate('Profile', { profileid: safeProfile._id })
    }

    return (
        <Card style={twoCols ? styles.contentCols : styles.content}>
            <Card.Content>
                <Title onPress={onPress} numberOfLines={2}>
                    <Text style={{ paddingTop: 10 }}>
                        {!hideIcon ? <Icon name={icon} size={18} /> : <></>}
                    </Text>
                    <Text>
                        {safeProfileInfo.firstName} {safeProfileInfo.lastName}
                    </Text>
                </Title>
                <Paragraph numberOfLines={2}>
                    {safeProfileObjInfo.description ? safeProfileObjInfo.description : "We are working on this course description, soon to come!"}
                </Paragraph>
                {safeProfile.data ? 
                <View style={{flexDirection: "row", marginTop:5}}>
                    <Avatar.Image size={64} source={{ uri: photoUrl }} />
                    <View>
                        <Text>By: {safeProfile.data.author ? safeProfile.data.author : 'Working on this'}</Text>
                        <Text>
                            <Icon name="date-range" />
                            {safeProfile.data.year ? safeProfile.data.year : 'XXXX'}
                        </Text>
                        <Text>
                            <Icon name="timer" />
                            {safeProfile.data.duration ? safeProfile.data.duration : '??'}
                        </Text>
                        <Text>
                            <Icon name="language" />
                            {safeProfile.data.language}
                        </Text>
                    </View>
                </View>
                : <></>
                }
            </Card.Content>
        </Card>

    );
}

export default React.memo(CourseCard);

const styles = StyleSheet.create({
    content: {
        margin: 4,
        width: 250,
    },
    contentCols: {
        margin: 4,
        width: "48%",
    },
    centerItems: {
        justifyContent: 'center',
        alignItems: 'center',
    }
});
