import {
	ButtonHTMLAttributes,
	DetailedHTMLProps,
	useEffect,
	useState,
} from "react";
import { cn } from "../../../helper/cn";

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

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

	return (
		<button
			{...(props as any)}
			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 as any}
		</button>
	);
};
