import { MouseEventHandler, ReactNode } from 'react'
import styled from 'styled-components'
import { Button } from './button.js'
import { Copy } from './copy.js'
import { Icon } from './icon.js'
import { IconName } from './icons/index.js'

import { Theme } from './theme.js'

export const HelperIcon = styled(Icon)`
  max-width: 16px;
  max-height: 16px;
  fill: ${({ theme }) => theme.navNeutral400};
`

export const HelperDescription = styled(Copy).attrs(() => ({ size: 'sm', bold: true }))`
  color: inherit;
`
const getHelperItemColor = (theme: Theme, isLink: boolean | undefined) => {
  return !isLink && theme.navNeutral400
}
export const HelperItem = styled.div.attrs<{ isLink?: boolean }>(
  ({ isLink }) => isLink && { as: Button, variation: 'buttonLink', type: 'button' }
)<{ isLink?: boolean; hasSpaceForErrors?: boolean }>`
  display: grid;
  padding-top: 4px;
  grid-template-columns: min-content 1fr;
  grid-gap: 4px;
  text-align: left;
  ${({ hasSpaceForErrors }) => (hasSpaceForErrors ? 'min-height: 18px;' : '')}
  color: ${({ theme, isLink }) => getHelperItemColor(theme, isLink)}
`

type HelperProps = {
  className?: string
  hasSpaceForErrors?: boolean
  helperText: ReactNode
  iconName?: IconName
  helperLinkAction?: MouseEventHandler<HTMLDivElement>
}

/**
 * Helper is a tooltip component
 *
 * @returns ReactElement
 */
const _Helper = ({
  className,
  hasSpaceForErrors,
  helperLinkAction,
  helperText,
  iconName = 'actions/circle-faq',
}: HelperProps) => (
  <HelperItem
    className={className}
    isLink={!!helperLinkAction}
    onClick={helperLinkAction}
    hasSpaceForErrors={hasSpaceForErrors}
  >
    {iconName && <HelperIcon name={iconName} />}
    <HelperDescription data-testid={`input:helper-text:${helperText}`} light>
      {helperText}
    </HelperDescription>
  </HelperItem>
)

export const Helper = styled(_Helper)``
