import { useState, useEffect } from 'react';

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

import { IconVolume, IconVolumeOff } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Slider from '@material-hu/mui/Slider';
import Stack from '@material-hu/mui/Stack';
import { alpha, useTheme } from '@material-hu/mui/styles';

import ControlsContainer from './ControlsContainer';

const DEFAULT_VOLUME = 50;
const MAX_SLIDER_VALUE = 100;

type SoftwareControlsProps = {
  isStreaming: boolean;
};

const SoftwareControls = ({ isStreaming }: SoftwareControlsProps) => {
  const theme = useTheme();
  const { useSpeakerState } = useCallStateHooks();
  const { participant } = useParticipantViewContext();
  const [sliderValue, setSliderValue] = useState(DEFAULT_VOLUME);
  const [previousVolume, setPreviousVolume] = useState(DEFAULT_VOLUME);
  const [isSliderOpen, setIsSliderOpen] = useState(false);

  const { speaker } = useSpeakerState();

  useEffect(() => {
    const volumeValue = isStreaming ? 0 : sliderValue / MAX_SLIDER_VALUE;
    speaker.setParticipantVolume(participant.sessionId, volumeValue);
    setSliderValue(volumeValue * MAX_SLIDER_VALUE);
  }, [isStreaming, participant.sessionId]);

  const handleVolumeClick = () => {
    if (sliderValue === 0) {
      const volumeToRestore = previousVolume / MAX_SLIDER_VALUE;
      speaker.setParticipantVolume(participant.sessionId, volumeToRestore);
      setSliderValue(previousVolume);
    } else {
      speaker.setParticipantVolume(participant.sessionId, 0);
      setPreviousVolume(sliderValue);
      setSliderValue(0);
    }
  };

  const handleVolumeChange = (event: Event, newValue: number | number[]) => {
    const value = Array.isArray(newValue) ? newValue[0] : newValue;
    speaker.setParticipantVolume(
      participant.sessionId,
      value / MAX_SLIDER_VALUE,
    );
    setSliderValue(value);
  };

  const handleVolumeChangeCommitted = (
    event: Event | React.SyntheticEvent,
    newValue: number | number[],
  ) => {
    const value = Array.isArray(newValue) ? newValue[0] : newValue;
    if (value > 0) {
      setPreviousVolume(value);
    }
  };

  return (
    <ControlsContainer>
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'flex-end',
          alignItems: 'center',
          flex: '1',
          gap: 1,
        }}
        onMouseLeave={() => setIsSliderOpen(false)}
      >
        {isSliderOpen && (
          <Slider
            min={0}
            max={MAX_SLIDER_VALUE}
            value={sliderValue}
            onChange={handleVolumeChange}
            onChangeCommitted={handleVolumeChangeCommitted}
            sx={{
              maxWidth: '240px',
              '& .MuiSlider-thumb': {
                height: 12,
                width: 12,
                backgroundColor:
                  sliderValue === 0
                    ? theme.palette.new.border.neutral.default
                    : theme.palette.base?.blueBrand[400],
                display: 'none',
                border: 'none',
              },
              '& .MuiSlider-track': {
                height: 4,
                backgroundColor:
                  sliderValue === 0
                    ? theme.palette.new.border.neutral.default
                    : theme.palette.base?.blueBrand[400],
                borderColor:
                  sliderValue === 0
                    ? theme.palette.new.border.neutral.default
                    : theme.palette.base?.blueBrand[400],
              },
              '& .MuiSlider-rail': {
                height: 4,
                backgroundColor: theme.palette.new.border.neutral.default,
                opacity: 1,
              },
              '&:hover': {
                '& .MuiSlider-thumb': {
                  display: 'block',
                  boxShadow: `0px 0px 0px 8px ${alpha(theme.palette.base?.blueBrand[400] ?? '', 0.15)}`,
                },
              },
            }}
          />
        )}
        <IconButton
          onClick={handleVolumeClick}
          onMouseEnter={() => setIsSliderOpen(true)}
          sx={{
            svg: {
              color: theme.palette.base?.white,
              stroke: theme.palette.base?.white,
            },
          }}
        >
          {sliderValue > 0 && <IconVolume />}
          {sliderValue === 0 && <IconVolumeOff />}
        </IconButton>
      </Stack>
    </ControlsContainer>
  );
};

export default SoftwareControls;
