import { type FC } from 'react';

import {
  useCallStateHooks,
  useConnectedUser,
  VideoPreview,
} from '@stream-io/video-react-sdk';
import {
  IconMicrophone,
  IconMicrophoneOff,
  IconPhone,
  IconVideo,
  IconVideoOff,
} 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/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';
import Spinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { useLokaliseTranslation } from 'src/utils/i18n';

import Toggle from '../controls/Toggle';

import LobbyContainer from './Container';
import VideoPreviewPlaceholder from './VideoPreviewPlaceholder';

const CARD_WIDTH = '692px';

type LobbyScreenProps = {
  joinCall: () => Promise<void>;
  isJoining: boolean;
};

const LobbyScreen: FC<LobbyScreenProps> = props => {
  const { joinCall, isJoining } = props;
  const { t } = useLokaliseTranslation('calls');
  const theme = useTheme();
  const connectedUser = useConnectedUser();
  const { useCallSession, useMicrophoneState, useCameraState } =
    useCallStateHooks();
  const {
    isMute: microphoneIsMute,
    microphone,
    hasBrowserPermission: hasPermissionMicrophone,
  } = useMicrophoneState();
  const {
    isMute: cameraIsMute,
    camera,
    hasBrowserPermission: hasPermissionCamera,
  } = useCameraState();

  const callSession = useCallSession();
  const participants = callSession?.participants;
  const hasParticipants = participants && participants.length > 0;

  return (
    <LobbyContainer title={t('lobby_header')}>
      <Stack
        sx={{ justifyContent: 'center', alignItems: 'center', gap: 2, py: 4 }}
      >
        <CardContainer
          sx={{
            position: 'relative',
            width: CARD_WIDTH,
            '& .str-video__video-preview-container': {
              width: '100%',
              borderRadius: 2,
            },
          }}
        >
          {connectedUser && (
            <>
              <VideoPreview
                NoCameraPreview={() => (
                  <VideoPreviewPlaceholder connectedUser={connectedUser} />
                )}
                StartingCameraPreview={() => (
                  <VideoPreviewPlaceholder connectedUser={connectedUser} />
                )}
                DisabledVideoPreview={() => (
                  <VideoPreviewPlaceholder connectedUser={connectedUser} />
                )}
              />
              <Stack
                sx={{
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  py: 2,
                  px: 2.5,
                  position: 'absolute',
                  bottom: '16px',
                  right: '16px',
                  left: '16px',
                  background:
                    'linear-gradient(180deg, transparent, #00000066, #000000B2)',
                  borderBottomLeftRadius: 16,
                  borderBottomRightRadius: 16,
                }}
              >
                <Stack
                  sx={{ flexDirection: 'row', gap: 0.5, alignItems: 'center' }}
                >
                  {microphoneIsMute && (
                    <Stack
                      sx={{
                        backgroundColor:
                          theme.palette.base?.greyTransparent['900p40'],
                        border: `1px solid ${theme.palette.base?.greyTransparent['900p40']}`,
                        borderRadius: 2,
                        py: 0.5,
                        px: 1,
                      }}
                    >
                      <IconMicrophoneOff
                        size={16}
                        color={theme.palette.new.text.neutral.inverted}
                      />
                    </Stack>
                  )}
                  <Typography
                    variant="globalS"
                    color="new.text.neutral.inverted"
                    fontWeight="fontWeightSemiBold"
                  >
                    {connectedUser?.name} ({t('CALL_YOU')})
                  </Typography>
                </Stack>
                <Stack sx={{ flexDirection: 'row', gap: 2 }}>
                  <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
                  />
                </Stack>
              </Stack>
            </>
          )}
          {!connectedUser && (
            <Stack
              sx={{
                height: '375px',
                background: theme.palette.new.text.neutral.default,
                borderRadius: 2,
                justifyContent: 'center',
              }}
            >
              <Spinner />
            </Stack>
          )}
        </CardContainer>
        <CardContainer
          sx={{ width: CARD_WIDTH, '& .MuiCardContent-root': { p: 0 } }}
        >
          <ListItem
            text={{
              title: t('participants_in_call'),
              description: hasParticipants
                ? participants
                    .map(participant => participant.user.name)
                    .join(', ')
                : t('no_participants'),
            }}
            {...(hasParticipants && {
              sideAvatars: {
                avatars: participants.map(participant => ({
                  alt: participant.user.name,
                  src: participant.user.image,
                })),
              },
            })}
            slotProps={{
              title: {
                slotProps: {
                  description: {
                    sx: {
                      display: '-webkit-box',
                      WebkitBoxOrient: 'vertical',
                      WebkitLineClamp: 1,
                      overflow: 'hidden',
                    },
                  },
                },
              },
            }}
          />
        </CardContainer>
        <Button
          variant="success"
          size="large"
          onClick={joinCall}
          loading={isJoining}
          startIcon={<IconPhone />}
        >
          {t('join')}
        </Button>
      </Stack>
    </LobbyContainer>
  );
};

export default LobbyScreen;
