import { Button } from '@astryxdesign/core/Button'
import type { ReactNode } from 'react'
import { safeHttpUrl } from './safe-url'

type LinkButtonLinkProps = {
  children: ReactNode
  className?: string
  'data-testid'?: string
  href: string | undefined
}

type LinkButtonButtonProps = {
  children: ReactNode
  className?: string
  'data-testid'?: string
  onClick(): void
  disabled?: boolean
  type?: 'button'
}

export type LinkButtonProps = LinkButtonLinkProps | LinkButtonButtonProps

export function LinkButton(props: LinkButtonProps) {
  const label = typeof props.children === 'string' ? props.children : ''

  if ('href' in props) {
    return (
      <Button
        as="a"
        href={safeHttpUrl(props.href)}
        label={label}
        variant="primary"
        className={props.className}
        data-testid={props['data-testid']}
      >
        {props.children}
      </Button>
    )
  }

  return (
    <Button
      type={props.type ?? 'button'}
      label={label}
      variant="primary"
      isDisabled={props.disabled}
      onClick={props.onClick}
      className={props.className}
      data-testid={props['data-testid']}
    >
      {props.children}
    </Button>
  )
}