import { ButtonHTMLAttributes, DetailedHTMLProps, useEffect, useState } from "react";
import { cn } from "@repo/shared-components";

export const Button = ({
	isLoading,
	...props
}: DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> & {
	isLoading?: boolean;
}) => {
	const [isLoadingState, setIsLoadingState] = useState(isLoading);

	useEffect(() => {
		setIsLoadingState(isLoading);
	}, [isLoading]);

	return (
		<button
			{...props}
			className={cn("btn", props.className)}
			disabled={isLoadingState || props.disabled}
			onClick={async (e) => {
				if (props.onClick) {
					setIsLoadingState(true);
					await props.onClick(e);
					setIsLoadingState(false);
				}
			}}
		>
			{isLoadingState && <span className="loading loading-spinner loading-sm"></span>}
			{props.children}
		</button>
	);
};
