import classnames from 'classnames';
import React, { useState } from 'react';
import { remove } from '../utils/utils';

interface Props {
	hvit?: boolean;
	fullbredde?: boolean;
	klasse?: string[] | string;
	tittel?: string;
	vedKlikk: () => Promise<void> | void | string;
	venstrestilt?: boolean;
	children?: React.ReactNode;
	disabled?: boolean;
}

function Knapp(props: Props) {
	const [isSubmitting, setIsSubmitting] = useState(false);

	const {
		hvit,
		fullbredde,
		klasse,
		tittel,
		vedKlikk,
		venstrestilt,
		children,
		disabled = false,
	} = props;

	const klasser = classnames('knapp', klasse, {
		'util-primaer': hvit,
		'knapp-blokk': fullbredde,
		'util-tekst-venstre': venstrestilt,
	});

	const restProps = remove(props, ['vedKlikk']);
	return (
		<button
			disabled={disabled || isSubmitting}
			className={klasser}
			onClick={() => {
				setIsSubmitting(true);
				const result = vedKlikk();

				if (result instanceof Promise) {
					result.finally(() => setIsSubmitting(false));
				} else {
					setIsSubmitting(false);
				}
			}}
			{...restProps}
		>
			{children || tittel}
		</button>
	);
}

export { Knapp };
