import { useRef } from 'react';

import useVirtualizer from '@material-hu/hooks/useVirtualizer';
import CloseIcon from '@material-hu/icons/material/Close';
import Box from '@material-hu/mui/Box';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import List, { type ListProps } from '@material-hu/mui/List';
import ListItem from '@material-hu/mui/ListItem';
import ListItemButton from '@material-hu/mui/ListItemButton';
import ListItemText from '@material-hu/mui/ListItemText';

import UserAvatar from '@material-hu/components/composed-components/UserAvatar';
import Checkbox from '@material-hu/components/design-system/Checkbox/Checkbox';

import { type User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type InfiniteListProps } from 'src/components/InfiniteList/InfiniteList';

const ROW_ESTIMATE_SIZE = 56;

type Props = {
  users: User[];
  sx?: ListProps['sx'];
  onEndScroll?: () => void;
  checkbox?: {
    usersCount: number;
    selected?: number[];
    disabled?: number[];
    onSelect?: (id: number) => void;
    onSelectAll?: () => void;
    allSelected?: boolean;
    someSelected?: boolean;
  };
  onRemove?: (userId: number) => void;
  showDivider?: boolean;
  showEmployeeInternalId?: boolean;
};

function UsersList({
  users,
  sx,
  checkbox,
  showDivider = false,
  showEmployeeInternalId = false,
  onRemove,
  onEndScroll,
}: Props) {
  const { t } = useLokaliseTranslation('backoffice_only');
  const scrollElementRef = useRef<HTMLDivElement | null>(null);

  const { virtualRows, rowVirtualizer } = useVirtualizer({
    registers: users,
    scrollElementRef,
    virtualizerOptions: {
      count: users.length,
      estimateSize: () => ROW_ESTIMATE_SIZE,
      getScrollElement: () => scrollElementRef.current,
      enabled: users.length > 0,
    },
    fetchNextPage: onEndScroll,
  });

  const ListComponent = (
    checkbox ? ListItemButton : ListItem
  ) as typeof ListItem;

  return (
    <List
      component="div"
      ref={scrollElementRef}
      sx={{ overflow: 'auto', ...sx }}
    >
      {checkbox?.onSelectAll && (
        <ListItem
          onClick={checkbox.onSelectAll}
          sx={{ p: 1, gap: 2 }}
        >
          <Checkbox
            checked={checkbox.allSelected}
            indeterminate={checkbox.someSelected}
            onChange={checkbox.onSelectAll}
          />
          <ListItemText
            primary={t('backoffice_only:users_list.select_all', {
              count: checkbox.usersCount,
            })}
          />
        </ListItem>
      )}
      <Box
        sx={{
          height: rowVirtualizer.getTotalSize(),
          position: 'relative',
        }}
      >
        {virtualRows.map(row => {
          const user = users[row.index];

          return (
            <Box
              key={user.id}
              sx={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: row.size,
                transform: `translateY(${row.start}px)`,
              }}
            >
              <ListComponent
                disabled={checkbox?.disabled?.includes(user.id)}
                onClick={() => checkbox?.onSelect?.(user.id)}
                sx={{ p: 1, gap: 2 }}
              >
                {checkbox && (
                  <Checkbox
                    checked={checkbox.selected?.includes(user.id)}
                    disabled={checkbox.disabled?.includes(user.id)}
                  />
                )}
                <UserAvatar
                  user={user}
                  profileProps={{ showEmployeeInternalId }}
                  sx={{
                    maxWidth: 500,
                    '& .MuiListItem-root': { p: 0 },
                  }}
                />
                {onRemove && (
                  <IconButton onClick={() => onRemove(user.id)}>
                    <CloseIcon fontSize="small" />
                  </IconButton>
                )}
              </ListComponent>
              {showDivider && <Divider />}
            </Box>
          );
        })}
      </Box>
    </List>
  );
}

export default UsersList;
