import React, { MouseEvent } from 'react';

import MaterialChip from '@mui/material/Chip';
import { StyledEngineProvider } from '@mui/material/styles';

import { bem } from 'utils/bem';
import { Typography, TYPOGRAPHY_TYPE } from 'components/Typography';
import { Icon, ICON_SIZE } from 'components/Icon/Icon';

import { THEME } from '../../constants'; // TODO: finish config Rollup to work properly with absolute path

import styles from './chip.scss';

export const chipClassName = bem(styles, 'chip');

export enum CHIP_TYPE {
  regular = 'regular',
  compact = 'compact',
}

export interface IChipProps {
  label: string;
  type?: CHIP_TYPE;
  theme?: THEME;
  deleteIcon?: string;
  className?: string;
  disabled?: boolean;
  onClick?: (event: MouseEvent<HTMLElement>) => void;
  onDelete?: (event: MouseEvent<HTMLElement>) => void;
  dataAttributes?: Record<`data-${string}`, string>;
}

const CHIP_TYPE_TO_TYPOGRAPHY: Record<CHIP_TYPE, TYPOGRAPHY_TYPE> = {
  [CHIP_TYPE.regular]: TYPOGRAPHY_TYPE.body2,
  [CHIP_TYPE.compact]: TYPOGRAPHY_TYPE.body4,
};

export const Chip: React.FC<IChipProps> = ({
  label,
  type = CHIP_TYPE.regular,
  theme = THEME.dark,
  deleteIcon = 'cross',
  className,
  disabled = false,
  onClick,
  onDelete,
  dataAttributes,
}) => {
  const handleDelete = !disabled ? onDelete : undefined;

  return (
    <StyledEngineProvider injectFirst>
      <MaterialChip
        {...dataAttributes}
        disabled={disabled}
        className={chipClassName('', { [type]: true, [theme]: true, isDisabled: disabled }, className)}
        label={<Typography type={CHIP_TYPE_TO_TYPOGRAPHY[type]}>{label}</Typography>}
        clickable={!disabled}
        deleteIcon={
          <div>
            <Icon
              name={deleteIcon}
              size={ICON_SIZE.small}
            />
          </div>
        }
        onClick={onClick}
        onDelete={handleDelete}
        classes={{
          deleteIcon: chipClassName('delete-icon'),
          label: chipClassName('label'),
        }}
      />
    </StyledEngineProvider>
  );
};
