import React from 'react';
import {View} from 'react-native';
import {AvatarGroup, RadioButton, SelectionCard, Typography} from '@components';
import {Poll, PollOption} from '@interfaces/poll';
import {VotersData} from '@modules/post/interfaces';
import {useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';
import {getCompleteName} from '@shared/utils';

import {styles} from './styles';

const AVATAR_GROUP_LIST_LIMIT = 1;

interface Props {
  pollOption: PollOption;
  index: number;
  pollOptionSelected: number;
  onShowVoters: (data: VotersData) => () => void;
  postId: number;
  groupId?: number;
  handlePollOptionPress: (index: number) => () => void;
  poll: Poll;
  disabled: boolean;
}

function PollItem({
  pollOption,
  index,
  pollOptionSelected,
  onShowVoters,
  postId,
  groupId,
  handlePollOptionPress,
  poll,
  disabled,
}: Props) {
  const {theme} = useTheme();
  const isSelected =
    pollOptionSelected === index || pollOption.isLoggedUserAnswer;
  const votersList = pollOption.voters.map(voter => ({
    id: voter.id,
    url: voter.profilePicture,
    name: getCompleteName(voter),
  }));

  return (
    <SelectionCard
      isSelected={isSelected}
      key={index}
      disabled={disabled}
      onPress={handlePollOptionPress(index)}
      style={[
        styles.selectionCard,
        disabled && {backgroundColor: theme.neutralBgTrans},
      ]}>
      <RadioButton
        disabled={disabled}
        title={pollOption.option}
        checked={isSelected}
        titleWeight="semiBold"
        onPress={handlePollOptionPress(index)}
        style={commonStyles.flex}
      />
      {poll.hasBeenAnswered && (
        <View style={styles.pollOptionRight}>
          <Typography variant="xs" color={theme.neutralTextLighter}>
            {pollOption.answerCount}
          </Typography>
          {!!votersList.length && (
            <AvatarGroup
              size="sm"
              limit={AVATAR_GROUP_LIST_LIMIT}
              groupCount={pollOption.answerCount}
              list={votersList}
              onPress={onShowVoters({
                option: pollOption.option,
                count: pollOption.answerCount,
                postId,
                groupId,
                pollId: poll.id,
                pollOptionId: pollOption.id,
              })}
            />
          )}
        </View>
      )}
    </SelectionCard>
  );
}

export default PollItem;
