import AsyncStorage from '@react-native-community/async-storage';
import {BlurView} from '@react-native-community/blur';
import {RouteProp} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import React, {useEffect, useState} from 'react';
import {Alert, Image, StyleSheet, View} from 'react-native';
import {Button} from 'react-native-elements';
import {TouchableOpacity} from 'react-native-gesture-handler';
import Animated from 'react-native-reanimated';
import {useDispatch, useSelector} from 'react-redux';
import {ProfileStackParams} from 'src/routes/profile/ProfileStack';
import {
  CaptionScreenHeader,
  CommentsCount,
  MomentMoreInfoDrawer,
} from '../../components';
import {getMomentCommentsCount} from '../../services';
import {sendReport} from '../../services/ReportingService';
import {loadUserMoments, logout} from '../../store/actions';
import {DUMMY_USERNAME} from '../../store/initialStates';
import {RootState} from '../../store/rootreducer';
import {
  getTimePosted,
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
  StatusBarHeight,
} from '../../utils';

/**
 * Individual moment view opened when user clicks on a moment tile
 */
type IndividualMomentRouteProp = RouteProp<
  ProfileStackParams,
  'IndividualMoment'
>;
type IndividualMomentNavigationProp = StackNavigationProp<
  ProfileStackParams,
  'IndividualMoment'
>;
interface IndividualMomentProps {
  route: IndividualMomentRouteProp;
  navigation: IndividualMomentNavigationProp;
}

const IndividualMoment: React.FC<IndividualMomentProps> = ({
  route,
  navigation,
}) => {
  const {
    moment_category,
    path_hash,
    date_time,
    moment_id,
  } = route.params.moment;
  const {userXId, screenType} = route.params;

  const {
    user: {userId: loggedInUserId, username: loggedInUsername},
  } = useSelector((state: RootState) => state.user);

  const {
    user: {username},
  } = userXId
    ? useSelector((state: RootState) => state.userX[screenType][userXId])
    : {user: {username: DUMMY_USERNAME}};

  const isOwnProfile = username === loggedInUsername;
  const [elapsedTime, setElapsedTime] = React.useState<string>();
  const [comments_count, setCommentsCount] = React.useState('');
  const [isReporting, setIsReporting] = React.useState(false);
  const dispatch = useDispatch();
  const [drawerVisible, setDrawerVisible] = useState(false);

  useEffect(() => {
    const timePeriod = async () => {
      setElapsedTime(getTimePosted(date_time));
    };

    const loadComments = async () => {
      const token = await AsyncStorage.getItem('token');
      if (!token) {
        dispatch(logout());
        return;
      }
      getMomentCommentsCount(moment_id, setCommentsCount, token);
    };

    timePeriod();
    loadComments();
  }, [date_time, dispatch, loggedInUserId, moment_id]);

  const sendReportAlert = async () => {
    const token = await AsyncStorage.getItem('token');
    setIsReporting(true);
    Alert.alert(
      'Report Issue',
      undefined,
      [
        {
          text: 'Mark as inappropriate',
          onPress: () =>
            sendReport(
              moment_id,
              'Mark as inappropriate',
              token ? token : '',
              setIsReporting,
            ),
        },
        {
          text: 'Cancel',
          onPress: () => setIsReporting(false),
          style: 'cancel',
        },
        {
          text: 'Mark as abusive',
          onPress: () =>
            sendReport(
              moment_id,
              'Mark as abusive',
              token ? token : '',
              setIsReporting,
            ),
        },
      ],
      {cancelable: false},
    );
  };

  return (
    <BlurView
      blurType="light"
      blurAmount={10}
      reducedTransparencyFallbackColor="white"
      style={styles.contentContainer}>
      <View style={styles.buttonsContainer}>
        <Button
          title="Close"
          buttonStyle={styles.button}
          onPress={() => {
            navigation.pop();
          }}
        />
        {!userXId && (
          <MomentMoreInfoDrawer
            isOpen={drawerVisible}
            setIsOpen={setDrawerVisible}
            momentId={moment_id}
            dismissScreenAndUpdate={() => {
              dispatch(loadUserMoments(loggedInUserId));
              navigation.pop();
            }}
          />
        )}
      </View>
      <CaptionScreenHeader
        style={styles.header}
        {...{title: moment_category}}
      />
      <Image
        style={styles.image}
        source={{uri: path_hash}}
        resizeMode={'cover'}
      />

      <View style={styles.bodyContainer}>
        <CommentsCount
          comments_count={comments_count}
          moment_id={moment_id}
          screenType={screenType}
        />
        <Animated.Text style={styles.text}>{elapsedTime}</Animated.Text>
      </View>
      <Animated.Text style={styles.captionText}>
        {route.params.moment.caption}
      </Animated.Text>
      {userXId && !isOwnProfile && !isReporting && (
        <TouchableOpacity onPress={sendReportAlert}>
          <Animated.Text style={styles.reportIssue}>
            {'Report an issue'}
          </Animated.Text>
        </TouchableOpacity>
      )}
    </BlurView>
  );
};
const styles = StyleSheet.create({
  contentContainer: {
    width: SCREEN_WIDTH,
    paddingTop: StatusBarHeight,
    height: SCREEN_HEIGHT,
    flex: 2,
    flexDirection: 'column',
    paddingBottom: 0,
  },
  buttonsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: '3%',
    marginRight: '3%',
  },
  button: {
    backgroundColor: 'transparent',
  },
  shareButtonTitle: {
    fontWeight: 'bold',
    color: '#6EE7E7',
  },
  header: {
    marginVertical: 20,
  },
  image: {
    position: 'relative',
    width: SCREEN_WIDTH,
    aspectRatio: 1,
    marginBottom: '3%',
  },
  bodyContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: '7%',
    marginRight: '5%',
    marginBottom: '2%',
  },
  text: {
    position: 'relative',
    paddingBottom: '1%',
    paddingTop: '1%',
    marginLeft: '7%',
    marginRight: '2%',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  captionText: {
    position: 'relative',
    paddingBottom: '34%',
    paddingTop: '1%',
    marginLeft: '5%',
    marginRight: '5%',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  reportIssue: {
    position: 'relative',
    color: 'white',
    textAlign: 'center',
    textDecorationLine: 'underline',
  },
});

export default IndividualMoment;
