import { type FC, useEffect, useState } from 'react';

import {
  type ClosedCaptionEvent,
  hasVideo,
  useCall,
  useCallStateHooks,
  useParticipantViewContext,
} from '@stream-io/video-react-sdk';
import { type AxiosResponse } from 'axios';
import { IconBadgeCc, IconBadgeCcFilled } from '@material-hu/icons/tabler';
import Chip from '@material-hu/mui/Chip';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

import HuTooltip from '@material-hu/components/design-system/Tooltip';

import {
  FullScreenElementType,
  type LiveStream,
  type LiveStreamPost,
  StreamEvents,
} from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';

import Captions from 'src/components/attachment/components/Captions';

import { FULL_SCREEN_COMMENT_WIDTH } from '../constants';
import { calculatePillsTopMargin, getIsRtmpConnection } from '../utils';

import ClosePlayerButton from './components/ClosePlayerButton';
import Controls from './components/Controls';
import ParticipantCountPill from './components/ParticipantCountPill';
import Poll from './components/Poll';
import useScreenDimensions from './hooks/useScreenDimensions';
import type useVolume from './hooks/useVolume';

type CustomParticipantViewProps = {
  stream: LiveStream;
  fullScreenElement: FullScreenElementType;
  toggleFullscreen: () => void;
  onClose: () => void;
  post: LiveStreamPost;
  showControls: boolean;
  pollService?: {
    vote: (pollId: number, pollOptionId: number) => Promise<AxiosResponse>;
    key: Array<string | number>;
  };
  isCaptionsOpen: boolean;
  setIsCaptionsOpen: (open: boolean) => void;
  volumeHandlers: ReturnType<typeof useVolume>;
};

export const fullScreenCommentWidth = Number(
  FULL_SCREEN_COMMENT_WIDTH.replace('px', ''),
);

const CustomParticipantView: FC<CustomParticipantViewProps> = props => {
  const {
    stream,
    fullScreenElement,
    toggleFullscreen,
    onClose,
    post,
    showControls,
    pollService,
    isCaptionsOpen,
    setIsCaptionsOpen,
    volumeHandlers,
  } = props;
  const { participant, participantViewElement } = useParticipantViewContext();
  const { useParticipantCount, useCallCustomData, useHasOngoingScreenShare } =
    useCallStateHooks();
  const { isRtmpConnection: customDataIsRtmpConnection } = useCallCustomData();
  const isRtmpConnection = getIsRtmpConnection(
    stream.streamSource,
    customDataIsRtmpConnection,
  );
  const participantCount = useParticipantCount();
  const hasOngoingScreenshare = useHasOngoingScreenShare();

  const { t } = useLokaliseTranslation('livestream');
  const call = useCall();
  const theme = useTheme();

  const [closedCaptions, setClosedCaptions] = useState<string>('');

  const { containerDimensions } = useScreenDimensions(
    fullScreenElement !== FullScreenElementType.NONE,
    participantViewElement,
  );

  const realParticipantCount = isRtmpConnection
    ? participantCount - 2
    : participantCount - 1;

  const showClosePlayerButton =
    fullScreenElement !== FullScreenElementType.NONE;

  useEffect(() => {
    if (!call || !isCaptionsOpen) return;

    const closedCaptionHandler = (event: ClosedCaptionEvent) => {
      setClosedCaptions(event.closed_caption.text);
    };

    call.on(StreamEvents.CLOSED_CAPTION, closedCaptionHandler);

    return () => {
      call.off(StreamEvents.CLOSED_CAPTION, closedCaptionHandler);
    };
  }, [call, isCaptionsOpen]);

  const toggleClosedCaption = () => {
    if (!isCaptionsOpen) {
      setClosedCaptions('');
    }
    setIsCaptionsOpen(!isCaptionsOpen);
  };

  return (
    <>
      <Stack
        sx={{
          position: 'absolute',
          top: calculatePillsTopMargin({
            spacing: 16,
            hasOngoingScreenshare,
            fullScreenElement,
            participantViewElement,
            containerDimensions,
            source: stream.source,
            hasVideo: hasVideo(participant),
          }),
          left: theme.spacing(2),
          flexDirection: 'row',
          alignItems: 'center',
          gap: theme.spacing(1),
          zIndex: 1,
        }}
      >
        {showClosePlayerButton && (
          <ClosePlayerButton
            onClick={
              fullScreenElement === FullScreenElementType.FULL
                ? toggleFullscreen
                : onClose
            }
          />
        )}
        <Chip
          // DS doesn't have dark variant yet
          sx={{
            height: '36px',
            backgroundColor: theme.palette.base?.red[800],
            border: `1px solid ${theme.palette.base?.red[600]}`,
            color: theme.palette.base?.white,
            fontSize: 14,
            fontWeight: 600,
          }}
          label={t('LIVE')}
        />
        <ParticipantCountPill count={realParticipantCount} />
      </Stack>
      {stream.captionsEnabled && isCaptionsOpen && closedCaptions && (
        <Captions
          captions={closedCaptions}
          variant={
            fullScreenElement === FullScreenElementType.NONE
              ? 'globalXXS'
              : 'globalL'
          }
          sx={{
            left:
              fullScreenElement === FullScreenElementType.SEMI
                ? `calc(50% - ${fullScreenCommentWidth / 2}px)`
                : '50%',
          }}
        />
      )}
      {post.poll && pollService && (
        <Poll
          poll={post.poll}
          pollService={pollService}
          isCaptionsOpen={isCaptionsOpen}
          toggleFullscreen={toggleFullscreen}
          fullScreenElement={fullScreenElement}
        />
      )}
      <Controls
        fullScreenElement={fullScreenElement}
        showControls={showControls}
        controlHandlers={{ toggleFullscreen }}
        volumeHandlers={volumeHandlers}
      >
        {stream.captionsEnabled && (
          <HuTooltip
            description={t('TOOLTIP_CAPTIONS')}
            direction="top"
          >
            <IconButton
              sx={{
                svg: {
                  stroke: theme.palette.base?.white,
                  color: theme.palette.base?.white,
                },
                '&:hover svg': {
                  stroke: theme.palette.base?.white,
                  color: theme.palette.base?.white,
                },
              }}
              onClick={toggleClosedCaption}
            >
              {isCaptionsOpen && <IconBadgeCcFilled />}
              {!isCaptionsOpen && <IconBadgeCc />}
            </IconButton>
          </HuTooltip>
        )}
      </Controls>
    </>
  );
};

export default CustomParticipantView;
