import React, {useEffect, useState} from 'react';
import {StyleSheet} from 'react-native';
import {useSelector} from 'react-redux';
import {MomentPostContent, MomentPostHeader} from '.';
import {deleteMomentTag, loadMomentTags} from '../../services';
import {RootState} from '../../store/rootReducer';
import {MomentPostType, MomentTagType, ScreenType} from '../../types';
import {normalize, SCREEN_HEIGHT} from '../../utils';

interface MomentPostProps {
  moment: MomentPostType;
  userXId: string | undefined;
  screenType: ScreenType;
  index: number;
}

const MomentPost: React.FC<MomentPostProps> = ({
  moment,
  userXId,
  screenType,
  index,
}) => {
  const {userId: loggedInUserId, username: loggedInUsername} = useSelector(
    (state: RootState) => state.user.user,
  );

  const {
    user: {username},
  } = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.user,
  );
  const [tags, setTags] = useState<MomentTagType[]>([]);
  const [momentTagId, setMomentTagId] = useState<string>('');

  const isOwnProfile = username === loggedInUsername;

  /*
   * Load tags on initial render to pass tags data to moment header and content
   */
  useEffect(() => {
    loadMomentTags(moment.moment_id).then((response) => {
      setTags(response ? response : []);
    });
  }, []);

  /*
   * Check if loggedInUser has been tagged in the picture and set the id
   */
  useEffect(() => {
    const getMomentTagId = () => {
      const ownTag: MomentTagType[] = tags.filter(
        (tag) => tag.user.id === loggedInUserId,
      );
      if (ownTag?.length > 0) {
        setMomentTagId(ownTag[0].id);
      } else {
        setMomentTagId('');
      }
    };
    getMomentTagId();
  }, [tags]);

  /*
   * Remove tag and update the current tags
   */
  const removeTag = async () => {
    const success = await deleteMomentTag(momentTagId);
    if (success) {
      const filteredTags = tags.filter((tag) => tag.user.id !== loggedInUserId);
      setTags(filteredTags);
    }
  };

  return (
    <>
      <MomentPostHeader
        userXId={userXId}
        screenType={screenType}
        username={isOwnProfile ? loggedInUsername : username}
        momentId={moment.moment_id}
        style={styles.postHeader}
        momentTagId={momentTagId}
        removeTag={removeTag}
      />
      <MomentPostContent
        style={styles.postContent}
        moment={moment}
        screenType={screenType}
        momentTags={tags}
        index={index}
      />
    </>
  );
};

const styles = StyleSheet.create({
  postHeader: {},
  postContent: {
    minHeight: SCREEN_HEIGHT * 0.8,
    paddingBottom: normalize(20),
  },
});

export default MomentPost;
