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

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

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

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

import HostContent from './HostContent';
import HostLiveConfigurationOptions from './HostLiveConfigurationOptions';

type HostLiveStreamLayoutProps = {
  postId?: number;
  streamId: string;
  streamStatus: StreamStatus;
  onHardwareReady: () => void;
  onStartPress: () => void;
  onCancel: () => void;
  onReady: () => void;
  onFinish: () => void;
  onGoBack: () => void;
  isLoadingGoLive: boolean;
  isLoadingStopLive: boolean;
};

const { GENERAL, CONFIGURATION } = Configuration;

const HostLiveStreamLayout: FC<HostLiveStreamLayoutProps> = props => {
  const {
    postId,
    streamId,
    streamStatus,
    onReady,
    onFinish,
    onHardwareReady,
    onStartPress,
    onCancel,
    onGoBack,
    isLoadingGoLive,
    isLoadingStopLive,
  } = props;

  const [activeStep, setActiveStep] = useState(GENERAL);
  const { useCameraState, useMicrophoneState } = useCallStateHooks();
  const { hasBrowserPermission: hasPermissionCamera } = useCameraState();
  const { hasBrowserPermission: hasPermissionMicrophone } =
    useMicrophoneState();

  useEffect(() => {
    if (hasPermissionCamera && hasPermissionMicrophone) {
      onHardwareReady();
    }
  }, [hasPermissionCamera, hasPermissionMicrophone, onHardwareReady]);

  useEffect(() => {
    const isFinished = streamStatus === StreamStatus.Finished;
    const isInConfiguration = activeStep === CONFIGURATION;
    if (isFinished && isInConfiguration) {
      handleStepSelect(GENERAL);
    }
  }, [streamStatus, activeStep]);

  const handleStepSelect = (selectedStep: Configuration) =>
    setActiveStep(selectedStep);

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        mt: theme => theme.spacing(8),
      }}
    >
      <HostLiveConfigurationOptions
        streamStatus={streamStatus}
        activeStep={activeStep}
        onStepSelected={handleStepSelect}
        onStartPress={onStartPress}
        onFinish={onFinish}
        onCancel={onCancel}
        onGoBack={onGoBack}
        isLoadingGoLive={isLoadingGoLive}
        isLoadingStopLive={isLoadingStopLive}
      />
      <HostContent
        postId={postId}
        streamId={streamId}
        streamStatus={streamStatus}
        activeStep={activeStep}
        onReady={onReady}
      />
    </Stack>
  );
};

export default HostLiveStreamLayout;
