import { type RowComponentProps } from 'react-window';

import SelectableListItem, {
  type SelectableListItemProps,
} from '@composed-components/SelectableListItem';
import Stack from '@mui/material/Stack/Stack';
import Typography from '@mui/material/Typography';

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

export type CollapsibleAutocompleteSelectorItemProps<T = unknown> = {
  items: T[];
  displayItems: FieldOption[];
  selectedCount: number;
  selectionLimit: number;
  getItemId: (item: T) => string | number;
  isItemSelected: (item: T) => boolean;
  handleOptionCheck: (item: T) => void;
  itemRenderer?: (item: T, displayOption: FieldOption) => React.ReactNode;
} & Omit<
  SelectableListItemProps,
  'id' | 'onSelect' | 'selected' | 'disabled' | 'children'
>;

const CollapsibleAutocompleteSelectorItem = <T,>({
  handleOptionCheck,
  index,
  items,
  displayItems,
  selectedCount,
  selectionLimit,
  getItemId,
  isItemSelected,
  style,
  itemRenderer,
  ...props
}: RowComponentProps<CollapsibleAutocompleteSelectorItemProps<T>>) => {
  const item = items[index];
  const displayOption = displayItems[index];
  const itemId = getItemId(item);
  const isSelected = isItemSelected(item);

  return (
    <Stack style={style}>
      <SelectableListItem
        key={String(itemId)}
        id={String(itemId)}
        sx={{ padding: 2, borderRadius: 1 }}
        onSelect={() => handleOptionCheck(item)}
        disabled={
          !!selectionLimit && !isSelected && selectedCount >= selectionLimit
        }
        selected={isSelected}
        {...props}
      >
        {itemRenderer ? (
          itemRenderer(item, displayOption)
        ) : (
          <Typography
            sx={{
              fontWeight: 'medium',
              color: theme => theme.palette.new.text.neutral.default,
              ml: 0.5,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {displayOption.name}
          </Typography>
        )}
      </SelectableListItem>
    </Stack>
  );
};

export default CollapsibleAutocompleteSelectorItem;
