import { memo } from 'react';
import clsx from 'clsx';

import MuiDialogTitle from '@mui/material/DialogTitle';
import type { DialogTitleProps as MuiDialogTitleProps } from '@mui/material/DialogTitle';
import Grid from '@mui/material/Grid';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import makeStyles from '@mui/styles/makeStyles';

import { ASSETS_URL } from '../../../consts/common';
import { CustomIcon } from '../../custom-icon';
import type { CustomIconProps } from '../../custom-icon';
import type { Theme } from '../../@styles/theme-provider';

export interface DialogTitleProps extends MuiDialogTitleProps {
  /**
   * Icon to be displayed before the title.
   */
  icon?: CustomIconProps;
  /**
   * Callback to be fired on close icon click.
   */
  onClose?: () => void;
}

const createClasses = makeStyles<Theme>(theme => ({
  root: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'start',
    '& .MuiIconButton-root': {
      padding: 0
    }
  },
  mainIconContainer: {
    backgroundColor: theme.palette.common.white,
    border: `${theme.spacing(1)} solid ${theme.palette.secondary[100]}`,
    borderRadius: '50%',
    color: theme.palette.primary[400],
    width: 64,
    height: 64,
    marginBottom: theme.spacing(3)
  },
  closeIcon: {
    color: theme.palette.primary[400]
  }
}));

const DialogTitle = (props: DialogTitleProps) => {
  const { icon, onClose, children, classes, ...other } = props;

  const styles = createClasses();

  return (
    <MuiDialogTitle
      classes={{
        root: clsx(classes?.root, styles.root)
      }}
      {...other}
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      component="div"
    >
      <Typography variant="h3">
        {icon?.src && (
          <Grid
            container
            alignItems="center"
            justifyContent="center"
            className={styles.mainIconContainer}
          >
            <CustomIcon color="inherit" size="large" {...icon} />
          </Grid>
        )}
        {children}
      </Typography>
      {onClose ? (
        <IconButton size="small" data-testid="close" aria-label="close" onClick={onClose}>
          <CustomIcon
            color="inherit"
            src={`${ASSETS_URL}/icons/icon_close.svg`}
            className={styles.closeIcon}
          />
        </IconButton>
      ) : null}
    </MuiDialogTitle>
  );
};

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