import React, { forwardRef, memo, useMemo } from 'react';
import clsx from 'clsx';

import MuiButton from '@mui/material/Button';
import MuiTypography from '@mui/material/Typography';

import { CustomIcon } from '../custom-icon';

import type { ButtonProps } from './types';
import createClasses from './styles';

const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(props, ref) {
  const {
    color = 'primary',
    children,
    startIconUrl,
    endIconUrl,
    active,
    size = 'medium',
    changed,
    variant: _variant,
    className,
    clickArea = true,
    customSize,
    onBtnClick,
    ...other
  } = props;

  const classes = createClasses();

  const variant = useMemo(() => (clickArea ? _variant : 'text'), [_variant, clickArea]);

  const isActiveText = useMemo(
    () => active && color === 'third' && size === 'medium' && typeof children === 'string',
    [active, color, size, children]
  );

  const isActiveIcon = useMemo(
    () => active && color === 'third' && typeof children !== 'string',
    [active, color, children]
  );

  const isChangedIcon = useMemo(
    () => changed && color === 'third' && typeof children !== 'string',
    [changed, color, children]
  );

  return (
    <MuiButton
      ref={ref}
      color={color === 'third' ? 'primary' : color}
      className={clsx(
        color === 'third' && classes.third,
        isActiveText && classes.active,
        isActiveIcon && classes.activeIcon,
        isChangedIcon && classes.changed,
        size === 'medium' && variant === 'text' && classes.mediumText,
        !clickArea && classes.noClickArea,
        className
      )}
      onClick={onBtnClick}
      size={size}
      variant={variant}
      startIcon={
        startIconUrl ? (
          <CustomIcon
            color="inherit"
            customSize={customSize}
            src={startIconUrl}
            className={classes.icon}
            data-testid="startIconUrl"
          />
        ) : undefined
      }
      endIcon={
        endIconUrl ? (
          <CustomIcon
            customSize={customSize}
            src={endIconUrl}
            className={classes.icon}
            data-testid="endIconUrl"
          />
        ) : undefined
      }
      data-testid="button"
      {...other}
    >
      <MuiTypography component="span" className={classes.btnTitle}>
        {children}
      </MuiTypography>
    </MuiButton>
  );
});

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