import {useNavigation} from '@react-navigation/native';
import React from 'react';
import {StyleProp, StyleSheet, View, ViewStyle} from 'react-native';
import {Text} from 'react-native-animatable';
import {ScrollView, TouchableOpacity} from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
import DeleteIcon from '../../assets/icons/delete-logo.svg';
import DownIcon from '../../assets/icons/down_icon.svg';
import BigPlusIcon from '../../assets/icons/plus-icon-white.svg';
import PlusIcon from '../../assets/icons/plus-icon.svg';
import UpIcon from '../../assets/icons/up_icon.svg';
import {TAGG_LIGHT_BLUE} from '../../constants';
import {MomentType, ScreenType} from '../../types';
import {normalize, SCREEN_WIDTH} from '../../utils';
import MomentTile from './MomentTile';

interface MomentProps {
  title: string;
  images: MomentType[] | undefined;
  userXId: string | undefined;
  screenType: ScreenType;
  handleMomentCategoryDelete: (_: string) => void;
  shouldAllowDeletion: boolean;
  showUpButton: boolean;
  showDownButton: boolean;
  move?: (direction: 'up' | 'down', title: string) => void;
  externalStyles?: Record<string, StyleProp<ViewStyle>>;
}

const Moment: React.FC<MomentProps> = ({
  title,
  images,
  userXId,
  screenType,
  handleMomentCategoryDelete,
  shouldAllowDeletion,
  showUpButton,
  showDownButton,
  move,
  externalStyles,
}) => {
  const navigation = useNavigation();

  const navigateToCaptionScreenForVideo = (uri: string) => {
    const randHash = Math.random().toString(36).substring(7);
    navigation.navigate('CaptionScreen', {
      screenType,
      title,
      media: {
        filename: `poc_${randHash}.mov`,
        uri,
        isVideo: true,
      },
    });
  };
  /**
   * This function opens the ImagePicker, only lets you select video files,
   * formats the file extension, then makes a call to the server to get the presigned URL,
   * after which it makes a POST request to the returned URL to upload the file directly to S3.
   * params: none
   * @returns: none
   */
  const navigateToVideoPicker = () => {
    ImagePicker.openPicker({
      mediaType: 'video',
    })
      .then(async (vid) => {
        console.log(vid);
        if (vid.path) {
          navigateToCaptionScreenForVideo(vid.path);
        }
      })
      .catch((err) => {
        if (err.code && err.code !== 'E_PICKER_CANCELLED') {
          Alert.alert(ERROR_UPLOAD);
        }
      });
  };

  const navigateToImagePicker = () => {
    ImagePicker.openPicker({
      smartAlbums: [
        'Favorites',
        'RecentlyAdded',
        'SelfPortraits',
        'Screenshots',
        'UserLibrary',
      ],
      mediaType: 'any',
    })
      .then((picture) => {
        if (picture.path && picture.filename) {
          navigation.navigate('ZoomInCropper', {
            screenType,
            title,
            media: {
              filename: picture.filename,
              uri: picture.path,
              isVideo: false,
            },
          });
        }
      })
      .catch((err) => {
        if (err.code && err.code !== 'E_PICKER_CANCELLED') {
          Alert.alert(ERROR_UPLOAD);
        }
      });
  const navigateToCameraScreen = () => {
    navigation.navigate('CameraScreen', {
      title,
      screenType,
    });
  };

  return (
    <View style={[styles.container, externalStyles?.container]}>
      <View style={[styles.header, externalStyles?.header]}>
        <Text
          style={[styles.titleText, externalStyles?.titleText]}
          numberOfLines={2}>
          {title}
        </Text>
        <View style={styles.buttonsContainer}>
          {!userXId && (
            <View style={styles.row}>
              {showUpButton && move && (
                <UpIcon
                  width={19}
                  height={19}
                  onPress={() => move('up', title)}
                  color={TAGG_LIGHT_BLUE}
                  style={styles.horizontalMargin}
                />
              )}
              {showDownButton && move && (
                <DownIcon
                  width={19}
                  height={19}
                  onPress={() => move('down', title)}
                  color={TAGG_LIGHT_BLUE}
                  style={styles.horizontalMargin}
                />
              )}
            </View>
          )}
          {!userXId && (
            <View style={styles.row}>
              <PlusIcon
                width={23}
                height={23}
                onPress={() =>
                  Alert.alert('Video Upload', 'pick one', [
                    {
                      text: 'gallery',
                      onPress: navigateToVideoPicker,
                    },
                    {
                      text: 'camera (simulator will not work)',
                      onPress: () =>
                        ImagePicker.openCamera({
                          mediaType: 'video',
                        })
                          .then((vid) => {
                            console.log(vid);
                            if (vid.path) {
                              navigateToCaptionScreenForVideo(vid.path);
                            }
                          })
                          .catch((err) => console.error(err)),
                    },
                  ])
                }
                color={'black'}
                style={styles.horizontalMargin}
              />
              <PlusIcon
                width={23}
                height={23}
                onPress={() => navigateToCameraScreen()}
                color={TAGG_LIGHT_BLUE}
                style={styles.horizontalMargin}
              />
              {shouldAllowDeletion && (
                <DeleteIcon
                  onPress={() => handleMomentCategoryDelete(title)}
                  width={19}
                  height={19}
                  style={[styles.horizontalMargin, styles.deleButtonAdjustment]}
                />
              )}
            </View>
          )}
        </View>
      </View>
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        style={[styles.scrollContainer, externalStyles?.scrollContainer]}>
        {images &&
          images.map((imageObj: MomentType) => (
            <MomentTile
              key={imageObj.moment_id}
              moment={imageObj}
              userXId={userXId}
              screenType={screenType}
            />
          ))}
        {(images === undefined || images.length === 0) && !userXId && (
          <TouchableOpacity onPress={() => navigateToCameraScreen()}>
            <LinearGradient
              colors={['rgba(105, 141, 211, 1)', 'rgba(105, 141, 211, 0.3)']}>
              <View style={styles.defaultImage}>
                <BigPlusIcon width={24} height={24} />
                <Text style={styles.defaultImageText}>
                  Add a moment of your {title?.toLowerCase()}!
                </Text>
              </View>
            </LinearGradient>
          </TouchableOpacity>
        )}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#eee',
  },
  header: {
    flex: 1,
    padding: '3%',
    backgroundColor: 'white',
    flexDirection: 'row',
    alignItems: 'center',
  },
  titleText: {
    fontSize: normalize(16),
    fontWeight: 'bold',
    color: TAGG_LIGHT_BLUE,
    maxWidth: '70%',
  },
  flexer: {
    flex: 1,
  },
  scrollContainer: {
    height: SCREEN_WIDTH / 3.25,
    backgroundColor: '#eee',
  },
  defaultImage: {
    aspectRatio: 1,
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'column',
  },
  defaultImageText: {
    fontSize: 14,
    paddingTop: 10,
    color: 'white',
    fontWeight: 'bold',
    width: '80%',
    textAlign: 'center',
  },
  buttonsContainer: {
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'space-between',
    minWidth: 50,
    alignItems: 'center',
  },
  row: {flexDirection: 'row'},
  horizontalMargin: {marginHorizontal: 4},
  deleButtonAdjustment: {top: 2},
});

export default Moment;
