// @flow
import React, { type ComponentType, forwardRef } from 'react';
import styled from 'styled-components';
import type { TertiaryButtonProps } from './tertiary-button.proptypes';
import { getThemeSpecificStyles } from '../../../mixins/themes';
import {
  commonStyles,
  buttonStyles,
  linkStyles,
} from './tertiary-button.css-rules';
import {
  tradeSpecificButtonStyles,
  tradeSpecificLinkStyles,
} from './tertiary-button.css-rules.trade';
import {
  cryptoSpecificButtonStyles,
  cryptoSpecificLinkStyles,
} from './tertiary-button.css-rules.crypto';
import { Spinner } from '../../feedback-ui/spinner';
import { HideAccessibly } from '../../../primitives/hide-accessibly';

const ActualButton: ComponentType<TertiaryButtonProps> = styled.button.attrs(
  () => ({
    type: 'button',
    bold: 'true',
    fontSize: 'f0',
  }),
)`
  ${commonStyles}
  ${buttonStyles}

  ${getThemeSpecificStyles({
    trade: tradeSpecificButtonStyles,
    crypto: cryptoSpecificButtonStyles,
  })}
`;

const LinkButton: ComponentType<TertiaryButtonProps> = styled.a.attrs(() => ({
  bold: 'true',
  fontSize: 'f0',
}))`
  ${commonStyles}
  ${linkStyles}
  
  ${getThemeSpecificStyles({
    trade: tradeSpecificLinkStyles,
    crypto: cryptoSpecificLinkStyles,
  })}
`;

export const TertiaryButton: ComponentType<TertiaryButtonProps> = forwardRef(
  (
    {
      href,
      target,
      onClick,
      disabled,
      isLoading = false,
      children,
      ...props
    }: TertiaryButtonProps,
    ref,
  ) =>
    href == null ? (
      <ActualButton
        onClick={onClick}
        disabled={disabled || isLoading}
        {...props}
        ref={ref}
      >
        {isLoading ? (
          <>
            <Spinner fontSize="f1" />
            <HideAccessibly>{children}</HideAccessibly>
          </>
        ) : (
          children
        )}
      </ActualButton>
    ) : (
      <LinkButton
        href={!disabled ? href : null}
        disabled={disabled}
        target={target}
        ref={ref}
        {...props}
      >
        {children}
      </LinkButton>
    ),
);

TertiaryButton.displayName = 'TertiaryButton';
