// @flow
import React, { forwardRef, type ComponentType } from 'react';
import styled from 'styled-components';
import type { SecondaryButtonProps } from './secondary-button.proptypes';
import {
  commonStyles,
  linkStyles,
  buttonStyles,
} from './secondary-button.css-rules';
import { Spinner } from '../../feedback-ui/spinner';
import { HideAccessibly } from '../../../primitives/hide-accessibly';

const ActualButton = styled.button.attrs((props) => ({
  type: props.type || 'button',
  bold: 'true',
}))`
  ${commonStyles}
  ${buttonStyles}
`;

const LinkButton = styled.a.attrs(() => ({
  bold: 'true',
}))`
  ${commonStyles}
  ${linkStyles}
`;

export const SecondaryButton: ComponentType<SecondaryButtonProps> = forwardRef(
  (
    { children, disabled, isLoading = false, ...props }: SecondaryButtonProps,
    ref,
  ) => {
    return props.href === undefined ? (
      <ActualButton
        {...props}
        isLoading={isLoading}
        disabled={disabled || isLoading}
        ref={ref}
      >
        {isLoading ? (
          <>
            <Spinner />
            <HideAccessibly>{children}</HideAccessibly>
          </>
        ) : (
          children
        )}
      </ActualButton>
    ) : (
      <LinkButton {...props} ref={ref}>
        {children}
      </LinkButton>
    );
  },
);

SecondaryButton.displayName = 'SecondaryButton';
