import React, {useState, useEffect} from 'react';
import {
  Alert,
  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 ImagePicker from 'react-native-image-crop-picker';
import {
  ERROR_UPLOAD_LARGE_PROFILE_PIC,
  ERROR_UPLOAD_SMALL_PROFILE_PIC,
} from '../../constants/strings';
import {patchEditProfile} from '../../services';
import {useDispatch, useSelector} from 'react-redux';
import {loadUserData, resetHeaderAndProfileImage} from '../../store/actions';
import {RootState} from '../../store/rootreducer';

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);

  const {
    profile: {website, biography, gender, snapchat, tiktok, university_class},
    avatar,
  } = useSelector((state: RootState) => state.user);

  const isCustomGender =
    gender !== '' && gender !== 'female' && gender !== 'male';

  const [form, setForm] = React.useState({
    largePic: cover ? cover : '',
    smallPic: avatar ? avatar : '',
    website: website ? website : '',
    bio: biography ? biography : '',
    gender: isCustomGender ? 'custom' : gender,
    customGenderText: isCustomGender ? gender : '',
    snapchat: snapchat,
    tiktok: tiktok,
    isValidWebsite: true,
    isValidBio: true,
    isValidGender: true,
    isValidSnapchat: true,
    isValidTiktok: true,
    attemptedSubmit: false,
    classYear: university_class,
  });

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

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

  const goToGalleryLargePic = () => {
    ImagePicker.openPicker({
      smartAlbums: [
        'Favorites',
        'RecentlyAdded',
        'SelfPortraits',
        'Screenshots',
        'UserLibrary',
      ],
      width: 580,
      height: 580,
      cropping: true,
      cropperToolbarTitle: 'Select Header',
      mediaType: 'photo',
    }).then((picture) => {
      if ('path' in picture) {
        setForm({
          ...form,
          largePic: picture.path,
        });
        handleSubmit();
      }
    });
  };

  const handleSubmit = () => {
    if (!form.largePic) {
      Alert.alert(ERROR_UPLOAD_LARGE_PROFILE_PIC);
      return;
    }
    if (!form.smallPic) {
      Alert.alert(ERROR_UPLOAD_SMALL_PROFILE_PIC);
      return;
    }

    const request = new FormData();
    request.append('largeProfilePicture', {
      uri: form.largePic,
      name: 'large_profile_pic.jpg',
      type: 'image/jpg',
    });

    setLoading(true);
    patchEditProfile(request, user.userId)
      .then((_) => {
        setNeedsUpdate(true);
        setValidImage(true);
        // navigation.pop();
      })
      .catch((error) => {
        Alert.alert(error);
      });
    setLoading(false);
  };

  const checkAvatar = (url: string | undefined) => {
    if (!url) {
      setValidImage(false);
    }
    fetch(url)
      .then((res) => {
        if (res.status === 200) {
          setValidImage(true);
        } else {
          setValidImage(false);
        }
      })
      .catch((err) => {
        setValidImage(false);
      });
  };

  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 PROFILE PICTURE"
              onPress={() => goToGalleryLargePic()}>
              <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: 18,
    top: 80,
    right: 20,
  },
  touch: {
    flex: 1,
  },
});
export default Cover;
