import { FC, useRef, useState, useEffect, useLayoutEffect } from 'react';

import { IconX } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { styled } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';

import { Participant } from 'src/types/stream';
import { getInitials } from 'src/utils/userUtils';

type GradientDirection = 'left' | 'right';

type GradientShadowProps = {
  gradientDirection: GradientDirection;
  isVisible: boolean;
};

const GradientShadow = styled(Stack, {
  shouldForwardProp: prop =>
    !['gradientDirection', 'isVisible'].includes(prop.toString()),
})<GradientShadowProps>(({ gradientDirection, isVisible }) => ({
  position: 'absolute',
  top: 0,
  bottom: 0,
  width: '90px',
  background: `linear-gradient(to ${gradientDirection === 'left' ? 'right' : 'left'}, rgba(255,255,255,1), rgba(255,255,255,0.2))`,
  pointerEvents: 'none',
  zIndex: 1,
  opacity: isVisible ? 1 : 0,
  transition: 'opacity 0.2s ease-in-out',
  ...(gradientDirection === 'left' ? { left: 0 } : { right: 0 }),
}));

type SelectedParticipantsProps = {
  selectedParticipants: Participant[];
  setSelectedParticipants: (value: Participant[]) => void;
};

const SelectedParticipants: FC<SelectedParticipantsProps> = (
  props: SelectedParticipantsProps,
) => {
  const { selectedParticipants, setSelectedParticipants } = props;
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);
  const [previousParticipantCount, setPreviousParticipantCount] = useState(
    selectedParticipants.length,
  );

  const checkScrollability = () => {
    const element = scrollContainerRef.current;
    if (element) {
      setCanScrollLeft(element.scrollLeft > 0);

      setCanScrollRight(
        element.scrollWidth > element.clientWidth &&
          element.scrollLeft < element.scrollWidth - element.clientWidth,
      );
    }
  };

  const handleAutoScroll = () => {
    const element = scrollContainerRef.current;
    const currentCount = selectedParticipants.length;

    if (element && currentCount > previousParticipantCount) {
      element.scrollLeft = element.scrollWidth;
    }

    setPreviousParticipantCount(currentCount);
  };

  useLayoutEffect(() => {
    checkScrollability();
    handleAutoScroll();
  }, [selectedParticipants]);

  useEffect(() => {
    window.addEventListener('resize', checkScrollability);

    return () => {
      window.removeEventListener('resize', checkScrollability);
    };
  }, []);

  const handleOnClick = (participant: Participant) => {
    const newArray = selectedParticipants.filter(
      elem => elem.id !== participant.id,
    );
    setSelectedParticipants([...newArray]);
  };

  return (
    <Stack
      sx={{
        position: 'relative',
        mb: theme => theme.spacing(2),
      }}
    >
      <GradientShadow
        gradientDirection="left"
        isVisible={canScrollLeft}
      />
      <Stack
        ref={scrollContainerRef}
        sx={{
          flexDirection: 'row',
          gap: theme => theme.spacing(1),
          pt: theme => theme.spacing(0.5),
          overflowX: 'scroll',
          '::-webkit-scrollbar': {
            height: '0px',
            background: 'transparent',
          },
          '::-webkit-scrollbar-thumb': {
            borderRadius: '0px',
            backgroundColor: 'transparent',
          },
          '::-webkit-scrollbar-track': {
            background: 'transparent',
          },
        }}
        onScroll={checkScrollability}
      >
        {selectedParticipants.map(participant => (
          <Stack
            key={participant.id}
            sx={{
              alignItems: 'center',
              justifyContent: 'flex-start',
              gap: theme => theme.spacing(0.5),
              minWidth: 76,
            }}
          >
            <Stack sx={{ position: 'relative' }}>
              <IconButton
                size="small"
                onClick={() => handleOnClick(participant)}
                sx={{
                  position: 'absolute',
                  zIndex: 1,
                  top: -4,
                  right: -8,
                  color: theme => theme.palette.new.text.neutral.default,
                }}
                variant="tertiary-filled"
              >
                <IconX />
              </IconButton>
              <HuAvatar
                src={participant.profilePicture || undefined}
                text={getInitials(participant.fullName)}
                size="large"
              />
            </Stack>
            <Typography
              variant="globalXXS"
              sx={{ textAlign: 'center', maxWidth: 76 }}
            >
              {participant.fullName}
            </Typography>
          </Stack>
        ))}
      </Stack>
      <GradientShadow
        gradientDirection="right"
        isVisible={canScrollRight}
      />
    </Stack>
  );
};

export default SelectedParticipants;
