import { memo } from 'react';

import { type VirtualItem, type Virtualizer } from '@tanstack/react-virtual';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import ListItem from '@material-hu/components/design-system/List/components/ListItem';

import { getFullName, getInitials } from 'src/utils/userUtils';

import { type RankingUser } from '../../types';

type RankingListItemProps = {
  virtualRow: VirtualItem;
  user: RankingUser;
  showDivider: boolean;
  onClickUser: (userId: number) => void;
  measureElement: Virtualizer<HTMLElement, Element>['measureElement'];
};

export const RankingListItem = memo((props: RankingListItemProps) => {
  const { virtualRow, user, showDivider, onClickUser, measureElement } = props;

  const fullName = getFullName({
    firstName: user.userFirstName,
    lastName: user.userLastName,
  });

  return (
    <Stack
      data-index={virtualRow.index}
      ref={measureElement}
      onClick={() => onClickUser(user.userId)}
      sx={{
        cursor: 'pointer',
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        transform: `translateY(${virtualRow.start}px)`,
      }}
    >
      <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
        <Typography
          fontWeight="fontWeightSemiBold"
          sx={{ minWidth: 32, textAlign: 'center', flexShrink: 0 }}
        >
          {virtualRow.index + 1}
        </Typography>
        <Stack sx={{ flex: 1, minWidth: 0 }}>
          <ListItem
            text={{ title: fullName }}
            slotProps={{
              container: { sx: { p: 1.5 } },
              title: { slotProps: { title: { sx: { maxWidth: '90%' } } } },
            }}
            sideText={{ title: String(user.points) }}
            avatar={{
              src: user.userProfilePicture || undefined,
              alt: fullName,
              text: getInitials(fullName),
            }}
          />
        </Stack>
      </Stack>
      {showDivider && <Divider sx={{ mx: 1.5 }} />}
    </Stack>
  );
});
