import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';

import { useCallStateHooks } from '@stream-io/video-react-sdk';
import RadioButtonCheckedIcon from '@material-hu/icons/material/RadioButtonChecked';
import {
  IconClock,
  IconPlayerPlay,
  IconSettings,
  IconVideo,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import useTheme from '@material-hu/mui/styles/useTheme';
import Typography from '@material-hu/mui/Typography';

import { Avatar } from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';

import {
  Configuration,
  StreamStatus,
  UserTypeStream,
  VideoOrigin,
} from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getCorrectLabelButton, getCorrectTime } from 'src/utils/stream';

import WidgetIcon from 'src/components/dashboard/widgets/WidgetIcon';

import { HOST_SIDEBAR_WIDTH } from '../../constants';
import { useStreamDestination } from '../../hooks/useStreamDestination';
import useTimerLiveStream from '../../hooks/useTimerLiveStream';

const { GENERAL, CONFIGURATION } = Configuration;

type LiveConfigurationOptionsProps = {
  activeStep: Configuration;
  onStepSelected: (param: Configuration) => void;
  streamStatus: StreamStatus;
  onFinish: () => void;
  onStartPress: () => void;
  onCancel: () => void;
  onGoBack: () => void;
  isLoadingGoLive: boolean;
  isLoadingStopLive: boolean;
};

const LiveConfigurationOptions: FC<LiveConfigurationOptionsProps> = props => {
  const {
    activeStep,
    onStepSelected,
    streamStatus,
    onFinish,
    onStartPress,
    onCancel,
    onGoBack,
    isLoadingGoLive,
    isLoadingStopLive,
  } = props;
  const { t } = useLokaliseTranslation('livestream');

  const { watch } = useFormContext();
  const theme = useTheme();
  const { useParticipants } = useCallStateHooks();
  const participants = useParticipants();
  const { videoOrigin } = watch();

  const isIdle = streamStatus === StreamStatus.Idle;
  const isStreaming = streamStatus === StreamStatus.Streaming;
  const isPreparing = streamStatus === StreamStatus.Preparing;
  const isFinished = streamStatus === StreamStatus.Finished;

  const liveStreamTime = useTimerLiveStream(isStreaming);

  const { details: destinationDetails } = useStreamDestination();

  const steps = {
    [GENERAL]: {
      id: GENERAL,
      label: t('SUMMARY_STREAM'),
      icon: <IconVideo />,
    },
    [CONFIGURATION]: {
      id: CONFIGURATION,
      label: t('CONFIGURATION'),
      icon: <IconSettings />,
    },
  };

  const isConnectSoftwareStream = participants.some(participant =>
    participant.userId.split('-').includes(UserTypeStream.RTMP),
  );

  const disabledToGoLiveSoftwareStream =
    !isConnectSoftwareStream &&
    isIdle &&
    videoOrigin === VideoOrigin.SOFTWARE_STREAMING;

  return (
    <Stack
      sx={{
        position: 'fixed',
        bottom: 0,
        top: theme.spacing(8),
        width: HOST_SIDEBAR_WIDTH,
        px: theme.spacing(2),
        pt: theme.spacing(3),
        pb: theme.spacing(2),
        justifyContent: 'space-between',
        backgroundColor: theme.palette.new.background.layout.default,
        borderRight: `1px solid ${theme.palette.new.border.neutral.default}`,
      }}
    >
      <Stack
        sx={{
          gap: theme.spacing(3),
        }}
      >
        <Typography
          variant="globalL"
          fontWeight="fontWeightSemiBold"
          color="text.primary"
        >
          {isFinished ? t('END') : t('MANAGE_LIVE_STREAM')}
        </Typography>
        {destinationDetails && (
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: theme.spacing(1),
              pb: theme.spacing(1),
              borderBottom: `1px solid ${theme.palette.new.border.neutral.default}`,
            }}
          >
            {destinationDetails.avatar && (
              <Avatar
                src={destinationDetails.avatar.src}
                Icon={destinationDetails.avatar.Icon}
                sx={{
                  backgroundColor: theme.palette.new.background.elements.grey,
                }}
              />
            )}
            {destinationDetails.icon && (
              <WidgetIcon
                icon={destinationDetails.icon}
                width="40px"
                height="40px"
                borderRadius="50%"
                objectFit="cover"
              />
            )}
            <Stack>
              <Typography
                variant="globalS"
                fontWeight="fontWeightSemiBold"
              >
                {t(`DESTINATION_${StreamStatus[streamStatus].toUpperCase()}`, {
                  destination: destinationDetails.title,
                })}
              </Typography>
              <Typography
                variant="globalXS"
                color="new.text.neutral.lighter"
              >
                {destinationDetails.description}
              </Typography>
            </Stack>
          </Stack>
        )}
        <Stack
          sx={{
            gap: theme.spacing(1),
            mx: '-16px',
          }}
        >
          {Object.values(steps).map(step => (
            <Button
              startIcon={step.icon}
              onClick={() => onStepSelected(step.id)}
              key={step.id}
              variant="text"
              disabled={isFinished && step.id === CONFIGURATION}
              size="large"
              sx={{
                justifyContent: 'flex-start',
                color:
                  activeStep === step.id
                    ? theme.palette.new.text.neutral.brand
                    : theme.palette.new.text.neutral.default,
                '&, &:hover': {
                  backgroundColor:
                    activeStep === step.id
                      ? theme.palette.new.background.layout.brand
                      : 'transparent',
                },
                '& .MuiButton-startIcon': {
                  ml: 0,
                  mr: theme.spacing(2),
                  '& svg': {
                    color:
                      activeStep === step.id
                        ? theme.palette.new.text.neutral.brand
                        : theme.palette.new.text.neutral.default,
                  },
                },
              }}
            >
              {step.label}
            </Button>
          ))}
        </Stack>
      </Stack>
      <Stack sx={{ gap: theme.spacing(1) }}>
        {(isStreaming || isFinished) && (
          <Stack
            sx={{
              flexDirection: 'row',
              gap: 1,
              alignItems: 'center',
              mb: 1,
            }}
          >
            <IconClock color={theme.palette.new.text.neutral.default} />
            <Typography
              variant="globalM"
              fontWeight="fontWeightSemiBold"
              color="text.primary"
            >
              {`${getCorrectTime(liveStreamTime.recordingHours)}:${getCorrectTime(liveStreamTime.recordingMinutes)}:${getCorrectTime(liveStreamTime.recordingSeconds)}`}
            </Typography>
            {!isFinished && <RadioButtonCheckedIcon color="error" />}
          </Stack>
        )}
        {isFinished && (
          <Button
            onClick={onGoBack}
            variant="primary"
            size="large"
          >
            {destinationDetails?.goBackText ?? t('GO_BACK')}
          </Button>
        )}
        {(isIdle || isStreaming || isLoadingGoLive) && (
          <Button
            onClick={isStreaming ? onFinish : onStartPress}
            variant={isStreaming ? 'error' : 'primary'}
            size="large"
            disabled={
              isLoadingGoLive ||
              isLoadingStopLive ||
              disabledToGoLiveSoftwareStream
            }
            startIcon={
              isLoadingGoLive || isStreaming ? (
                <IconVideo />
              ) : (
                <IconPlayerPlay />
              )
            }
          >
            {getCorrectLabelButton(t, isLoadingGoLive, isStreaming)}
          </Button>
        )}

        {isPreparing && (
          <Button
            onClick={onCancel}
            variant="primary"
            size="large"
            startIcon={<IconVideo />}
            sx={{
              '& .MuiButton-startIcon svg': {
                width: '16px',
                height: '16px',
              },
            }}
          >
            {t('CANCEL')}
          </Button>
        )}
      </Stack>
    </Stack>
  );
};

export default LiveConfigurationOptions;
