import React from 'react';
import {StyleSheet, View, Image, Alert, Text, Platform} from 'react-native';
import {Button} from 'react-native-elements';
import {SearchBackground, TabsGradient, TaggBigInput} from '../../components';
import {SCREEN_HEIGHT, SCREEN_WIDTH, StatusBarHeight} from '../../utils';
import AsyncStorage from '@react-native-community/async-storage';
import {RouteProp} from '@react-navigation/native';
import {ProfileStackParams} from 'src/routes';
import {StackNavigationProp} from '@react-navigation/stack';
import {CaptionScreenHeader} from '../../components/';
import {MOMENTS_ENDPOINT} from '../../constants';
import {AuthContext} from '../../routes/authentication';
/**
 * Upload Screen to allow users to upload posts to Tagg
 */
type CaptionScreenRouteProp = RouteProp<ProfileStackParams, 'CaptionScreen'>;
type CaptionScreenNavigationProp = StackNavigationProp<
  ProfileStackParams,
  'CaptionScreen'
>;
interface CaptionScreenProps {
  route: CaptionScreenRouteProp;
  navigation: CaptionScreenNavigationProp;
}

const CaptionScreen: React.FC<CaptionScreenProps> = ({route, navigation}) => {
  const {title, image} = route.params;
  const {
    user: {userId},
    updateMoments,
  } = React.useContext(AuthContext);
  const [caption, setCaption] = React.useState('');

  const handleCaptionUpdate = (caption: string) => {
    setCaption(caption);
  };

  const checkImageUploadStatus = (statusMap: object) => {
    for (let [key, value] of Object.entries(statusMap)) {
      if (value != 'Success') {
        return false;
      }
    }
    return true;
  };

  const handleShare = async () => {
    try {
      const request = new FormData();
      const uri = image.path;
      var fileName = image.filename;

      //Manipulating filename to end with .jpg instead of .heic
      if (fileName.endsWith('.heic') || fileName.endsWith('.HEIC')) {
        fileName = fileName.split('.')[0] + '.jpg';
      }
      request.append('image', {
        uri: uri,
        name: fileName,
        type: 'image/jpg',
      });
      request.append('moment', title);
      request.append('user_id', userId);
      request.append('captions', JSON.stringify({image: caption}));

      const token = await AsyncStorage.getItem('token');
      let response = await fetch(MOMENTS_ENDPOINT, {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Token ' + token,
        },
        body: request,
      });
      let statusCode = response.status;
      let data = await response.json();
      if (statusCode === 200 && checkImageUploadStatus(data)) {
        Alert.alert('The picture was uploaded successfully!');
        updateMoments(true);
        navigation.navigate('Profile', {isProfileView: false});
      } else {
        Alert.alert('An error occured while uploading. Please try again!');
      }
    } catch (err) {
      Alert.alert('An error occured during authenticaion. Please login again!');
    }
  };

  return (
    <SearchBackground>
      <View style={styles.contentContainer}>
        <View style={styles.buttonsContainer}>
          <Button
            title="Cancel"
            buttonStyle={styles.button}
            onPress={() => {
              navigation.navigate('Profile', {isProfileView: false});
            }}
          />
          <Button
            title="Share"
            titleStyle={styles.shareButtonTitle}
            buttonStyle={styles.button}
            onPress={handleShare}
          />
        </View>
        <CaptionScreenHeader style={styles.header} {...{title: title}} />
        <Image
          style={styles.image}
          source={{uri: image.path}}
          resizeMode={'cover'}
        />
        <TaggBigInput
          style={styles.text}
          multiline
          placeholder="Write something....."
          placeholderTextColor="gray"
          onChangeText={handleCaptionUpdate}
        />
      </View>
      <TabsGradient />
    </SearchBackground>
  );
};
const styles = StyleSheet.create({
  contentContainer: {
    paddingTop: StatusBarHeight,
    paddingBottom: SCREEN_HEIGHT,
  },
  buttonsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: '5%',
    marginRight: '5%',
  },
  button: {
    backgroundColor: 'transparent',
  },
  shareButtonTitle: {
    fontWeight: 'bold',
    color: '#6EE7E7',
  },
  header: {
    marginVertical: 20,
  },
  image: {
    position: 'relative',
    width: SCREEN_WIDTH,
    aspectRatio: 1,
    marginBottom: '3%',
  },
  text: {
    position: 'relative',
    backgroundColor: 'white',
    width: '100%',
    paddingLeft: '2%',
    paddingRight: '2%',
    paddingBottom: '1%',
    paddingTop: '1%',
    height: 60,
  },
});

export default CaptionScreen;
