import React, { MouseEvent } from 'react';

import ListItem from '@mui/material/ListItem';
import { StyledEngineProvider } from '@mui/material/styles';
import ListItemText from '@mui/material/ListItemText';

import { bem } from 'utils/bem';
import { Button, BUTTON_SIZE, BUTTON_TYPE } from 'components/Button';

import { THEME } from '../../constants';
import { SECONDARY_ACTION_ID } from './constants';

import styles from './simple-list-item.scss';

const simpleListItemClassName = bem(styles, 'simple-list-item');

export interface ISimpleListItem {
  label: string;
  theme?: THEME;
  actionIcon?: string;
  className?: string;
  onClick?: (event: MouseEvent<HTMLElement>) => void;
  onActionClick?: (event: MouseEvent<HTMLElement>) => void;
  dataAttributes?: Record<`data-${string}`, string>;
}

export const SimpleListItem: React.FC<ISimpleListItem> = ({
  label,
  theme = THEME.light,
  actionIcon = 'delete-outline',
  className,
  onClick,
  onActionClick,
  dataAttributes,
}) => {
  const handleClick = (event: MouseEvent<HTMLElement>): void => {
    if (event.target instanceof HTMLElement) {
      if (event.target.dataset.id === SECONDARY_ACTION_ID) {
        onActionClick?.(event);
      } else {
        onClick?.(event);
      }
    }
  };

  const secondaryAction = onActionClick ? (
    <Button
      type={BUTTON_TYPE.tertiary}
      size={BUTTON_SIZE.smallRound}
      theme={theme}
      icon={actionIcon}
      data-id={SECONDARY_ACTION_ID}
      className={simpleListItemClassName('secondary-action')}
    />
  ) : undefined;

  return (
    <StyledEngineProvider injectFirst>
      <ListItem
        {...dataAttributes}
        component="div"
        className={simpleListItemClassName(null, { [theme]: true }, className)}
        onClick={handleClick}
        secondaryAction={secondaryAction}
      >
        <ListItemText primary={label} />
      </ListItem>
    </StyledEngineProvider>
  );
};
