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

import { motion } from 'motion/react';
import Avatar from '@material-hu/mui/Avatar';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import phone1 from 'src/assets/sound/phone1.mp3';
import { useAuth } from 'src/contexts/JWTContext';
import useCallRingtone from 'src/pages/dashboard/videoCall/hooks/useCallRingtone';
import { type Participant } from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CallerSelfView from './CallerSelfView';
import CallControls from './controls/CallControls';

const MotionTypography = motion.create(Typography);

export type CallPreviewProps = {
  participants: Participant[];
};

const CallPreview: FC<CallPreviewProps> = props => {
  const { participants } = props;

  const { t } = useLokaliseTranslation('calls');
  const { user } = useAuth();

  const {
    component: audioComponent,
    playAudio,
    stopAudio,
  } = useCallRingtone({
    src: phone1,
  });

  useEffect(() => {
    playAudio();
    return () => stopAudio();
  }, []);

  const membersWithoutCurrentUser = participants.filter(
    member => member.id !== user?.id,
  );

  return (
    <Stack
      sx={{
        gap: theme => theme.spacing(2),
        alignItems: 'center',
        justifyContent: 'center',
        position: 'relative',
        width: '100%',
        height: '100%',
        backgroundColor: theme => theme.palette.base?.grey[800],
      }}
    >
      {membersWithoutCurrentUser.map(member => (
        <Stack
          key={member.id}
          sx={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
        >
          <Avatar
            src={member.profilePicture ?? ''}
            sx={{
              height: 100,
              width: 100,
            }}
          />
          <Typography
            variant="globalL"
            color="new.text.neutral.inverted"
            sx={{ mt: theme => theme.spacing(1) }}
          >
            {member.name}
          </Typography>
          <MotionTypography
            variant="globalXS"
            color="new.text.neutral.inverted"
            animate={{ opacity: [1, 0.4, 1] }}
            transition={{
              duration: 1.4,
              repeat: Infinity,
              ease: 'easeInOut',
            }}
          >
            {t('CALLING')}
          </MotionTypography>
        </Stack>
      ))}
      <CallerSelfView />
      <CallControls onEndCall={() => window.close()} />
      {audioComponent}
    </Stack>
  );
};

export default CallPreview;
