import { forwardRef } from "react";
import { Link } from "react-router-dom";
import { Spinner } from "./Spinner";
import "./Button.css";

/**
 * variant: "primary" | "secondary" | "ghost" | "danger" | "warning"
 * size: "sm" | "md"
 */
export const Button = forwardRef(function Button(
    {
        children,
        variant = "primary",
        size = "md",
        loading = false,
        disabled = false,
        icon = null,
        type = "button",
        className = "",
        to = null,
        ...props
    },
    ref
) {
    const classes = `dw-btn dw-btn--${variant} dw-btn--${size} ${className}`;

    if (to && !disabled && !loading) {
        return (
            <Link ref={ref} to={to} className={classes} {...props}>
                {icon && <span className="dw-btn__icon">{icon}</span>}
                <span className="dw-btn__label">{children}</span>
            </Link>
        );
    }

    return (
        <button
            ref={ref}
            type={type}
            disabled={disabled || loading}
            className={classes}
            {...props}
        >
            {loading ? (
                <Spinner size={size === "sm" ? 13 : 15} />
            ) : (
                icon && <span className="dw-btn__icon">{icon}</span>
            )}
            <span className="dw-btn__label">{children}</span>
        </button>
    );
});
