import React, {useState, useEffect} from 'react';
import {StyleSheet, TouchableOpacity} from 'react-native';
import {RootState} from '../../store/rootreducer';
import {ScreenType} from '../../types';
import {Avatar} from '../common';
import {useDispatch, useSelector} from 'react-redux';
import {loadUserData, resetHeaderAndProfileImage} from '../../store/actions';
import PurplePlus from '../../assets/icons/purple-plus.svg';
import {patchProfile, validateImageLink} from '../../utils';

const PROFILE_DIM = 100;

interface TaggAvatarProps {
  style?: object;
  userXId: string | undefined;
  screenType: ScreenType;
}
const TaggAvatar: React.FC<TaggAvatarProps> = ({
  style,
  screenType,
  userXId,
}) => {
  const {avatar} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.user,
  );
  const dispatch = useDispatch();
  const [needsUpdate, setNeedsUpdate] = useState(false);
  const [loading, setLoading] = useState(false);
  const [validImage, setValidImage] = useState<boolean>(true);
  const {user} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.user,
  );

  useEffect(() => {
    checkAvatar(avatar);
  }, []);

  useEffect(() => {
    if (needsUpdate) {
      const userId = user.userId;
      const username = user.username;
      dispatch(resetHeaderAndProfileImage());
      dispatch(loadUserData({userId, username}));
    }
  }, [dispatch, needsUpdate]);

  const handleNewImage = async () => {
    setLoading(true);
    const result = await patchProfile('profile', user.userId);
    if (result) {
      setNeedsUpdate(true);
    } else {
      setLoading(false);
    }
  };

  const checkAvatar = async (url: string | undefined) => {
    const valid = await validateImageLink(url);
    if (valid !== validImage) {
      setValidImage(valid);
    }
  };

  if (!validImage && userXId === undefined && !loading) {
    return (
      <>
        <Avatar style={[styles.image, style]} uri={avatar} />
        <TouchableOpacity
          accessible={true}
          accessibilityLabel="ADD PROFILE PICTURE"
          onPress={() => handleNewImage()}>
          <PurplePlus style={styles.plus} />
        </TouchableOpacity>
      </>
    );
  } else {
    return <Avatar style={[styles.image, style]} uri={avatar} />;
  }
};

const styles = StyleSheet.create({
  image: {
    height: PROFILE_DIM,
    width: PROFILE_DIM,
    borderRadius: PROFILE_DIM / 2,
  },
  plus: {
    position: 'absolute',
    bottom: 35,
    right: 0,
  },
});

export default TaggAvatar;
