import {useNavigation} from '@react-navigation/native';
import React from 'react';
import {
  Alert,
  StyleProp,
  StyleSheet,
  View,
  ViewProps,
  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 PlusIcon from '../../assets/icons/plus_icon-01.svg';
import UpIcon from '../../assets/icons/up_icon.svg';
import DownIcon from '../../assets/icons/down_icon.svg';
import DeleteIcon from '../../assets/icons/delete-logo.svg';
import BigPlusIcon from '../../assets/icons/plus_icon-02.svg';
import {TAGG_TEXT_LIGHT_BLUE} from '../../constants';
import {SCREEN_WIDTH} from '../../utils';
import ImagePicker from 'react-native-image-crop-picker';
import MomentTile from './MomentTile';
import {MomentType, ScreenType} from 'src/types';
import {useDispatch} from 'react-redux';

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 dispatch = useDispatch();

  const navigateToImagePicker = () => {
    ImagePicker.openPicker({
      smartAlbums: [
        'Favorites',
        'RecentlyAdded',
        'SelfPortraits',
        'Screenshots',
        'UserLibrary',
      ],
      width: 580,
      height: 580,
      cropping: true,
      cropperToolbarTitle: 'Upload a moment',
      mediaType: 'photo',
    })
      .then((picture) => {
        if ('path' in picture) {
          navigation.navigate('CaptionScreen', {
            screenType,
            title: title,
            image: picture,
          });
        }
      })
      .catch((err) => {
        if (err.code && err.code !== 'E_PICKER_CANCELLED') {
          Alert.alert('Unable to upload moment!');
        }
      });
  };

  return (
    <View style={[styles.container, externalStyles?.container]}>
      <View style={[styles.header, externalStyles?.header]}>
        <Text style={[styles.titleText, externalStyles?.titleText]}>
          {title}
        </Text>
        <View style={styles.flexer} />
        {!userXId ? (
          <>
            <PlusIcon
              width={21}
              height={21}
              onPress={() => navigateToImagePicker()}
              color={TAGG_TEXT_LIGHT_BLUE}
              style={{marginRight: 10}}
            />
            {showUpButton && move && (
              <UpIcon
                width={19}
                height={19}
                onPress={() => move('up', title)}
                color={TAGG_TEXT_LIGHT_BLUE}
                style={{marginRight: 10}}
              />
            )}
            {showDownButton && move && (
              <DownIcon
                width={19}
                height={19}
                onPress={() => move('down', title)}
                color={TAGG_TEXT_LIGHT_BLUE}
                style={{marginRight: 10}}
              />
            )}
            {shouldAllowDeletion && (
              <DeleteIcon
                onPress={() => handleMomentCategoryDelete(title)}
                width={19}
                height={19}
              />
            )}
          </>
        ) : (
          <React.Fragment />
        )}
      </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={() => navigateToImagePicker()}>
            <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: 16,
    fontWeight: 'bold',
    color: TAGG_TEXT_LIGHT_BLUE,
  },
  // titleContainer: {
  //   flex: 1,
  //   flexDirection: 'row',
  //   justifyContent: 'flex-end',
  // },
  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',
  },
});

export default Moment;
