import { FC, memo } from 'react';

import { usePoll } from 'src/hooks/usePoll';
import { Poll as PollType } from 'src/types/posts';

import { usePost } from 'src/components/post/PostContext';

import PollAnonymousMessage from './PollAnonymousMessage';
import PollDeadlineDisplay from './PollDeadlineDisplay';
import { PollLayout } from './PollLayout';
import PollOptionsContainer from './PollOptionsContainer';
import PollVoteButton from './PollVoteButton';

type PollProps = {
  id: number;
  poll: PollType;
  isDetail?: boolean;
  isDraft?: boolean;
  viewOnly?: boolean;
  /** Whether the user can vote (for group member check). Defaults to true. */
  userCanVote?: boolean;
};

const Poll: FC<PollProps> = props => {
  const {
    id,
    poll,
    isDetail = false,
    isDraft = false,
    viewOnly = false,
    userCanVote = true,
  } = props;

  const { groupId } = usePost();

  const {
    votersVisible,
    pollEnded,
    selectedOption,
    isLoading,
    handleSelect,
    submit,
  } = usePoll({
    poll,
    postId: id,
    groupId: groupId?.toString(),
    isDetail,
  });

  return (
    <PollLayout>
      <PollDeadlineDisplay endsAt={poll.pollConfiguration?.endsAt} />

      <PollAnonymousMessage
        votersVisible={votersVisible}
        hasBeenAnswered={poll.hasBeenAnswered}
      />

      <PollOptionsContainer
        pollOptions={poll.pollOptions}
        disabled={
          poll.hasBeenAnswered ||
          isDraft ||
          pollEnded ||
          viewOnly ||
          !userCanVote
        }
        onSelect={handleSelect}
        selectedOption={selectedOption}
        votersVisible={votersVisible}
        poll={poll}
        postId={id}
      />

      {!viewOnly && userCanVote && (
        <PollVoteButton
          hasBeenAnswered={poll.hasBeenAnswered}
          isDraft={isDraft}
          disabled={selectedOption === null || pollEnded}
          onVote={submit}
          isLoading={isLoading}
        />
      )}
    </PollLayout>
  );
};

export default memo(Poll);
