import {RouteProp} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import React from 'react';
import {
  Image,
  Keyboard,
  KeyboardAvoidingView,
  Platform,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import {Button} from 'react-native-elements';
import {useDispatch, useSelector} from 'react-redux';
import {MainStackParams} from 'src/routes';
import {SearchBackground, TaggBigInput} from '../../components';
import {CaptionScreenHeader} from '../../components/';
import {postMoment} from '../../services';
import {
  loadUserMoments,
  updateProfileCompletionStage,
} from '../../store/actions';
import {RootState} from '../../store/rootReducer';
import {SCREEN_WIDTH, StatusBarHeight} from '../../utils';

/**
 * Upload Screen to allow users to upload posts to Tagg
 */
type CaptionScreenRouteProp = RouteProp<MainStackParams, 'CaptionScreen'>;
type CaptionScreenNavigationProp = StackNavigationProp<
  MainStackParams,
  'CaptionScreen'
>;
interface CaptionScreenProps {
  route: CaptionScreenRouteProp;
  navigation: CaptionScreenNavigationProp;
}

const CaptionScreen: React.FC<CaptionScreenProps> = ({route, navigation}) => {
  const {title, image, screenType} = route.params;
  const {
    user: {userId},
  } = useSelector((state: RootState) => state.user);
  const dispatch = useDispatch();
  const [caption, setCaption] = React.useState('');

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

  const navigateToProfile = () => {
    //Since the logged In User is navigating to own profile, useXId is not required
    navigation.navigate('Profile', {
      screenType,
      userXId: undefined,
    });
  };

  const handleShare = async () => {
    try {
      const data = await postMoment(
        image.filename,
        image.path,
        caption,
        title,
        userId,
      );
      if (data) {
        dispatch(loadUserMoments(userId));
        dispatch(updateProfileCompletionStage(data));
        navigateToProfile();
      }
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <SearchBackground>
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
          style={{flex: 1}}>
          <View style={styles.contentContainer}>
            <View style={styles.buttonsContainer}>
              <Button
                title="Cancel"
                buttonStyle={styles.button}
                onPress={() => navigateToProfile()}
              />
              <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>
        </KeyboardAvoidingView>
      </TouchableWithoutFeedback>
    </SearchBackground>
  );
};
const styles = StyleSheet.create({
  contentContainer: {
    paddingTop: StatusBarHeight,
    justifyContent: 'flex-end',
  },
  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;
