import { Button as ButtonRAC } from 'react-aria-components'
import { Loading, type LoadingProps } from '../Loading/Loading'

import type { ButtonProps } from './types'
import { variants } from './variants'

export function Button({
  variant,
  color,
  size,
  wrapping,
  fullWidth,
  typography,
  className,
  children,
  ...props
}: ButtonProps) {
  const classNames = variants({
    variant,
    color,
    size,
    wrapping,
    typography,
    fullWidth,
    className,
  })

  return (
    <ButtonRAC {...props} className={classNames}>
      {({ isPending, isHovered }) => {
        let loadingType: LoadingProps['type'] = 'White'
        if (variant === 'Secondary') {
          if (isHovered || color !== 'Inverted') {
            loadingType = 'Dark'
          }
        } else {
          if (color === 'Inverted') {
            loadingType = 'Dark'
          }
        }

        return (
          <>
            {children}
            {isPending && <Loading size={20} type={loadingType} />}
          </>
        )
      }}
    </ButtonRAC>
  )
}
