import styled from 'styled-components'

import { StyledButton } from './button'
import Icon from './icon'
import type { VariationKey } from './button'
import { InferComponentProps } from './types.js'
import isRebrand from './is-rebrand'
import { forwardRef } from 'react'

const getIconName = (name: string) => {
  const nameArr = name.split('/')
  return nameArr[nameArr.length - 1]
}

type IconButtonProps = {
  variation?: VariationKey
  buttonAriaLabel?: string
} & Omit<InferComponentProps<typeof StyledButton>, 'size'> &
  InferComponentProps<typeof Icon>

const StyleOverrideButton = styled(StyledButton)`
  padding: 0;
  height: ${({ variation }) => (variation === 'buttonLink' ? '24px' : '32px')};
  width: ${({ variation }) => (variation === 'buttonLink' ? '24px' : '32px')};
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 0;
  border-radius: ${({ variation }) => (variation === 'buttonLink' ? '2px' : '50%')};

  ${({ variation, theme }) => {
    if (variation === 'buttonLink') {
      return `
        &:focus {
          box-shadow: ${
            isRebrand(theme) ? `0 0 0 4px ${theme.navStatusPositive500}` : `0 0 0 3px ${theme.navPrimary700}`
          };
        }
      `
    }
    return ``
  }}
`

/** Pass all event handler props to a wrapper button to avoid rerendering the icon and causing flicker */
const IconButton = forwardRef(
  ({ variation = 'buttonLink', buttonAriaLabel, className, name, color, size, ...props }: IconButtonProps, ref) => {
    return (
      <StyleOverrideButton
        className={className}
        variation={variation}
        data-testid="icon-button"
        aria-label={buttonAriaLabel || `${getIconName(name)} icon button`}
        {...props}
        ref={ref}
      >
        <Icon name={name} color={color} size={size} />
      </StyleOverrideButton>
    )
  }
)

export const InteractiveIcon = styled(IconButton)``

export default styled(IconButton)``
