import React, { FunctionComponent, useMemo } from 'react';
import cn from 'classnames';

import { Tooltip } from '../Tooltip';
import { StyledBtn } from './styled-component';
import { useTheme } from '../Theme';
import { ButtonProps } from './types.d';
import { ActivityIndicator } from '../Activity-Indicator';

export const Button: FunctionComponent<ButtonProps> = ({
  autoFocus,
  className = '',
  color = 'primaryColor',
  customize,
  icon,
  iconPosition = 'left',
  isDisabled = false,
  isLoading,
  mode = 'filled',
  onClick,
  size = 'medium',
  style,
  text,
  tooltip,
}): React.ReactElement => {
  const classNames = cn({
    btn: true,
    [className]: true,
    [mode]: true,
    [size]: true,
    disabled: isDisabled,
  });

  const iconClassNames = cn({
    icon: true,
    icon__right: iconPosition === 'right',
    [size]: true,
  });

  const theme = useTheme();
  const { pallet, text: textColor } = theme;

  const bgColor = customize?.buttonColor ?? pallet[color];

  const sizeNumber = useMemo(
    () =>
      (() => {
        if (typeof size !== 'number') return undefined;
        return size > 24 ? 24 : size;
      })(),
    [size]
  );

  const tColor = useMemo(
    () =>
      customize?.textColor ??
      (color === 'gray' || color === 'gray20' || color === 'white' || color === 'yellow' ? textColor.secondary : textColor.white),
    [color, customize, theme]
  );

  const renderIcon = () => {
    if (!icon && !isLoading) return null;
    return (
      <div className={iconClassNames} style={{ width: sizeNumber, height: sizeNumber }}>
        {isLoading ? <ActivityIndicator customColor={mode === 'filled' ? tColor : bgColor} size={sizeNumber} /> : icon}
      </div>
    );
  };

  return (
    // eslint-disable-next-line react/jsx-props-no-spreading
    <Tooltip {...tooltip}>
      <div>
        <StyledBtn
          $bgColor={bgColor}
          $mode={mode}
          $textColor={tColor}
          autoFocus={autoFocus}
          className={classNames}
          disabled={isDisabled}
          onClick={isDisabled ? undefined : onClick}
          style={{
            alignItems: 'center',
            display: 'flex',
            justifyContent: 'center',
            flexDirection: iconPosition === 'right' ? 'row-reverse' : 'row',
            fontSize: sizeNumber,
            ...style,
          }}
          type="button"
        >
          {renderIcon()}
          {mode !== 'icon-mode' ? <span className="btn__text">{text}</span> : null}
        </StyledBtn>
      </div>
    </Tooltip>
  );
};
