import React from 'react';
import {ListRenderItem} from 'react-native';
import {useTranslation} from 'react-i18next';
import {FlatList} from 'react-native-gesture-handler';
import {IconInfoCircle} from '@tabler/icons-react-native';
import {Avatar, ListEmpty, ListFooter, RefreshControl} from '@components';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import BottomSheetPost from '@modules/post/components/BottomSheetPost';
import {PostRequest} from '@modules/post/interfaces';
import {DEFAULT_THRESHOLD} from '@shared/constants';
import {SPACING} from '@shared/theme';

import {styles} from './styles';

export interface PendingApprovalPostsListProps {
  data: PostRequest[];
  isFetchingNextPage: boolean;
  getNextPage: () => void;
  onRefresh: () => void;
  isRefreshing: boolean;
}

const keyExtractor = (item: PostRequest) => `${item.id}`;

const renderItem: ListRenderItem<PostRequest> = ({item}) => (
  <BottomSheetPost
    item={
      item.postContent?.bodyHtml
        ? {
            ...item.post,
            bodyHtml: item.postContent.bodyHtml,
          }
        : item.post
    }
    isEdited={!!item.postContent?.bodyHtml}
    requestId={item.id}
  />
);

export function PendingApprovalPostsList({
  data,
  isFetchingNextPage,
  getNextPage,
  onRefresh,
  isRefreshing,
}: PendingApprovalPostsListProps) {
  const {t} = useTranslation();
  const paddingBottom = useSafeAreaBottomPadding({bottom: SPACING['x1.5']});

  return (
    <FlatList
      refreshControl={
        <RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} />
      }
      showsVerticalScrollIndicator={false}
      contentContainerStyle={[styles.listContentContainer, {paddingBottom}]}
      data={data}
      keyExtractor={keyExtractor}
      ListEmptyComponent={
        <ListEmpty
          IconComponent={<Avatar Icon={IconInfoCircle} variant="primary" />}
          title={t('post.no_results')}
        />
      }
      ListFooterComponent={
        <ListFooter
          isFetchingNextPage={isFetchingNextPage}
          paginationType="infiniteScroll"
          isVisible
        />
      }
      renderItem={renderItem}
      onEndReached={getNextPage}
      onEndReachedThreshold={DEFAULT_THRESHOLD}
    />
  );
}
