import { type ButtonHTMLAttributes, type FC, memo, type ReactNode } from 'react'
import MoonLoader from "react-spinners/MoonLoader"
import { type XOR } from '../helpers/types'
import { clx } from '../helpers/utils'

type Props = {
    className?: string;
    isLoading?: boolean,
    variant?: 'primary' | 'outline' | 'ghost' | 'danger';
    size?: 'sm' | 'md' | 'lg';
} & ButtonHTMLAttributes<HTMLButtonElement> &
    XOR<{ children: ReactNode }, { label: string }>;

const Button: FC<Props> = memo((props) => {
    const { variant = 'primary', size = 'md', className, isLoading, ...restProps } = props;

    const buttonClass = clx(
        'flex rounded-xl items-center justify-center text-center font-medium transition-colors',
        // Variant styles
        variant === 'primary' && 'bg-primary text-white hover:bg-primary/90',
        variant === 'outline' && 'bg-transparent border border-gray-300 text-gray-700 hover:bg-gray-50 hover:border-gray-400',
        variant === 'ghost' && 'bg-transparent text-gray-700 hover:bg-gray-100',
        variant === 'danger' && 'bg-red-500 text-white hover:bg-red-600',
        // Size styles
        size === 'sm' && 'h-8 px-3 text-xs',
        size === 'md' && 'h-10 px-4 text-sm',
        size === 'lg' && 'h-12 px-6 text-base',
        // Disabled state
        restProps.disabled && 'cursor-not-allowed opacity-60',
        // Default width
        'w-full'
    );

    return (
        <button
            disabled={isLoading}
            {...restProps}
            className={clx(buttonClass, className)}
        >
            {
                isLoading ?
                    <MoonLoader color={variant === 'primary' || variant === 'danger' ? "white" : "#6B7280"} size={16} />
                    :
                    restProps.label || restProps.children
            }
        </button>
    )
})

export default Button