import {useNavigation} from '@react-navigation/native';
import React, {useEffect, useState} from 'react';
import {
  Alert,
  Image,
  ImageBackground,
  StatusBar,
  StyleSheet,
} from 'react-native';
import {Text} from 'react-native-animatable';
import {TouchableOpacity} from 'react-native-gesture-handler';
import ImagePicker from 'react-native-image-crop-picker';
import {SafeAreaView} from 'react-native-safe-area-context';
import {useDispatch, useSelector} from 'react-redux';
import {TaggSquareButton} from '../../components';
import TaggLoadingIndicator from '../../components/common/TaggLoadingIndicator';
import {SP_HEIGHT, SP_WIDTH} from '../../constants';
import {ERROR_UPLOAD, SUCCESS_PIC_UPLOAD} from '../../constants/strings';
import {
  getSuggestedPeopleProfile,
  sendSuggestedPeoplePhoto,
} from '../../services';
import {uploadedSuggestedPeoplePhoto} from '../../store/actions';
import {RootState} from '../../store/rootReducer';
import {normalize, SCREEN_HEIGHT, SCREEN_WIDTH} from '../../utils';

const SuggestedPeopleUploadPictureScreen: React.FC = ({route}) => {
  const {goTo} = route.params;
  const [image, setImage] = useState<string | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const {userId: loggedInUserId} = useSelector(
    (state: RootState) => state.user.user,
  );

  useEffect(() => {
    const loadData = async () => {
      const response = await getSuggestedPeopleProfile(loggedInUserId);
      if (response) {
        setImage(response.suggested_people_url);
      }
    };
    // if we're in edit SP, attempt to load current sp image
    if (goTo === 'Profile') {
      loadData();
    }
  }, []);

  const openImagePicker = () => {
    ImagePicker.openPicker({
      smartAlbums: [
        'Favorites',
        'RecentlyAdded',
        'SelfPortraits',
        'Screenshots',
        'UserLibrary',
      ],
      width: SP_WIDTH,
      height: SP_HEIGHT,
      cropping: true,
      cropperToolbarTitle: 'Select Photo',
      mediaType: 'photo',
    })
      .then((picture) => {
        if ('path' in picture) {
          setImage(picture.path);
        }
      })
      .catch((_) => {});
  };

  const uploadImage = async () => {
    setLoading(true);
    if (image) {
      const success = await sendSuggestedPeoplePhoto(image);
      if (success) {
        dispatch(uploadedSuggestedPeoplePhoto(image));
        if (goTo !== 'Profile') {
          navigation.push('BadgeSelection');
        }
      } else {
        Alert.alert(ERROR_UPLOAD);
      }
    }
    setLoading(false);

    // Navigated back to Profile if user is editing their Suggested People Picture
    if (goTo === 'Profile') {
      navigation.goBack();
      setTimeout(() => {
        Alert.alert(SUCCESS_PIC_UPLOAD);
      }, 500);
    }
  };

  return (
    <>
      {loading && <TaggLoadingIndicator fullscreen />}
      <StatusBar barStyle={'light-content'} />
      <SafeAreaView style={styles.container}>
        <Text style={styles.title}>PHOTO</Text>
        {image ? (
          <Text style={styles.body}>Tap again to choose another photo</Text>
        ) : (
          <Text style={styles.body}>
            Upload a photo, this is what other users will see
          </Text>
        )}
        {image ? (
          <TouchableOpacity onPress={openImagePicker}>
            <ImageBackground
              source={{uri: image}}
              style={[styles.imageContainer, styles.overlay]}
              borderRadius={30}>
              <Image
                style={styles.overlay}
                source={require('../../assets/images/suggested-people-preview-silhouette.png')}
              />
            </ImageBackground>
          </TouchableOpacity>
        ) : (
          <TouchableOpacity onPress={openImagePicker}>
            <ImageBackground
              source={require('../../assets/images/suggested-people-preview-silhouette.png')}
              style={[styles.imageContainer, styles.overlay]}>
              <Image
                style={styles.images}
                source={require('../../assets/images/images.png')}
              />
              <Text style={styles.body}>Upload Photo</Text>
            </ImageBackground>
          </TouchableOpacity>
        )}
        {image && (
          <TaggSquareButton
            onPress={uploadImage}
            title={'Done'}
            buttonStyle={'normal'}
            buttonColor={'purple'}
            labelColor={'white'}
            style={styles.buttonStyle}
            labelStyle={styles.buttonLabel}
          />
        )}
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    backgroundColor: '#878787',
    alignItems: 'center',
  },
  title: {
    marginTop: '5%',
    fontSize: normalize(25),
    lineHeight: normalize(30),
    fontWeight: '600',
    color: 'white',
  },
  body: {
    fontSize: normalize(15),
    lineHeight: normalize(18),
    textAlign: 'center',
    fontWeight: '600',
    color: 'white',
    marginTop: '5%',
    width: SCREEN_WIDTH * 0.7,
  },
  buttonLabel: {
    fontWeight: '600',
    fontSize: normalize(15),
  },
  buttonStyle: {
    width: '40%',
  },
  imageContainer: {
    marginTop: '10%',
    backgroundColor: 'black',
    borderRadius: 30,
    alignItems: 'center',
  },
  overlay: {
    height: SCREEN_HEIGHT * 0.6,
    aspectRatio: SP_WIDTH / SP_HEIGHT,
  },
  images: {
    width: normalize(100),
    height: normalize(100),
    marginTop: '30%',
    marginBottom: '10%',
  },
});
export default SuggestedPeopleUploadPictureScreen;
