"use client"

import type { IButtonProps } from "./Button.d"
import type { JSX } from "react"

import { forwardRef } from "react"

import {
	Button as RadixButton,
	IconButton as RadixIconButton,
} from "@radix-ui/themes"
import cs from "classnames"
import { LoaderCircle } from "lucide-react"

import styles from "./Button.module.scss"

const sizeMap = {
	sm: "1",
	md: "2",
	lg: "3",
} as const

const variantMap = {
	primary: { variant: "solid", color: "plum" },
	secondary: { variant: "soft", color: "plum" },
	outline: { variant: "outline", color: "gray" },
	ghost: { variant: "ghost", color: "gray" },
	danger: { variant: "solid", color: "ruby" },
	icon: { variant: "ghost", color: "gray" },
} as const

export const Button = forwardRef<HTMLButtonElement, IButtonProps>(
	(
		{ variant = "primary", size = "md", loading, children, className, ...props },
		ref,
	): JSX.Element => {
		const visual = variantMap[variant]
		const radixSize = sizeMap[size]
		const buttonClass = cs(styles.button, styles[`variant-${variant}`], loading && styles.loading, className)

		if (variant === "icon") {
			return (
				<RadixIconButton
					ref={ref}
					size={radixSize}
					variant={visual.variant}
					color={visual.color}
					className={buttonClass}
					disabled={loading || props.disabled}
					style={{ cursor: "pointer", ...props.style }}
					{...props}
				>
					{loading ? <LoaderCircle className={styles.spinner} size={16} /> : children}
				</RadixIconButton>
			)
		}

		return (
			<RadixButton
				ref={ref}
				size={radixSize}
				variant={visual.variant}
				color={visual.color}
				className={buttonClass}
				disabled={loading || props.disabled}
				style={{ cursor: "pointer", ...props.style }}
				{...props}
			>
				{loading && <LoaderCircle className={styles.spinner} size={16} />}
				{children}
			</RadixButton>
		)
	},
)

Button.displayName = "Button"
