import React, {useCallback, useEffect} from 'react';
import {FlatList} from 'react-native-gesture-handler';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {Navigation} from '@interfaces/navigation';
import {useGetGroupFeed} from '@modules/group/screens/GroupDetail/hooks/useGetGroupFeed';
import GroupPost from '@modules/group/components/GroupPost';
import {useGetGroupById} from '@modules/group/hooks/useGetGroupById';
import {getGroupRoles} from '@modules/group/utils';
import {useTheme} from '@shared/theme';
import {Screens} from '@shared/constants';

import {styles} from './styles';

const keyExtractor = (item: number) => `${item}`;

function PinnedGroupPosts({
  route: {
    params: {groupId},
  },
  navigation,
}: Navigation<Screens.PINNED_GROUP_POSTS>) {
  const {theme} = useTheme();
  const paddingBottom = useSafeAreaBottomPadding();
  const {pinnedPostIds} = useGetGroupFeed({groupId});
  const {data: group} = useGetGroupById(groupId);
  const {iAmAdmin, iAmMember} = getGroupRoles(group);
  const isArchived = group?.isArchived;
  const canManagePosts = !isArchived && iAmAdmin;
  const canManageComments = !isArchived && iAmAdmin;
  const canInteract = !isArchived && iAmMember;

  useEffect(() => {
    if (!pinnedPostIds.length) {
      navigation.goBack();
    }
  }, [navigation, pinnedPostIds.length]);

  const renderPostItem = useCallback(
    ({item}: {item: number}) => {
      return (
        <GroupPost
          postId={item}
          canManagePosts={canManagePosts}
          canManageComments={canManageComments}
          canInteract={canInteract}
          groupId={groupId}
          isArchived={isArchived}
        />
      );
    },
    [canManagePosts, canManageComments, canInteract, groupId, isArchived],
  );

  return (
    <FlatList
      data={pinnedPostIds}
      showsVerticalScrollIndicator={false}
      removeClippedSubviews
      keyExtractor={keyExtractor}
      renderItem={renderPostItem}
      contentContainerStyle={[
        styles.contentContainer,
        {backgroundColor: theme.background.layout.default, paddingBottom},
      ]}
    />
  );
}

export default PinnedGroupPosts;
