import React from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Dialog, List, ListRow, Pill, Spinner, Typography} from '@components';
import {useCursorInfinityQuery} from '@hooks/queries/useCursorInfinityQuery';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {User} from '@interfaces/user';
import {VotersData} from '@modules/post/interfaces';
import {postQueryKeys} from '@modules/post/constants';
import {getPollVoters} from '@modules/post/services';
import {DEFAULT_LIMIT} from '@services/constants';
import {getCompleteName} from '@shared/utils/generics';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

function VotersBottomSheet({
  onClose,
  data: {option, count, postId, groupId, pollId, pollOptionId},
}: {onClose: () => void} & {data: VotersData}) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const paddingBottom = useSafeAreaBottomPadding();
  const {data, isLoading, isFetchingNextPage, getNextPage, refresh} =
    useCursorInfinityQuery({
      queryKey: postQueryKeys.pollVoters({pollId, pollOptionId, postId}),
      queryFn: ({cursor}) =>
        getPollVoters({
          limit: DEFAULT_LIMIT,
          cursor,
          postId,
          groupId,
          pollId,
          pollOptionId,
        }),
    });

  const renderItem = ({item}: {item: User}) => {
    const name = getCompleteName(item);
    return (
      <ListRow>
        <ListRow.Avatar name={name} url={item.profilePicture} />
        <ListRow.Title title={name} />
        {item.isExternal && (
          <Pill variant="neutral" size="sm" text={t('group.external')} />
        )}
      </ListRow>
    );
  };

  return (
    <Dialog
      isVisible
      onClose={onClose}
      title={t('post.voters')}
      contentStyle={styles.dialog}>
      <View>
        <Typography variant="m" weight="semiBold">
          {`${t('post.option')}: ${option}`}
        </Typography>
        {!isLoading && (
          <Typography variant="xs" color={theme.neutralTextLighter}>
            {t('post.vote_count', {count: Math.max(data.length, count)})}
          </Typography>
        )}
      </View>
      {isLoading ? (
        <View style={styles.loadingContainer}>
          <Spinner />
        </View>
      ) : (
        <List
          data={data}
          renderItem={renderItem}
          showsVerticalScrollIndicator={false}
          onNextPage={getNextPage}
          style={[styles.list, {paddingBottom}]}
          onRefresh={refresh}
          isFetchingNextPage={isFetchingNextPage}
          isLoading={isLoading}
          FetchingNextPageLoader={<Spinner />}
          bounces={false}
          paginationType="infiniteScroll"
        />
      )}
    </Dialog>
  );
}

export default VotersBottomSheet;
