import { FC, useEffect } from 'react';

import { useCall, useCallStateHooks } from '@stream-io/video-react-sdk';
import { AxiosResponse } from 'axios';
import Stack from '@material-hu/mui/Stack';
import { styled } from '@material-hu/mui/styles';

import { logEvent } from 'src/config/amplitude';
import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { EventName } from 'src/types/amplitude';
import { LiveStream, LiveStreamPost } from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { ReactionsHandlers } from './components/LiveDetails';
import LiveStreamPlayer from './components/Player';

export const Background = styled(Stack, {
  shouldForwardProp: prop => prop !== 'isHost',
})<{ isHost?: boolean }>(({ theme, isHost = false }) => ({
  alignItems: 'center',
  justifyContent: 'center',
  height: isHost ? 500 : 292,
  background: theme.palette.new.background.elements.inverted,
  borderRadius: '16px',
}));

type ViewerPlayerProps = {
  stream: LiveStream;
  post: LiveStreamPost;
  reactionsHandlers: ReactionsHandlers;
  shouldPlay: boolean;
  setAlwaysPlayMode: () => void;
  pollService?: {
    vote: (pollId: number, pollOptionId: number) => Promise<AxiosResponse>;
    key: Array<string | number>;
  };
};

const ViewerPlayer: FC<ViewerPlayerProps> = props => {
  const {
    stream,
    post,
    reactionsHandlers,
    shouldPlay,
    setAlwaysPlayMode,
    pollService,
  } = props;

  const { t } = useLokaliseTranslation('livestream');
  const { user, instance } = useAuth();

  const { useCallEndedAt } = useCallStateHooks();
  const showGeneralError = useGeneralError();
  const call = useCall();
  const endedAt = useCallEndedAt();

  useEffect(() => {
    if (call && !endedAt && shouldPlay) {
      call
        .join()
        .then(() => {
          setAlwaysPlayMode();
          logEvent(EventName.LIVESTREAM_VIEWER_JOIN, {
            userId: user?.id,
            instanceId: instance?.id,
            livestreamId: stream.id,
            isHls: stream.hlsEnabled,
          });
        })
        .catch(error => {
          showGeneralError(error, t('ERROR_JOIN_VIDEO'));
          logEvent(EventName.LIVESTREAM_VIEWER_REQUEST_JOIN_ERROR, {
            userId: user?.id,
            livestreamId: stream.id,
            isHls: stream.hlsEnabled,
            status: stream.status,
            error:
              typeof error === 'object' && error !== null && 'message' in error
                ? error.message
                : 'Unknown error',
          });
        });
    }

    // "When the user navigates to another section within Humand, they should exit the call."
    return () => {
      if (call) {
        // It is not necessary to use try in the method or to catch the error.
        call.leave().catch(console.error);
      }
    };
  }, [call, endedAt, shouldPlay]);

  return (
    <LiveStreamPlayer
      stream={stream}
      post={post}
      reactionsHandlers={reactionsHandlers}
      pollService={pollService}
    />
  );
};

export default ViewerPlayer;
