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

import {
  type StreamVideoParticipant,
  useCall,
} from '@stream-io/video-react-sdk';
import { LayoutGroup } from 'motion/react';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

import { getCallLayoutAspectRatio } from 'src/pages/dashboard/videoCall/utils';

import CallControls from '../controls/CallControls';

import AutoplayBlockedAlert from './AutoplayBlockedAlert';
import CallHeader from './CallHeader';
import LowBandwithAlert from './LowBandwithAlert';

export type CallLayoutContainerProps = {
  children: ReactNode;
  providerParticipants: StreamVideoParticipant[];
  screenShareParticipant?: StreamVideoParticipant;
  handleShowParticipants: () => void;
  handleShowAddParticipantModal: () => void;
  onEndCall: () => void;
};

const CallLayoutGrid: FC<CallLayoutContainerProps> = props => {
  const {
    children,
    providerParticipants,
    screenShareParticipant,
    handleShowParticipants,
    handleShowAddParticipantModal,
    onEndCall,
  } = props;
  const theme = useTheme();

  const [participantsGrid, setParticipantsGrid] =
    useState<HTMLDivElement | null>(null);

  const call = useCall();

  useEffect(() => {
    if (!participantsGrid || !call) return;
    const cleanup = call.setViewport(participantsGrid);
    return () => cleanup?.();
  }, [participantsGrid, call]);

  return (
    <Stack
      ref={setParticipantsGrid}
      sx={{
        alignItems: 'center',
        position: 'relative',
        width: '100%',
        height: '100%',
        backgroundColor: theme.palette.base?.grey[800],
      }}
    >
      <CallHeader
        handleShowParticipants={handleShowParticipants}
        providerParticipants={providerParticipants}
      />
      <Stack
        sx={{
          height: '100%',
          width: 'inherit',
          px: theme.spacing(3),
          overflow: 'hidden',
        }}
      >
        <Stack
          sx={{
            height: '100%',
            justifyContent: 'center',
            alignItems: 'center',
            '& .str-video__participant-view': {
              maxWidth: '100%',
              aspectRatio: getCallLayoutAspectRatio(
                providerParticipants.length,
                !!screenShareParticipant,
              ),
              borderRadius: 1,
              '& .str-video__video': {
                width: '100%',
              },
            },
          }}
        >
          <LayoutGroup>{children}</LayoutGroup>
        </Stack>
      </Stack>
      <CallControls
        handleShowAddParticipantModal={handleShowAddParticipantModal}
        screenShareParticipant={screenShareParticipant}
        onEndCall={onEndCall}
      />
      <LowBandwithAlert />
      <AutoplayBlockedAlert variant="call" />
    </Stack>
  );
};

export default CallLayoutGrid;
