import { type FC, useEffect, useRef } from 'react';
import { useFormContext } from 'react-hook-form';

import { IconX } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { alpha, type Theme, useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { BUNNY_IMAGE_CLASSES } from 'src/pages/dashboard/Conversations/constants';
import { type Member } from 'src/pages/dashboard/Conversations/types';
import { getInitials } from 'src/utils/userUtils';

import LazySecureImage from '../shared/LazySecureImage';

const MAX_MEMBERS = 5;
const ShowSelectedMembers: FC = () => {
  const { setValue, watch } = useFormContext();
  const theme = useTheme();
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const previousUsersLength = useRef<number>(0);

  const users = watch('users') as Member[];

  useEffect(() => {
    const currentLength = users.length;
    const isAddingMember = currentLength > previousUsersLength.current;

    if (
      isAddingMember &&
      currentLength > MAX_MEMBERS &&
      scrollContainerRef.current
    ) {
      scrollContainerRef.current.scrollLeft =
        scrollContainerRef.current.scrollWidth;
    }

    previousUsersLength.current = currentLength;
  }, [users]);

  const handleOnClick = (member: Member) => {
    const newArray = users.filter(elem => elem.id !== member.id);
    setValue('users', [...newArray]);
  };

  return (
    <Stack
      sx={{
        position: 'relative',
        px: 2,
      }}
    >
      {users.length > MAX_MEMBERS && (
        <Box
          sx={{
            position: 'absolute',
            left: 0,
            top: 0,
            bottom: 0,
            width: 40,
            background:
              'linear-gradient(to right, rgba(255, 255, 255, 0.6), rgba(255, 255, 255, 0.2))',
            zIndex: 10,
            pointerEvents: 'none',
          }}
        />
      )}
      <Stack
        ref={scrollContainerRef}
        sx={{
          gap: 2,
          flexDirection: 'row',
          pt: 2,
          overflowX: 'scroll',
          minHeight: '110px',
          '::-webkit-scrollbar': {
            height: '0px',
            background: 'transparent',
          },
          '::-webkit-scrollbar-thumb': {
            borderRadius: '0px',
            backgroundColor: 'transparent',
          },
          '::-webkit-scrollbar-track': {
            background: 'transparent',
          },
        }}
      >
        {users.map(member => (
          <Stack
            key={member.id}
            sx={{
              alignItems: 'center',
              justifyContent: 'flex-start',
              gap: 0.5,
              width: 50,
            }}
          >
            <Stack sx={{ position: 'relative' }}>
              <IconButton
                size="small"
                onClick={() => handleOnClick(member)}
                sx={{
                  backgroundColor:
                    theme.palette.new.action.button.background.tertiary,
                  position: 'absolute',
                  zIndex: 1,
                  top: -12,
                  right: -12,
                }}
                variant="tertiary"
              >
                <IconX color={theme.palette.new.text.neutral.default} />
              </IconButton>
              <LazySecureImage
                url={member.picture_asset_url}
                isAvatar
                imageClass={BUNNY_IMAGE_CLASSES.AVATAR}
                avatarProps={{
                  text: getInitials(`${member.first_name} ${member.last_name}`),
                }}
              />
            </Stack>
            <Typography
              variant="globalXXS"
              sx={{
                textAlign: 'center',
                width: '100%',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
              }}
            >
              {member.first_name}
            </Typography>
          </Stack>
        ))}
      </Stack>
    </Stack>
  );
};

export default ShowSelectedMembers;
