import type {
	AnchorHTMLAttributes,
	ButtonHTMLAttributes,
	ReactNode,
} from 'react';

type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
type ButtonSize = 'default' | 'tiny' | 'large';

interface ButtonBaseProps {
	variant?: ButtonVariant;
	size?: ButtonSize;
	className?: string;
	children: ReactNode;
}

type NativeButtonProps = ButtonBaseProps &
	ButtonHTMLAttributes< HTMLButtonElement > & { href?: never };

type AnchorButtonProps = ButtonBaseProps &
	AnchorHTMLAttributes< HTMLAnchorElement > & { href: string };

export const buttonClassName = (
	variant: ButtonVariant = 'secondary',
	size: ButtonSize = 'default',
	className = ''
): string =>
	[
		'btn',
		`btn-${ variant }`,
		'tiny' === size ? 'tiny' : '',
		'large' === size ? 'btn-lg' : '',
		className,
	]
		.filter( Boolean )
		.join( ' ' );

export const Button = ( props: NativeButtonProps | AnchorButtonProps ) => {
	const { variant, size, className, children, ...rest } = props;
	const classes = buttonClassName( variant, size, className );

	if ( 'href' in props && props.href ) {
		const { href, ...anchorRest } =
			rest as AnchorHTMLAttributes< HTMLAnchorElement >;

		return (
			<a { ...anchorRest } className={ classes } href={ href }>
				{ children }
			</a>
		);
	}

	const buttonRest = rest as ButtonHTMLAttributes< HTMLButtonElement >;

	return (
		<button
			{ ...buttonRest }
			className={ classes }
			type={ buttonRest.type || 'button' }
		>
			{ children }
		</button>
	);
};
