import { FC, useEffect } from 'react';

import { StreamVideo } from '@stream-io/video-react-sdk';

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

import { useAuth } from 'src/contexts/JWTContext';
import usePermissions from 'src/hooks/usePermissions';
import useGetStreamVideoClient from 'src/pages/dashboard/liveStream/hooks/useGetStreamVideoClient';
import { useStreamActions } from 'src/pages/dashboard/liveStream/hooks/useStreamActions';
import { UserPermissions } from 'src/utils/permissions';

import StreamioProvider from './context/StreamioProvider';
import { useStreamDestination } from './hooks/useStreamDestination';
import HostLiveStream from './HostLiveStream';
import LiveStreamDemo from './LiveStreamDemo';

const { CREATE_LIVESTREAM } = UserPermissions;

const LiveStream: FC = () => {
  const { hasAll: canCreateLiveStream } = usePermissions([CREATE_LIVESTREAM]);
  const client = useGetStreamVideoClient();
  const { instance, user } = useAuth();

  const { streamData, createMutate, isLoadingCreate } = useStreamActions({});
  const { isLoading: isLoadingDestination } = useStreamDestination();

  useEffect(() => {
    if (canCreateLiveStream) {
      createMutate({ userLanguage: user?.language });
    }
  }, [canCreateLiveStream]);

  const stream = streamData?.data || null;
  const isLoading = isLoadingCreate || isLoadingDestination || !stream;

  return (
    <StreamVideo client={client}>
      {instance?.allowLiveStream && !canCreateLiveStream && <LiveStreamDemo />}
      {canCreateLiveStream && isLoading && (
        <Stack sx={{ alignItems: 'center' }}>
          <CircularProgress />
        </Stack>
      )}
      {canCreateLiveStream && !isLoading && (
        <StreamioProvider
          isHost
          streamId={stream?.providerStreamId}
        >
          <HostLiveStream stream={stream} />
        </StreamioProvider>
      )}
    </StreamVideo>
  );
};

export default LiveStream;
