// @flow
import React, { forwardRef, type ComponentType } from 'react';
import styled from 'styled-components';
import type { UnstyledButtonProps } from './unstyled-button.proptypes';
import { commonStyles } from './unstyled-button.css-rules';

export const ActualUnstyledButton: ComponentType<UnstyledButtonProps> = styled.button.attrs(
  ({ type = 'button', role = 'button' }) => ({
    type,
    role,
  }),
)`
  ${commonStyles}
`;

export const UnstyledLink = styled.a.attrs(({ target }) =>
  target?.length ? { rel: 'noreferrer noopener' } : {},
)`
  ${commonStyles}
  display: inline-block;
  &,
  &:hover {
    text-decoration: none;
  }
`;

export const UnstyledButton: ComponentType<UnstyledButtonProps> = forwardRef(
  ({ href, target, onClick, type, ...props }: UnstyledButtonProps, ref) =>
    href == null ? (
      <ActualUnstyledButton
        onClick={onClick}
        type={type}
        {...props}
        ref={ref}
      />
    ) : (
      <UnstyledLink
        href={href}
        target={target}
        onClick={onClick}
        {...props}
        ref={ref}
      />
    ),
);
