import {useNavigation} from '@react-navigation/native';
import React, {useEffect} from 'react';
import {Image, StyleSheet, Text, View, ViewProps} from 'react-native';
import {useDispatch, useStore} from 'react-redux';
import {getCommentsCount} from '../../services';
import {RootState} from '../../store/rootReducer';
import {ScreenType, UserType} from '../../types';
import {
  getTimePosted,
  navigateToProfile,
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} from '../../utils';
import {renderTextWithMentions} from '../../utils/comments';
import {CommentsCount} from '../comments';

interface MomentPostContentProps extends ViewProps {
  screenType: ScreenType;
  momentId: string;
  caption: string;
  pathHash: string;
  dateTime: string;
}
const MomentPostContent: React.FC<MomentPostContentProps> = ({
  screenType,
  momentId,
  caption,
  pathHash,
  dateTime,
  style,
}) => {
  const [elapsedTime, setElapsedTime] = React.useState<string>();
  const [comments_count, setCommentsCount] = React.useState('');
  const state: RootState = useStore().getState();
  const navigation = useNavigation();
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchCommentsCount = async () => {
      const count = await getCommentsCount(momentId, false);
      setCommentsCount(count);
    };
    setElapsedTime(getTimePosted(dateTime));
    fetchCommentsCount();
  }, [dateTime, momentId]);

  return (
    <View style={[styles.container, style]}>
      <Image
        style={styles.image}
        source={{uri: pathHash}}
        resizeMode={'cover'}
      />
      <View style={styles.footerContainer}>
        <CommentsCount
          commentsCount={comments_count}
          momentId={momentId}
          screenType={screenType}
        />
        <Text style={styles.text}>{elapsedTime}</Text>
      </View>
      {renderTextWithMentions({
        value: caption,
        styles: styles.captionText,
        onPress: (user: UserType) =>
          navigateToProfile(state, dispatch, navigation, screenType, user),
      })}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    height: SCREEN_HEIGHT,
  },
  image: {
    width: SCREEN_WIDTH,
    aspectRatio: 1,
    marginBottom: '3%',
  },
  footerContainer: {
    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',
  },
});
export default MomentPostContent;
