import React, {useMemo} from 'react';
import {View, SectionList} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconUserSearch} from '@tabler/icons-react-native';
import {
  Avatar,
  getUsersAudience,
  newPostQueryKeys,
  Spinner,
  USERS_AUDIENCE_DEFAULT_LIMIT,
} from '@components';
import {Typography} from '@components/_core';
import {segmentateUsers} from '@components/_custom/NewPost/utils';
import {ListEmpty, ListRow} from '@components/_HuGo/List';
import {useInfiniteQuery} from '@hooks/queries/useInfiniteQuery';
import {User} from '@interfaces/user';
import {SegmentationUser} from '@interfaces/segmentation';
import {useTheme} from '@shared/theme';
import {getCompleteName} from '@shared/utils';

import {styles} from './styles';

interface SegmentationUsersProps {
  selectedSegmentationItemIds: number[];
}

const keyExtractor = (item: SegmentationUser, key: number) =>
  `${item.id}-${key}`;

const renderItem = ({item}: {item: SegmentationUser}) => (
  <ListRow style={styles.listRow}>
    <ListRow.Avatar url={item.profilePicture} />
    <ListRow.Title title={getCompleteName(item)} description={item.email} />
  </ListRow>
);

const renderSectionHeader = ({
  section: {title},
}: {
  section: {title: string};
}) => (
  <View style={styles.sectionHeader}>
    <Typography>{title}</Typography>
  </View>
);

const SegmentationUsers = ({
  selectedSegmentationItemIds,
}: SegmentationUsersProps) => {
  const {theme} = useTheme();
  const {data, isLoading, isFetchingNextPage, getNextPage} = useInfiniteQuery(
    newPostQueryKeys.segmentationUsers(selectedSegmentationItemIds),
    ({page}) =>
      getUsersAudience({
        page,
        limit: USERS_AUDIENCE_DEFAULT_LIMIT,
        includeLoggedUser: !!selectedSegmentationItemIds.length,
        segmentationItemIds: selectedSegmentationItemIds.join(','),
      }),
  );
  const {t} = useTranslation();

  const segmentatedUsers = useMemo(() => {
    return segmentateUsers((data as unknown as User[]) || []);
  }, [data]);

  return (
    <View style={styles.container}>
      <SectionList
        keyboardShouldPersistTaps="always"
        sections={segmentatedUsers}
        keyExtractor={keyExtractor}
        renderItem={renderItem}
        renderSectionHeader={renderSectionHeader}
        onEndReached={getNextPage}
        ListFooterComponent={
          isFetchingNextPage || isLoading ? (
            <View style={[{backgroundColor: theme.background.layout.tertiary}]}>
              <Spinner />
            </View>
          ) : null
        }
        ListEmptyComponent={
          !isLoading ? (
            <ListEmpty
              IconComponent={<Avatar Icon={IconUserSearch} variant="primary" />}
              title={t('general.no_people')}
            />
          ) : null
        }
      />
    </View>
  );
};

export default SegmentationUsers;
