// @flow
import React, { forwardRef, type ComponentType } from 'react';
import styled from 'styled-components';
import type { ButtonProps } from './button.proptypes';
import { getThemeSpecificStyles } from '../../../mixins/themes';
import { commonButtonStyles, commonLinkStyles } from './button.css-rules';
import { Spinner } from '../../feedback-ui/spinner';
import {
  investSpecificButtonStyles,
  investSpecificLinkStyles,
} from './button.css-rules.invest';
import { HideAccessibly } from '../../../primitives/hide-accessibly';

const ActualButton = styled.button.attrs((props) => ({
  type: props.type || 'button',
  bold: 'true',
}))`
  ${commonButtonStyles}
  ${getThemeSpecificStyles({ wealthsimple: investSpecificButtonStyles })}
`;

const LinkButton = styled.a.attrs(() => ({
  bold: 'true',
}))`
  ${commonLinkStyles}
  ${getThemeSpecificStyles({ wealthsimple: investSpecificLinkStyles })}
`;

export const Button: ComponentType<ButtonProps> = forwardRef(
  (
    {
      href,
      target,
      onClick,
      type,
      isLoading = false,
      disabled,
      children,
      size,
      ...props
    }: ButtonProps,
    ref,
  ) =>
    href == null ? (
      <ActualButton
        onClick={onClick}
        type={type}
        size={size}
        {...props}
        ref={ref}
        disabled={disabled || isLoading}
        isLoading={isLoading}
      >
        {isLoading ? (
          <>
            <Spinner fontSize={size === 'md' ? 'f3' : 'f2'} />
            <HideAccessibly>{children}</HideAccessibly>
          </>
        ) : (
          children
        )}
      </ActualButton>
    ) : (
      <LinkButton
        href={href}
        target={target}
        onClick={onClick}
        size={size}
        {...props}
        ref={ref}
      >
        {children}
      </LinkButton>
    ),
);

Button.displayName = 'Button';
