import type { PropsWithChildren } from 'react'
import Link from 'next/link'
import cx from 'classnames'

import { PropsWithClassName } from '@/lib/types'
import { isExternalURL, transformHeadlessURLs } from '@/lib/utilities'

export type Props = PropsWithChildren &
  PropsWithClassName & {
    href?: string
    target?: string
    onClick?(e: any): void
    color?: 'white' | 'dark' | 'blue'
    external?: boolean
    disabled?: boolean
  }

export default function Button({ href, onClick, color, external, disabled = false, className, ...props }: Props) {
  const classNames = cx('btn', `btn--${color}`, className)

  if (href) {
    const isExternal = external ?? isExternalURL(href)
    const Component = isExternal ? 'a' : Link
    return (
      <Component
        href={transformHeadlessURLs(href)}
        className={cx(
          'btn btn--arrow-block font-bold uppercase',
          `btn--arrow-block-${color}`,
          disabled && 'opacity-75 pointer-events-none',
          classNames
        )}
        {...props}
      >
        {props.children}
        <span aria-hidden className={cx('arrow-block', `arrow-block-${color}`)} />
      </Component>
    )
  }

  return (
    <button
      onClick={onClick}
      className={cx(
        'btn btn--arrow-block font-bold uppercase',
        `btn--arrow-block-${color}`,
        disabled && 'opacity-75 pointer-events-none',
        classNames
      )}
      disabled={disabled}
      {...props}
    >
      {props.children}
      <span aria-hidden className={cx('arrow-block', `arrow-block-${color}`)} />
    </button>
  )
}
Button.defaultProps = {
  color: 'dark',
}
