/**
 * BoostMedia AI Content Generator Admin - Button Component
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { forwardRef } from 'react'
import type { ButtonHTMLAttributes, ReactNode } from 'react'
import { Loader2 } from 'lucide-react'

type ButtonVariant = 'primary' | 'secondary' | 'accent' | 'ghost' | 'danger'
type ButtonSize = 'sm' | 'md' | 'lg'

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: ButtonVariant
  size?: ButtonSize
  loading?: boolean
  icon?: ReactNode
  iconPosition?: 'start' | 'end'
  children: ReactNode
}

const variantClasses: Record<ButtonVariant, string> = {
  primary: 'bg-bc-primary text-white hover:bg-bc-primary-dark disabled:bg-bc-gray-300',
  secondary: 'bg-transparent text-bc-primary border-2 border-bc-primary hover:bg-bc-primary-light disabled:border-bc-gray-300 disabled:text-bc-gray-300',
  accent: 'bg-bc-accent text-white hover:bg-bc-accent-dark disabled:bg-bc-gray-300',
  ghost: 'bg-transparent text-bc-gray-600 hover:bg-bc-gray-100 disabled:text-bc-gray-300',
  danger: 'bg-bc-error text-white hover:bg-red-600 disabled:bg-bc-gray-300',
}

const sizeClasses: Record<ButtonSize, string> = {
  sm: 'px-3 py-1.5 text-sm',
  md: 'px-4 py-2.5 text-base',
  lg: 'px-6 py-3 text-lg',
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  (
    {
      variant = 'primary',
      size = 'md',
      loading = false,
      icon,
      iconPosition = 'start',
      children,
      className = '',
      disabled,
      ...props
    },
    ref
  ) => {
    const iconEl = loading ? (
      <Loader2 className="w-5 h-5 animate-spin" />
    ) : icon ? (
      <span className="shrink-0">{icon}</span>
    ) : null

    return (
      <button
        ref={ref}
        className={`
          inline-flex items-center justify-center gap-2
          font-semibold rounded-bc
          transition-all duration-200
          bc-focus-visible
          ${variantClasses[variant]}
          ${sizeClasses[size]}
          ${loading || disabled ? 'cursor-not-allowed opacity-70' : ''}
          ${className}
        `}
        disabled={loading || disabled}
        {...props}
      >
        {iconPosition === 'start' && iconEl}
        <span>{children}</span>
        {iconPosition === 'end' && iconEl}
      </button>
    )
  }
)

Button.displayName = 'Button'

