import { Button as PerformativeButton, type ButtonSize } from 'performative-ui'
import { Link, type LinkProps } from 'react-router-dom'
import type { AnchorHTMLAttributes, ButtonHTMLAttributes, ReactNode } from 'react'

type HyperTwistButtonTone = 'primary' | 'secondary' | 'ghost'

function resolvePerformativeVariant(tone: HyperTwistButtonTone) {
  if (tone === 'primary') return 'glow'
  if (tone === 'secondary') return 'wave'
  return 'ghost'
}

function buildClassName({
  tone,
  full,
  className,
}: {
  tone: HyperTwistButtonTone
  full?: boolean
  className?: string
}) {
  return [
    'button',
    `button--${tone}`,
    full ? 'button--full' : '',
    className || '',
  ].filter(Boolean).join(' ')
}

export function HyperTwistButtonLink({
  to,
  tone = 'primary',
  size = 'md',
  full,
  className,
  children,
  ...props
}: Omit<LinkProps, 'to'> & {
  to: LinkProps['to']
  tone?: HyperTwistButtonTone
  size?: ButtonSize
  full?: boolean
  children: ReactNode
}) {
  return (
    <PerformativeButton
      as={Link}
      to={to}
      size={size}
      variant={resolvePerformativeVariant(tone)}
      sparkle={tone === 'primary'}
      block={full}
      className={buildClassName({ tone, full, className })}
      {...props}
    >
      {children}
    </PerformativeButton>
  )
}

export function HyperTwistButton({
  tone = 'primary',
  size = 'md',
  full,
  className,
  children,
  ...props
}: ButtonHTMLAttributes<HTMLButtonElement> & {
  tone?: HyperTwistButtonTone
  size?: ButtonSize
  full?: boolean
  children: ReactNode
}) {
  return (
    <PerformativeButton
      as="button"
      size={size}
      variant={resolvePerformativeVariant(tone)}
      sparkle={tone === 'primary'}
      block={full}
      className={buildClassName({ tone, full, className })}
      {...props}
    >
      {children}
    </PerformativeButton>
  )
}

export function HyperTwistButtonAnchor({
  href,
  tone = 'primary',
  size = 'md',
  full,
  className,
  children,
  ...props
}: AnchorHTMLAttributes<HTMLAnchorElement> & {
  href: string
  tone?: HyperTwistButtonTone
  size?: ButtonSize
  full?: boolean
  children: ReactNode
}) {
  return (
    <PerformativeButton
      as="a"
      href={href}
      size={size}
      variant={resolvePerformativeVariant(tone)}
      sparkle={tone === 'primary'}
      block={full}
      className={buildClassName({ tone, full, className })}
      {...props}
    >
      {children}
    </PerformativeButton>
  )
}
