import { makeStyles, Spinner } from "@fluentui/react-components";
import React from "react";

/**
 * A button that is substituted by a spinner while its making an action
 */

type ActionButtonProps = {} & React.ButtonHTMLAttributes<HTMLButtonElement>
const useStyles = makeStyles({
	topSpace: {
		paddingTop: "1rem",
		textAlign: "center"
	}
});

export const ActionButton: React.FC<ActionButtonProps> = (props) => {
	const styles = useStyles();
	const {onClick, ...otherProps} = props;
	
	const [isWorking, setWorking] = React.useState(false);

	const actionButtonHandler = async (e:React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
		setWorking(true);
		await onClick(e); // Could be (and most likely will be) an async function.
		setWorking(false);
	};
	
	return (
		<div className={styles.topSpace}>
			{isWorking && (
				<Spinner size="huge" label={{ size: "small", children: "Working..." }} />
			) || (
				<button 
					{...otherProps}
					onClick={actionButtonHandler}
				>Save</button>
			)}
		</div>
	);
}