"use client";

import { Slot } from "@radix-ui/react-slot";
import { RiLoader2Fill } from "@remixicon/react";
import React from "react";
import { tv, type VariantProps } from "tailwind-variants";
import { cx, focusRing } from "../lib/utils";

const buttonVariants = tv({
	base: [
		"relative inline-flex items-center justify-center whitespace-nowrap rounded-md border px-3 py-2 text-center font-medium shadow-sm transition-all duration-100 ease-in-out text-base sm:text-sm cursor-pointer",
		"disabled:pointer-events-none disabled:shadow-none disabled:cursor-default",
		focusRing,
	],
	variants: {
		variant: {
			primary: [
				"border-transparent",
				"text-primary-foreground",
				"bg-primary",
				"hover:bg-primary/90",
				"disabled:bg-muted disabled:text-muted-foreground",
			],
			secondary: [
				"border-border",
				"text-foreground",
				"bg-background",
				"hover:bg-muted",
				"disabled:text-muted-foreground",
			],
			ghost: [
				"shadow-none",
				"border-transparent",
				"text-foreground",
				"bg-transparent hover:bg-muted",
				"disabled:text-muted-foreground",
			],
			destructive: [
				"text-white",
				"border-transparent",
				"bg-destructive",
				"hover:bg-destructive/90",
				"disabled:bg-destructive/50",
			],
		},
	},
	defaultVariants: {
		variant: "primary",
	},
});

interface OnboardingButtonProps
	extends React.ComponentPropsWithoutRef<"button">,
		VariantProps<typeof buttonVariants> {
	asChild?: boolean;
	isLoading?: boolean;
	loadingText?: string;
}

const OnboardingButton = React.forwardRef<
	HTMLButtonElement,
	OnboardingButtonProps
>(
	(
		{
			asChild,
			isLoading = false,
			loadingText,
			className,
			disabled,
			variant,
			children,
			...props
		},
		forwardedRef,
	) => {
		const Component = asChild ? Slot : "button";
		return (
			<Component
				ref={forwardedRef}
				className={cx(buttonVariants({ variant }), className)}
				disabled={disabled || isLoading}
				{...props}
			>
				{isLoading ? (
					<span className="pointer-events-none flex shrink-0 items-center justify-center gap-1.5">
						<RiLoader2Fill
							className="size-4 shrink-0 animate-spin"
							aria-hidden="true"
						/>
						<span className="sr-only">
							{loadingText ? loadingText : "Loading"}
						</span>
						{loadingText ? loadingText : children}
					</span>
				) : (
					children
				)}
			</Component>
		);
	},
);

OnboardingButton.displayName = "OnboardingButton";

export { OnboardingButton, buttonVariants, type OnboardingButtonProps };
