import type { AlertProps as MuiAlertProps } from '@mui/material/Alert';
import MuiAlert from '@mui/material/Alert';
import type { IconButtonProps } from '@mui/material/IconButton';
import IconButton from '@mui/material/IconButton';
import type { ReactNode, SyntheticEvent } from 'react';
import { forwardRef, memo } from 'react';
import { ASSETS_URL } from '../../../consts/common';
import { CustomIcon } from '../../custom-icon';
import createClasses from './style';

export interface AlertProps extends Omit<MuiAlertProps, 'children' | 'onClose'> {
  /**
   * The content of the alert.
   */
  children?: ReactNode;
  /**
   * The action to display. It renders after the message, at the end of the alert.
   */
  action?: ReactNode;
  /**
   * Callback fired when the component requests to be closed.
   * When provided, a close icon button is displayed that triggers the callback when clicked.
   * @param {SyntheticEvent} event The event source of the callback.
   */
  onClose?: IconButtonProps['onClick'];
}

const Alert = forwardRef<HTMLDivElement, AlertProps>((props: AlertProps, ref) => {
  const { action, children, onClose, ...other } = props;
  const classes = createClasses();
  return (
    <MuiAlert
      className={classes.root}
      role="alert"
      action={
        <>
          {action}
          {onClose && (
            <IconButton
              className={classes.icon}
              size="small"
              aria-label="Close"
              title="Close"
              color="inherit"
              onClick={onClose}
            >
              <CustomIcon color="inherit" src={`${ASSETS_URL}/icons/icon_close.svg`} />
            </IconButton>
          )}
        </>
      }
      ref={ref}
      {...other}
    >
      {children}
    </MuiAlert>
  );
});

Alert.defaultProps = {
  variant: 'outlined',
  severity: 'info'
};

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