import Link from 'next/link';
import { cn } from '@/lib/utils';
import { ButtonHTMLAttributes, forwardRef } from 'react';

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'secondary' | 'gold' | 'ghost';
  size?: 'sm' | 'md' | 'lg';
  href?: string;
  external?: boolean;
}

function getButtonClasses(
  variant: ButtonProps['variant'],
  size: ButtonProps['size'],
  className?: string
) {
  const variants = {
    primary: 'btn-primary',
    secondary: 'btn-secondary',
    gold: 'btn-gold',
    ghost:
      'inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-brand-700',
  };

  const sizes = {
    sm: 'px-4 py-2 text-xs',
    md: '',
    lg: 'px-8 py-4 text-base',
  };

  return cn(variants[variant ?? 'primary'], sizes[size ?? 'md'], className);
}

function isHttpHref(href: string) {
  return /^https?:\/\//i.test(href);
}

const Button = forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonProps>(
  (
    {
      className,
      variant = 'primary',
      size = 'md',
      children,
      href,
      external,
      type = 'button',
      disabled,
      form,
      formAction,
      formEncType,
      formMethod,
      formNoValidate,
      formTarget,
      name,
      value,
      ...props
    },
    ref
  ) => {
    const classes = getButtonClasses(variant, size, className);

    if (href) {
      const openInNewTab = external || isHttpHref(href);
      const linkClassName = cn(classes, disabled && 'pointer-events-none opacity-50');

      if (href.startsWith('/') && !openInNewTab) {
        return (
          <Link
            href={href}
            ref={ref as React.Ref<HTMLAnchorElement>}
            className={linkClassName}
            aria-disabled={disabled || undefined}
          >
            {children}
          </Link>
        );
      }

      return (
        <a
          href={disabled ? undefined : href}
          ref={ref as React.Ref<HTMLAnchorElement>}
          className={linkClassName}
          aria-disabled={disabled || undefined}
          {...(openInNewTab ? { target: '_blank' as const, rel: 'noopener noreferrer' } : {})}
        >
          {children}
        </a>
      );
    }

    return (
      <button
        ref={ref as React.Ref<HTMLButtonElement>}
        type={type}
        className={classes}
        disabled={disabled}
        form={form}
        formAction={formAction}
        formEncType={formEncType}
        formMethod={formMethod}
        formNoValidate={formNoValidate}
        formTarget={formTarget}
        name={name}
        value={value}
        {...props}
      >
        {children}
      </button>
    );
  }
);

Button.displayName = 'Button';
export default Button;