import React, {useEffect, useRef, useState} from 'react';
import {StyleSheet} from 'react-native';
import {FlatList} from 'react-native-gesture-handler';
import {useDispatch, useSelector} from 'react-redux';
import {CommentTile} from '.';
import {getComments} from '../../services';
import {RootState} from '../../store/rootReducer';
import {CommentType, ScreenType, TypeOfComment} from '../../types';
import {SCREEN_HEIGHT} from '../../utils';
export type CommentsContainerProps = {
  screenType: ScreenType;
  //objectId can be either moment_id or comment_id
  objectId: string;
  commentId?: string;
  setCommentsLength?: (count: number) => void;
  newCommentsAvailable: boolean;
  setNewCommentsAvailable: (value: boolean) => void;
  typeOfComment: TypeOfComment;
  setCommentObjectInFocus?: (comment: CommentType | undefined) => void;
  commentObjectInFocus?: CommentType;
};

/**
 * Comments Container to be used for both comments and replies
 */

const CommentsContainer: React.FC<CommentsContainerProps> = ({
  screenType,
  objectId,
  setCommentsLength,
  newCommentsAvailable,
  setNewCommentsAvailable,
  typeOfComment,
  setCommentObjectInFocus,
  commentObjectInFocus,
  commentId,
}) => {
  const {username: loggedInUsername} = useSelector(
    (state: RootState) => state.user.user,
  );
  const [commentsList, setCommentsList] = useState<CommentType[]>([]);
  const dispatch = useDispatch();
  const ref = useRef<FlatList<CommentType>>(null);
  const [initialIndex, setInitialIndex] = useState<number>(0);

  useEffect(() => {
    //Scroll only if a new comment and not a reply was posted
    const shouldScroll = () =>
      (typeOfComment === 'Comment' && !commentObjectInFocus) ||
      typeOfComment === 'Thread';
    const loadComments = async () => {
      const comments = await getComments(objectId, typeOfComment === 'Thread');
      setCommentsList(comments);
      if (setCommentsLength) {
        setCommentsLength(comments.length);
      }
      setNewCommentsAvailable(false);
    };
    if (newCommentsAvailable) {
      loadComments();
      if (shouldScroll()) {
        if (commentId) {
          const index = commentsList.findIndex(
            (item) => item.comment_id === commentId,
          );
          setInitialIndex(index);
        } else {
          setTimeout(() => {
            ref.current?.scrollToEnd({animated: true});
          }, 500);
        }
      }
    }
  }, [
    dispatch,
    objectId,
    newCommentsAvailable,
    setNewCommentsAvailable,
    setCommentsLength,
    typeOfComment,
    commentObjectInFocus,
    commentId,
    commentsList,
  ]);

  const ITEM_HEIGHT = SCREEN_HEIGHT / 7.5;

  const renderComment = ({item}: {item: CommentType}) => (
    <CommentTile
      key={item.comment_id}
      comment_object={item}
      screenType={screenType}
      typeOfComment={typeOfComment}
      setCommentObjectInFocus={setCommentObjectInFocus}
      newCommentsAvailable={newCommentsAvailable}
      setNewCommentsAvailable={setNewCommentsAvailable}
      canDelete={item.commenter.username === loggedInUsername}
    />
  );

  return (
    <FlatList
      data={commentsList}
      ref={ref}
      keyExtractor={(item, index) => index.toString()}
      decelerationRate={'fast'}
      snapToAlignment={'start'}
      snapToInterval={ITEM_HEIGHT}
      renderItem={renderComment}
      showsVerticalScrollIndicator={false}
      initialScrollIndex={initialIndex}
      contentContainerStyle={styles.scrollViewContent}
      getItemLayout={(data, index) => ({
        length: ITEM_HEIGHT,
        offset: ITEM_HEIGHT * index,
        index,
      })}
      pagingEnabled
    />
  );
};

const styles = StyleSheet.create({
  scrollView: {},
  scrollViewContent: {
    justifyContent: 'center',
  },
});

export default CommentsContainer;
