import { useMemo } from 'react';
import { Link as RouterLink } from 'react-router-dom';

import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';

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

import { type Acknowledgement } from 'src/pages/dashboard/acknowledgements/types';
import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { getFullName, getInitials } from 'src/utils/userUtils';

import { USERS_AVATARS_LIMIT } from '../../constants';

type AcknowledgementAvatarsProps = Pick<Acknowledgement, 'acknowledgeds'> & {
  showAcknowledgedsNamesDrawer: () => void;
};

const AcknowledgementAvatars = ({
  acknowledgeds = [],
  showAcknowledgedsNamesDrawer,
}: AcknowledgementAvatarsProps) => {
  const avatarsCount = acknowledgeds?.length || 0;

  const avatars = useMemo(
    () =>
      acknowledgeds?.map(user => ({
        id: user.id,
        src: user.profilePicture || undefined,
        alt: getFullName(user),
        text: getInitials(getFullName(user)),
      })) || [],
    [acknowledgeds],
  );

  const showUniqueAvatar = avatarsCount === 1;
  const showMultipleAvatars =
    avatarsCount > 1 && avatarsCount <= USERS_AVATARS_LIMIT;

  const showDrawerWithAvatars = avatarsCount > USERS_AVATARS_LIMIT;

  return (
    <Stack
      sx={{
        zIndex: 10,
        alignItems: 'center',
        '& .MuiAvatar-root': {
          border: theme =>
            `2px solid ${theme.palette.new.border.neutral.default}`,
          marginTop: -6,
        },
      }}
    >
      {showUniqueAvatar && (
        <Link
          component={RouterLink}
          sx={{ textDecoration: 'none' }}
          to={profileRoutes.profile(avatars[0].id)}
        >
          <Avatar
            size="large"
            src={avatars[0]?.src}
            alt={avatars[0].alt}
            text={avatars[0].text}
          />
        </Link>
      )}
      {showMultipleAvatars && (
        <Stack sx={{ flexDirection: 'row' }}>
          {avatars.map(user => (
            <Link
              key={user.id}
              sx={{ textDecoration: 'none' }}
              component={RouterLink}
              to={profileRoutes.profile(user.id)}
            >
              <Avatar
                sx={{ marginLeft: -1 }}
                key={user.id}
                size="large"
                {...user}
              />
            </Link>
          ))}
        </Stack>
      )}
      {showDrawerWithAvatars && (
        <Stack
          onClick={showAcknowledgedsNamesDrawer}
          style={{ cursor: 'pointer' }}
        >
          <AvatarGroup
            size="large"
            avatars={avatars}
            totalAvatars={avatars?.length}
          />
        </Stack>
      )}
    </Stack>
  );
};

export default AcknowledgementAvatars;
