import { FC, useEffect } from 'react';

import { useQuery } from 'react-query';

import CircularProgress from '@material-hu/mui/CircularProgress';
import Stack from '@material-hu/mui/Stack';

import Typography from '@material-hu/mui/Typography/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';

import Tooltip from '@material-hu/components/design-system/Tooltip';
import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import { getLivestreamPolls } from 'src/services/streaming';

import {
  LivestreamPollAnsweredEvent,
  PollStatus,
  StreamStatus,
} from 'src/types/stream';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { incrementPollOptionVote, livestreamKeys } from '../../../queries';

import { getPollStatus } from '../../../utils';

import EmptyState from './EmptyState';
import { usePollDrawer } from './hooks';
import PollItem from './Item';

type ContainerProps = {
  streamId: string;
  streamStatus: StreamStatus;
};

const Container: FC<ContainerProps> = props => {
  const { streamId, streamStatus } = props;
  const { t } = useLokaliseTranslation('livestream');
  const socket = useSocket();
  const { createPollDrawer, showCreatePollDrawer, showEditPollDrawer } =
    usePollDrawer({
      streamId,
    });

  const { data: polls, isLoading: isLoadingPolls } = useQuery(
    livestreamKeys.polls(streamId),
    () => getLivestreamPolls(streamId),
    {
      select: response => response.data.polls,
    },
  );

  useEffect(() => {
    const handlePollAnswered = (event: LivestreamPollAnsweredEvent) => {
      if (event.livestreamId === streamId) {
        incrementPollOptionVote(streamId, event.pollId, event.pollOptionId);
      }
    };

    socket.listenEvent(
      EVENTS_SOCKETS.LIVESTREAM_POLL_ANSWERED,
      handlePollAnswered,
    );

    return () => {
      socket.closeEvent(
        EVENTS_SOCKETS.LIVESTREAM_POLL_ANSWERED,
        handlePollAnswered,
      );
    };
  }, [socket, streamId]);

  const showEmptyState = polls?.length === 0;
  const showPolls = polls && polls.length > 0;
  const showCardContainer =
    streamStatus === StreamStatus.Idle ||
    streamStatus === StreamStatus.Connecting ||
    streamStatus === StreamStatus.Preparing;

  const content = (
    <>
      {showEmptyState && (
        <EmptyState
          onButtonClick={showCreatePollDrawer}
          streamStatus={streamStatus}
        />
      )}
      {showPolls && (
        <Stack sx={{ gap: 2 }}>
          <Stack>
            <Typography
              variant="globalM"
              fontWeight="fontWeightSemiBold"
              color="new.text.neutral.default"
            >
              {showCardContainer && t('polls.title')}
            </Typography>
            <Typography
              variant="globalXS"
              color="new.text.neutral.lighter"
            >
              {showCardContainer
                ? t('polls.before_start.description')
                : t('polls.live_started')}
            </Typography>
          </Stack>
          <Stack sx={{ maxHeight: '450px', gap: 1, overflow: 'auto' }}>
            {polls.map(poll => (
              <PollItem
                key={poll.id}
                streamId={streamId}
                poll={poll}
                streamStatus={streamStatus}
                onEditButtonClick={showEditPollDrawer}
                isAnotherPollActive={polls.some(
                  p =>
                    p.id !== poll.id &&
                    getPollStatus(
                      p.pollConfiguration.startsAt,
                      p.pollConfiguration.endsAt,
                    ) === PollStatus.ACTIVE,
                )}
              />
            ))}
          </Stack>
          {streamStatus !== StreamStatus.Finished && (
            <Tooltip
              disableTooltip={polls.length < 10}
              description={t('polls.max_polls_created')}
            >
              <Stack>
                <Button
                  variant="secondary"
                  size="large"
                  fullWidth
                  onClick={showCreatePollDrawer}
                  disabled={polls.length >= 10}
                >
                  {showCardContainer
                    ? t('polls.create')
                    : t('polls.create_at_live')}
                </Button>
              </Stack>
            </Tooltip>
          )}
        </Stack>
      )}
    </>
  );

  if (isLoadingPolls) {
    return (
      <Stack
        sx={{
          width: '100%',
          height: '100%',
          justifyContent: 'center',
          alignItems: 'center',
          py: 4,
        }}
      >
        <CircularProgress />
      </Stack>
    );
  }

  return (
    <>
      {createPollDrawer}
      {showCardContainer && (
        <CardContainer
          sx={{
            width: '100%',
            py: theme => theme.spacing(1),
          }}
        >
          {content}
        </CardContainer>
      )}
      {!showCardContainer && content}
    </>
  );
};

export default Container;
