import React, {useState, useEffect} from 'react';
import {
  Image,
  StyleSheet,
  View,
  TouchableOpacity,
  Text,
  ImageBackground,
} from 'react-native';
import {COVER_HEIGHT, IMAGE_WIDTH} from '../../constants';
import {ScreenType} from '../../types';
import GreyPurplePlus from '../../assets/icons/grey-purple-plus.svg';
import {useDispatch, useSelector} from 'react-redux';
import {loadUserData, resetHeaderAndProfileImage} from '../../store/actions';
import {RootState} from '../../store/rootreducer';
import {normalize, patchProfile, validateImageLink} from '../../utils';

interface CoverProps {
  userXId: string | undefined;
  screenType: ScreenType;
}
const Cover: React.FC<CoverProps> = ({userXId, screenType}) => {
  const dispatch = useDispatch();
  const {cover, user} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.user,
  );

  const [needsUpdate, setNeedsUpdate] = useState(false);
  const [loading, setLoading] = useState(false);
  const [validImage, setValidImage] = useState<boolean>(true);

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

  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('header', user.userId);
    setLoading(true);
    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 (
      <View style={[styles.container]}>
        <ImageBackground
          style={styles.image}
          defaultSource={require('../../assets/images/cover-placeholder.png')}
          source={{uri: cover, cache: 'reload'}}>
          <TouchableOpacity
            accessible={true}
            accessibilityLabel="ADD HEADER PICTURE"
            onPress={() => handleNewImage()}>
            <GreyPurplePlus style={styles.plus} />
            <Text style={styles.text}>Add Picture</Text>
          </TouchableOpacity>
        </ImageBackground>
      </View>
    );
  } else {
    return (
      <View style={styles.container}>
        <Image
          style={styles.image}
          defaultSource={require('../../assets/images/cover-placeholder.png')}
          source={{uri: cover, cache: 'reload'}}
        />
      </View>
    );
  }
};

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
  },
  image: {
    width: IMAGE_WIDTH,
    height: COVER_HEIGHT,
  },
  plus: {
    position: 'absolute',
    top: 75,
    right: 125,
  },
  text: {
    color: 'white',
    position: 'absolute',
    fontSize: normalize(16),
    top: 80,
    right: 20,
  },
  touch: {
    flex: 1,
  },
});
export default Cover;
