"use client";

import { ButtonHTMLAttributes, forwardRef, ReactNode } from "react";

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
    variant?: "primary" | "secondary" | "outline" | "ghost";
    size?: "sm" | "md" | "lg";
    isLoading?: boolean;
    leftIcon?: string | ReactNode;
    rightIcon?: string | ReactNode;
}

const Button = forwardRef<HTMLButtonElement, ButtonProps>(
    (
        {
            children,
            variant = "primary",
            size = "md",
            isLoading = false,
            leftIcon,
            rightIcon,
            className = "",
            disabled,
            ...props
        },
        ref
    ) => {
        const baseStyles =
            "inline-flex items-center justify-center font-medium rounded-[6px] transition-opacity focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer";

        const variants = {
            primary: "text-white hover:opacity-90 active:opacity-80",
            secondary:
                "bg-[#E5E5E5] dark:bg-gray-700 text-[#000000] dark:text-white hover:opacity-90 active:opacity-80",
            outline:
                "border border-[#E5E5E5] dark:border-gray-600 text-[#000000] dark:text-white hover:bg-[#E5E5E5]/10 dark:hover:bg-gray-700/50 active:bg-[#E5E5E5]/20 dark:active:bg-gray-700",
            ghost: "text-[#000000] dark:text-white hover:bg-[#E5E5E5]/20 dark:hover:bg-gray-700/30 active:bg-[#E5E5E5]/30 dark:active:bg-gray-700/50",
        };

        const sizes = {
            sm: "h-9 px-3 text-[13px]",
            md: "h-10 px-4 text-[14px]",
            lg: "h-12 px-6 text-[14px]",
        };

        return (
            <button
                ref={ref}
                className={`${baseStyles} ${variants[variant]} ${sizes[size]} ${className}`}
                style={variant === 'primary' ? { background: 'var(--gradient-primary)' } : undefined}
                disabled={disabled || isLoading}
                {...props}
            >
                {isLoading && (
                    <i className="ri-loader-4-line animate-spin mr-2 text-[20px]" />
                )}
                {!isLoading && leftIcon && (
                    typeof leftIcon === 'string' ? (
                        <i className={`${leftIcon} mr-2 text-[20px]`} />
                    ) : (
                        <div className="w-5 h-5 mr-2">{leftIcon}</div>
                    )
                )}
                {children}
                {!isLoading && rightIcon && (
                    typeof rightIcon === 'string' ? (
                        <i className={`${rightIcon} ml-2 text-[20px]`} />
                    ) : (
                        <div className="w-5 h-5 ml-2">{rightIcon}</div>
                    )
                )}
            </button>
        );
    }
);

Button.displayName = "Button";

export default Button;
