import React, {useState, useEffect} from 'react';
import {Alert, 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 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';

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 {
    profile: {website, biography, gender, snapchat, tiktok, university_class},
    cover,
  } = useSelector((state: RootState) => state.user);
  const {user} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : 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(avatar);
  }, []);

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

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

  const handleSubmit = async () => {
    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('smallProfilePicture', {
      uri: form.smallPic,
      name: 'small_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((_) => {
        setValidImage(false);
      });
  };


  if (!validImage && userXId === undefined && !loading) {
    return (
      <>
        <Avatar style={[styles.image, style]} uri={avatar} />
        <TouchableOpacity
          accessible={true}
          accessibilityLabel="ADD PROFILE PICTURE"
          onPress={() => goToGallerySmallPic()}>
          <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;
