import React, { PropsWithChildren } from 'react';

import ButtonUnstyled from '@mui/base/ButtonUnstyled';
import { StyledEngineProvider } from '@mui/material/styles';

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

import { BUTTON_SIZE, BUTTON_TYPE, IButtonProps } from './types';
import DotTypeLoader from './DotTypeLoader';
import { THEME } from '../../constants'; // TODO: finish config Rollup to work properly with absolute path
import { getIconSize } from './helpers';

import styles from './button.scss';

export const buttonClassName = bem(styles, 'button');

export const Button = React.forwardRef<HTMLButtonElement, PropsWithChildren<IButtonProps>>(function Button(
  {
    type = BUTTON_TYPE.primary,
    size = BUTTON_SIZE.medium,
    theme = THEME.dark,
    caption,
    icon,
    onClick,
    className,
    disabled = false,
    children,
    isLoading = false,
    noPadding = false,
    ...attributes
  },
  ref,
) {
  const renderContent = (): JSX.Element => {
    if (!caption && !icon) {
      return <>{children}</>;
    }
    return (
      <div className={buttonClassName('caption')}>
        {icon && (
          <Icon
            name={icon}
            size={getIconSize(size)}
          />
        )}
        {caption && (
          <Typography
            theme={theme}
            className={buttonClassName('caption-text', { withIcon: Boolean(icon), disabled })}
            type={TYPOGRAPHY_TYPE.subtitle3}
          >
            {caption}
          </Typography>
        )}
      </div>
    );
  };

  return (
    <StyledEngineProvider injectFirst>
      <ButtonUnstyled
        ref={ref}
        disabled={disabled || isLoading}
        onClick={onClick}
        className={buttonClassName(
          '',
          {
            [type]: true,
            [theme]: true,
            [size]: true,
            withLoader: isLoading,
            noPadding,
          },
          className,
        )}
        {...attributes}
      >
        {isLoading ? <DotTypeLoader /> : renderContent()}
      </ButtonUnstyled>
    </StyledEngineProvider>
  );
});
