import { useState } from 'react'
import type { CSSProperties, ReactNode, MouseEvent } from 'react'

type ButtonVariant = 'filled' | 'outline' | 'paper' | 'ghost';
type ButtonSize = 'sm' | 'md' | 'lg';

interface ButtonProps {
  children: ReactNode;
  variant?: ButtonVariant;
  size?: ButtonSize;
  className?: string;
  onClick?: (e: MouseEvent<HTMLButtonElement>) => void;
  type?: 'button' | 'submit' | 'reset';
  disabled?: boolean;
  asChild?: boolean;
}

const sizeStyles: Record<ButtonSize, CSSProperties> = {
  sm: { padding: '9px 20px', fontSize: '9px' },
  md: { padding: '11px 24px', fontSize: '11px' },
  lg: { padding: '12px 28px', fontSize: '12px' },
};

const baseStyle: CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
  gap: '6px',
  borderRadius: 0,
  fontFamily: 'Vazir, sans-serif',
  fontWeight: 700,
  letterSpacing: '0.5px',
  textTransform: 'uppercase',
  cursor: 'pointer',
  transition: 'background-color 200ms, color 200ms, border-color 200ms',
  outline: 'none',
  border: '1px solid transparent',
  whiteSpace: 'nowrap',
};

const variantBase: Record<ButtonVariant, CSSProperties> = {
  filled: {
    backgroundColor: 'var(--ink)',
    color: 'var(--paper)',
    borderColor: 'var(--ink)',
  },
  outline: {
    backgroundColor: 'transparent',
    color: 'var(--ink)',
    borderColor: 'var(--ink)',
  },
  paper: {
    backgroundColor: 'var(--paper)',
    color: 'var(--ink)',
    borderColor: 'var(--paper)',
  },
  ghost: {
    backgroundColor: 'transparent',
    color: 'var(--ink)',
    borderColor: 'transparent',
  },
};

export function Button({
  children,
  variant = 'filled',
  size = 'md',
  className = '',
  onClick,
  type = 'button',
  disabled = false,
}: ButtonProps) {
  const [hovered, setHovered] = useState(false);

  const getHoverStyle = (): CSSProperties => {
    if (!hovered || disabled) return {};
    switch (variant) {
      case 'filled':
        return { backgroundColor: 'var(--ink-2)' };
      case 'outline':
        return { backgroundColor: 'var(--ink)', color: 'var(--paper)' };
      case 'paper':
        return { backgroundColor: 'var(--paper-2)' };
      case 'ghost':
        return { backgroundColor: 'var(--paper-2)' };
      default:
        return {};
    }
  };

  return (
    <button
      type={type}
      disabled={disabled}
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      className={`focus-visible:ring-2 focus-visible:ring-offset-1 ${className}`}
      style={{
        ...baseStyle,
        ...variantBase[variant],
        ...sizeStyles[size],
        ...getHoverStyle(),
        opacity: disabled ? 0.45 : 1,
        pointerEvents: disabled ? 'none' : 'auto',
      }}
    >
      {children}
    </button>
  );
}
