import React from 'react'
import styled from 'styled-components'
import { th } from '@pubsweet/ui-toolkit'
import { Action, Icon } from '@pubsweet/ui'

import { paddingHelper } from './styledHelpers'

const ActionLink = ({
  to,
  icon,
  size,
  onClick,
  disabled,
  children,
  iconSize = 2,
  iconPosition = 'left',
  ...rest
}) => (
  <Root {...rest} to={to}>
    {icon &&
      iconPosition === 'left' && (
        <Icon onClick={onClick} secondary={to} size={iconSize} warning={!to}>
          {icon}
        </Icon>
      )}
    {to ? (
      <ExternalLink href={to} target="_blank">
        {children}
      </ExternalLink>
    ) : (
      <Action disabled={disabled} onClick={onClick} size={size}>
        {children}
      </Action>
    )}
    {icon &&
      iconPosition === 'right' && (
        <Icon onClick={onClick} secondary={to} size={iconSize} warning={!to}>
          {icon}
        </Icon>
      )}
  </Root>
)

export default ActionLink

// #region styles
const ExternalLink = styled.a`
  color: ${th('colorSecondary')};
  font-family: ${th('fontReading')};
  text-decoration: underline;

  &:hover {
    color: ${th('colorSecondary')};
    font-family: ${th('fontReading')};
    text-decoration: underline;
  }
`

const Root = styled.div`
  align-items: center;
  display: ${props => (props.to ? 'inline-flex' : 'flex')};
  ${paddingHelper};

  height: max-content;
  width: max-content;
`
// #endregion