import {
  type BaseItemProps,
  type BaseListRendererProps,
} from '@composed-components/MenuListItems/types';
import SelectableListItem from '@composed-components/SelectableListItem';
import VirtualizedList, {
  type RowComponentProps,
} from '@composed-components/VirtualizedList';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';

const DefaultList = <ItemType extends BaseItemProps>({
  items,
  selected,
  maxSelection,
  onItemClick,
  disabled,
}: BaseListRendererProps<ItemType>) => {
  return (
    <VirtualizedList
      style={{ maxHeight: '224px', overflow: 'auto' }}
      rowComponent={DefaultRowComponent<ItemType>}
      rowCount={items.length}
      rowHeight={56}
      overscanCount={10}
      rowProps={{
        items,
        selected,
        maxSelection,
        onItemClick,
        disabled:
          disabled ||
          Boolean(
            maxSelection && maxSelection > 1 && selected.size >= maxSelection,
          ),
      }}
    />
  );
};

const DefaultRowComponent = <ItemType extends BaseItemProps>({
  items,
  style,
  index,
  selected,
  maxSelection,
  onItemClick,
  disabled,
}: RowComponentProps<BaseListRendererProps<ItemType>>) => {
  const item = items[index];
  const isSelected = selected?.has(item.id);

  return (
    <Stack
      key={item.id}
      style={style}
    >
      <SelectableListItem
        id={item.id.toString()}
        selected={isSelected || false}
        onSelect={() => onItemClick(item.id)}
        showCheckbox={maxSelection ? maxSelection > 1 : false}
        disabled={!isSelected && disabled}
      >
        <Typography
          variant="globalS"
          sx={{
            fontWeight:
              maxSelection === 1 ? 'fontWeightSemiBold' : 'fontWeightRegular',
          }}
          color={theme => theme.palette.new.text.neutral.default}
        >
          {item.name}
        </Typography>
      </SelectableListItem>
    </Stack>
  );
};

export default DefaultList;
