import {RouteProp} from '@react-navigation/core';
import {useNavigation} from '@react-navigation/native';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import {
  Image,
  StyleSheet,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import {useFocusEffect} from '@react-navigation/native';
import {Button} from 'react-native-elements';
import Video from 'react-native-video';
import {MainStackParams} from 'src/routes';
import BackArrow from '../../assets/icons/back-arrow.svg';
import {CaptionScreenHeader, MomentTags} from '../../components';
import {TagFriendsFooter} from '../../components/moments';
import {TAGG_LIGHT_BLUE_2} from '../../constants';
import {MomentTagType} from '../../types';
import {
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  HeaderHeight,
  isIPhoneX,
  normalize,
} from '../../utils';

type TagFriendsScreenRouteProps = RouteProp<
  MainStackParams,
  'TagFriendsScreen'
>;
interface TagFriendsScreenProps {
  route: TagFriendsScreenRouteProps;
}
const TagFriendsScreen: React.FC<TagFriendsScreenProps> = ({route}) => {
  const {media, selectedTags} = route.params;
  const navigation = useNavigation();
  const imageRef = useRef(null);
  const [tags, setTags] = useState<MomentTagType[]>([]);
  const [imageWidth, setImageWidth] = useState<number>(0);
  const [imageHeight, setImageHeight] = useState<number>(0);

  // Calculate boundary (if any) for drag from bottom
  let bottomBound;
  if (SCREEN_HEIGHT / 2 - imageHeight / 2 < SCREEN_HEIGHT * 0.15) {
    if (SCREEN_HEIGHT / 2 - imageHeight / 2 < 0) {
      bottomBound = SCREEN_HEIGHT * 0.15;
    } else {
      bottomBound =
        SCREEN_HEIGHT * 0.15 - (SCREEN_HEIGHT / 2 - imageHeight / 2);
    }
  } else {
    bottomBound = 0;
  }

  /*
   * Update list of tagged users from route params
   */
  useEffect(() => {
    setTags(selectedTags ? selectedTags : []);
  }, [selectedTags]);

  /*
   * Hide Tab Bar
   */
  useFocusEffect(
    useCallback(() => {
      navigation.dangerouslyGetParent()?.setOptions({
        tabBarVisible: false,
      });
      return () => {
        navigation.dangerouslyGetParent()?.setOptions({
          tabBarVisible: true,
        });
      };
    }, [navigation]),
  );

  /*
   * Navigate back to Tag Users Screen, send selected users
   */
  const handleDone = () => {
    navigation.navigate('CaptionScreen', {
      ...route.params,
      selectedTags: tags,
    });
  };

  const setMediaDimensions = (width: number, height: number) => {
    const imageAspectRatio = width / height;
    const screenRatio = SCREEN_WIDTH / SCREEN_HEIGHT;

    // aspectRatio: >= 1 [Landscape] [1:1]
    if (imageAspectRatio >= screenRatio) {
      setImageWidth(SCREEN_WIDTH);
      setImageHeight(SCREEN_WIDTH / imageAspectRatio);
    }
    // aspectRatio: < 1 [Portrait]
    if (imageAspectRatio < screenRatio) {
      setImageHeight(SCREEN_HEIGHT);
      setImageWidth(SCREEN_HEIGHT * imageAspectRatio);
    }
  };

  /*
   * Calculating image width and height with respect to it's enclosing view's dimensions. Only works for images.
   */
  useEffect(() => {
    if (imageRef && imageRef.current && !media.isVideo) {
      Image.getSize(
        media.uri,
        (w, h) => {
          setMediaDimensions(w, h);
        },
        (err) => console.log(err),
      );
    }
  }, []);

  return (
    <View style={styles.contentContainer}>
      <View
        style={{
          position: 'absolute',
          paddingTop: SCREEN_HEIGHT / 2 - imageHeight / 2,
        }}>
        <TouchableWithoutFeedback
          onPress={() =>
            navigation.navigate('TagSelectionScreen', {
              selectedTags: tags,
            })
          }>
          {media.isVideo ? (
            <View
              style={{
                width: imageWidth,
                height: imageHeight,
                marginHorizontal: (SCREEN_WIDTH - imageWidth) / 2,
              }}
              ref={imageRef}>
              <Video
                style={{
                  width: imageWidth,
                  height: imageHeight,
                }}
                source={{uri: media.uri}}
                repeat={true}
                onLoad={(response) => {
                  const {width, height, orientation} = response.naturalSize;
                  // portrait will flip width and height
                  if (orientation === 'portrait') {
                    setMediaDimensions(height, width);
                  } else {
                    setMediaDimensions(width, height);
                  }
                }}
              />
            </View>
          ) : (
            <Image
              ref={imageRef}
              style={{
                width: imageWidth,
                height: imageHeight,
                marginHorizontal: (SCREEN_WIDTH - imageWidth) / 2,
              }}
              source={{uri: media.uri}}
            />
          )}
        </TouchableWithoutFeedback>
      </View>
      <TouchableOpacity
        onPress={() => {
          navigation.goBack();
        }}
        style={styles.backArrow}>
        <View style={styles.backArrowContainer}>
          <BackArrow
            height={normalize(18)}
            width={normalize(18)}
            color={'white'}
          />
        </View>
      </TouchableOpacity>
      {tags.length !== 0 && (
        <View style={styles.buttonContainer}>
          <Button
            title="Done"
            titleStyle={styles.shareButtonTitle}
            type="clear"
            buttonStyle={styles.button}
            onPress={handleDone}
          />
        </View>
      )}
      <View style={styles.captionContainer}>
        <CaptionScreenHeader
          style={styles.header}
          title={
            tags.length === 0
              ? 'Tap on photo to tag friends!'
              : 'Press and drag to move'
          }
        />
      </View>
      {tags.length !== 0 && (
        <MomentTags
          tags={tags}
          setTags={setTags}
          editing={true}
          imageRef={imageRef}
          deleteFromList={(user) =>
            setTags(tags.filter((tag) => tag.user.id !== user.id))
          }
          boundaries={{bottom: bottomBound}}
        />
      )}
      {tags.length !== 0 && (
        <View style={styles.footerContainer}>
          <TagFriendsFooter tags={tags} setTags={setTags} />
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  contentContainer: {
    backgroundColor: 'black',
    height: SCREEN_HEIGHT,
    alignContent: 'center',
  },
  backArrow: {
    marginLeft: '5%',
    marginTop: isIPhoneX() ? HeaderHeight : '10%',
    position: 'absolute',
    zIndex: 9999,
  },
  backArrowContainer: {
    flex: 1,
  },
  button: {
    zIndex: 9999,
  },
  buttonContainer: {
    position: 'absolute',
    marginTop: isIPhoneX() ? HeaderHeight : '10%',
    right: 0,
    marginRight: '5%',
  },
  captionContainer: {
    marginVertical: 20,
    marginTop: SCREEN_HEIGHT * 0.2,
    flexDirection: 'row',
    justifyContent: 'center',
    borderWidth: 4,
    borderColor: 'pink',
  },
  shareButtonTitle: {
    fontWeight: 'bold',
    color: TAGG_LIGHT_BLUE_2,
  },
  header: {},
  footerContainer: {
    marginTop: '3%',
    backgroundColor: 'black',
    padding: '5%',
    flexDirection: 'column',
    justifyContent: 'center',
    width: SCREEN_WIDTH,
    position: 'absolute',
    paddingBottom: 0,
    bottom: 0,
    height: SCREEN_HEIGHT * 0.15,
  },
});

export default TagFriendsScreen;
