import { useEffect, useMemo, useState } from 'react';
import { PollRepository } from '@amityco/ts-sdk-react-native';
import { useToast } from '../../core/stores/slices/toastSlice';
const POLL_ERROR = {
  POLL_CLOSED: 'Poll was closed',
  POLL_NOT_FOUND: 'Poll not found'
};
export const usePoll = pollId => {
  const [poll, setPoll] = useState(undefined);
  const [isAuthorSeeingResults, setIsAuthorSeeingResults] = useState(false);
  const {
    showToast
  } = useToast();
  const [loading, setLoading] = useState(false);
  const isPollClosed = useMemo(() => {
    return (poll === null || poll === void 0 ? void 0 : poll.status) === 'closed';
  }, [poll]);
  const isAlreadyVoted = useMemo(() => {
    return poll === null || poll === void 0 ? void 0 : poll.isVoted;
  }, [poll]);
  const totalVotes = useMemo(() => {
    var _poll$answers;
    const total = poll === null || poll === void 0 || (_poll$answers = poll.answers) === null || _poll$answers === void 0 ? void 0 : _poll$answers.reduce((acc, answer) => {
      return acc + answer.voteCount;
    }, 0);
    return total;
  }, [poll]);
  useEffect(() => {
    PollRepository.getPoll(pollId, ({
      data,
      loading: pollLoading
    }) => {
      setPoll(data);
      setLoading(pollLoading);
    });
  }, [pollId]);
  const handlePollError = error => {
    var _error$message, _error$message2;
    if (error !== null && error !== void 0 && (_error$message = error.message) !== null && _error$message !== void 0 && _error$message.includes(POLL_ERROR.POLL_CLOSED)) {
      showToast({
        type: 'informative',
        message: 'Poll ended.'
      });
    } else if (error !== null && error !== void 0 && (_error$message2 = error.message) !== null && _error$message2 !== void 0 && _error$message2.includes(POLL_ERROR.POLL_NOT_FOUND)) {
      showToast({
        type: 'informative',
        message: 'This poll is no longer available.'
      });
    } else {
      showToast({
        type: 'failed',
        message: 'Oops, something went wrong.'
      });
    }
  };
  const votePoll = async answerIds => {
    try {
      await PollRepository.votePoll(pollId, answerIds);
    } catch (error) {
      handlePollError(error);
    }
  };
  const unvotePoll = async () => {
    try {
      await PollRepository.unvotePoll(pollId);
      showToast({
        type: 'success',
        message: 'Vote removed.'
      });
    } catch (error) {
      handlePollError(error);
    }
  };
  return {
    poll,
    loading,
    votePoll,
    unvotePoll,
    totalVotes,
    isPollClosed,
    isAlreadyVoted,
    isAuthorSeeingResults,
    setIsAuthorSeeingResults
  };
};
//# sourceMappingURL=usePoll.js.map