import { forwardRef, memo, LegacyRef } from 'react';
import MuiTooltip from '@mui/material/Tooltip';
import { TooltipProps as MuiTooltipProps } from '@mui/material/Tooltip';
import { alpha, styled } from '@mui/material/styles';
import type { ClassNameMap } from '@mui/styles/withStyles';
import type { Theme } from '../@styles/theme-provider';

type StyledTextWithBgProps = Pick<TextWithBGProps, 'backgroundColor' | 'color' | 'severity'>;

const StyledTextWithBg = styled('span', {
  label: 'TextWithBG',
  shouldForwardProp: prop => prop !== 'backgroundColor' && prop !== 'color' && prop !== 'severity'
})<StyledTextWithBgProps>(
  ({ backgroundColor, color, severity, theme }: StyledTextWithBgProps & { theme: Theme }) => ({
    ...theme.typography.caption2,
    display: 'block',
    backgroundColor: severity
      ? alpha(theme.palette[severity === 'info' ? 'secondary' : severity][500], 0.16)
      : backgroundColor || theme.palette.primary[300],
    borderRadius: theme.spacing(1),
    color: severity
      ? theme.palette[severity === 'info' ? 'secondary' : severity][500]
      : color || theme.palette.common.white,
    padding: theme.spacing(0, 1),
    width: 'fit-content'
  })
);

export interface TextWithBGProps {
  children?: React.ReactNode;
  backgroundColor?: string;
  color?: string;
  /**
   * Status severity (defines the colors used).
   */
  severity?: 'error' | 'info' | 'success' | 'warning';
  tooltipText?: MuiTooltipProps['title'];
  className?: string;
  /**
   * @deprecated Use `className` instead.
   */
  classes?: Partial<ClassNameMap<'root'>>;
  /**
   * @deprecated Use `children` instead.
   */
  content?: string;
}

const TextWithBG = forwardRef((props: TextWithBGProps, ref: LegacyRef<HTMLSpanElement>) => {
  const { children, className, classes, content, tooltipText, ...otherProps } = props;

  const textWithBG = (
    <StyledTextWithBg ref={ref} {...otherProps} className={classes?.root || className}>
      {content || children}
    </StyledTextWithBg>
  );

  return tooltipText ? (
    <MuiTooltip title={tooltipText} placement="top">
      {textWithBG}
    </MuiTooltip>
  ) : (
    textWithBG
  );
});

const m = memo(TextWithBG);
export { m as TextWithBG };
