import { type FC } from 'react';

import {
  CallingState,
  type StreamVideoParticipant,
  useCall,
  useCallStateHooks,
} from '@stream-io/video-react-sdk';
import { useModal } from '@material-hu/hooks/useModal';
import {
  IconMicrophone,
  IconMicrophoneOff,
  IconPhoneOff,
  IconScreenShare,
  IconScreenShareOff,
  IconUserPlus,
  IconVideo,
  IconVideoOff,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuDialog from '@material-hu/components/design-system/Dialog';

import useGeneralError from 'src/hooks/useGeneralError';
import { CALL_SNACKBAR_BOTTOM_SPACING } from 'src/pages/dashboard/videoCall/constants';
import { CallMode } from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { truncateText } from 'src/utils/text';

import Button from './Button';
import Toggle from './Toggle';

type CallControlsProps = {
  screenShareParticipant?: StreamVideoParticipant | undefined;
  handleShowAddParticipantModal?: () => void;
  onEndCall: () => void;
};

const CallControls: FC<CallControlsProps> = props => {
  const { screenShareParticipant, handleShowAddParticipantModal, onEndCall } =
    props;
  const theme = useTheme();
  const { t } = useLokaliseTranslation('calls');
  const showGeneralError = useGeneralError();

  const call = useCall();

  const {
    useCallCallingState,
    useCameraState,
    useMicrophoneState,
    useScreenShareState,
    useCallCustomData,
    useParticipants,
  } = useCallStateHooks();

  const {
    camera,
    isMute: cameraIsMute,
    hasBrowserPermission: hasPermissionCamera,
  } = useCameraState();
  const {
    microphone,
    isMute: microphoneIsMute,
    hasBrowserPermission: hasPermissionMicrophone,
  } = useMicrophoneState();
  const { screenShare, status: screenShareStatus } = useScreenShareState();

  const callingState = useCallCallingState();
  const isJoining = callingState === CallingState.JOINING;

  const { type } = useCallCustomData();

  const participants = useParticipants();
  const isLastParticipant = participants.length === 1;

  const {
    modal: confirmShareScreenModal,
    showModal: showConfirmShareScreenModal,
    closeModal: closeConfirmShareScreenModal,
  } = useModal(
    HuDialog,
    {
      fullWidth: true,
      maxWidth: 'sm',
    },
    {
      title: t('SHARE_SCREEN_MODAL_TITLE'),
      textBody: t('SHARE_SCREEN_MODAL_TEXT', {
        name: screenShareParticipant?.name.split(' ')[0] || '',
      }),
      primaryButtonProps: {
        children: t('START_SCREEN_SHARE'),
        onClick: () => {
          screenShare.toggle();
          closeConfirmShareScreenModal();
        },
      },
      secondaryButtonProps: {
        children: t('CANCEL'),
        onClick: () => {
          closeConfirmShareScreenModal();
        },
      },
    },
  );

  const handleToggleScreenShare = () => {
    if (screenShareStatus !== 'enabled' && screenShareParticipant) {
      showConfirmShareScreenModal();
    } else {
      screenShare.toggle();
    }
  };

  const handleLeaveCall = () => {
    if (!type || type === CallMode.SINGLE || isLastParticipant) {
      onEndCall();
    } else {
      call?.leave().catch(error => {
        showGeneralError(error, t('ERROR_LEAVE_CALL'), true, {
          spacing: {
            bottom: CALL_SNACKBAR_BOTTOM_SPACING,
          },
        });
      });
    }
  };

  return (
    <>
      {confirmShareScreenModal}
      <Stack
        sx={{
          position: 'relative',
          width: '100%',
          background: 'linear-gradient(180deg, transparent, #000000b3)',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'center',
          gap: theme.spacing(3),
          py: theme.spacing(2),
        }}
      >
        {screenShareParticipant && (
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
            color="new.text.neutral.inverted"
            sx={{
              position: 'absolute',
              left: 24,
              bottom: 26,
            }}
          >
            {t('SCREEN_SHARE_PARTICIPANT', {
              name: truncateText(screenShareParticipant.name, 44),
            })}
          </Typography>
        )}
        <Toggle
          onToggle={() => camera.toggle()}
          isOff={cameraIsMute}
          offText={t('TURN_CAMERA_ON')}
          onText={t('TURN_CAMERA_OFF')}
          IconOff={IconVideoOff}
          IconOn={IconVideo}
          permissionText={t('PERMISSION_TOOLTIP')}
          hasPermission={hasPermissionCamera}
          highlightOff
        />
        <Toggle
          onToggle={() => microphone.toggle()}
          isOff={microphoneIsMute}
          offText={t('TURN_MIC_ON')}
          onText={t('TURN_MIC_OFF')}
          IconOff={IconMicrophoneOff}
          IconOn={IconMicrophone}
          permissionText={t('PERMISSION_TOOLTIP')}
          hasPermission={hasPermissionMicrophone}
          highlightOff
        />
        <Toggle
          onToggle={handleToggleScreenShare}
          isOff={screenShareStatus !== 'enabled'}
          offText={t('START_SCREEN_SHARE')}
          onText={t('STOP_SCREEN_SHARE')}
          IconOff={IconScreenShare}
          IconOn={IconScreenShareOff}
          disabled={isJoining}
        />
        <Button
          onClick={handleShowAddParticipantModal}
          text={t('ADD_MEMBER')}
          Icon={IconUserPlus}
          disabled={!handleShowAddParticipantModal}
        />
        <Button
          variant="danger"
          onClick={handleLeaveCall}
          text={t('LEAVE_CALL')}
          Icon={IconPhoneOff}
          disabled={isJoining}
        />
      </Stack>
    </>
  );
};

export default CallControls;
