import React, { forwardRef } from 'react';
import { __ } from '@wordpress/i18n';
import Icon from '../icons/Icon';

export function Spinner({ size = 'md', label, className = '' }) {
	return (
		<span
			className={['bp-spinner', size === 'lg' ? 'bp-spinner--lg' : '', className].filter(Boolean).join(' ')}
			role={label ? 'status' : undefined}
			aria-label={label || undefined}
			aria-hidden={label ? undefined : 'true'}
		/>
	);
}

/**
 * Button.
 *
 * @param {'primary'|'secondary'|'soft'|'ghost'|'danger'|'danger-ghost'|'link'} [variant='secondary']
 * @param {'sm'|'md'|'lg'} [size='md']
 * @param {boolean} [loading]  Shows a spinner and blocks clicks (keeps width).
 * @param {string}  [icon]     Leading icon name.
 * @param {string}  [iconEnd]  Trailing icon name.
 * @param {boolean} [block]    Full width.
 * @param {string}  [href]     Renders an <a> when set.
 */
const Button = forwardRef(function Button(
	{
		variant = 'secondary',
		size = 'md',
		loading = false,
		icon,
		iconEnd,
		block = false,
		href,
		className = '',
		children,
		disabled,
		type = 'button',
		...rest
	},
	ref
) {
	const classes = [
		'bp-btn',
		`bp-btn--${variant}`,
		size !== 'md' ? `bp-btn--${size}` : '',
		block ? 'bp-btn--block' : '',
		loading ? 'is-loading' : '',
		className,
	]
		.filter(Boolean)
		.join(' ');

	const content = (
		<>
			{icon ? <Icon name={icon} /> : null}
			{children != null && children !== false ? <span>{children}</span> : null}
			{iconEnd ? <Icon name={iconEnd} /> : null}
			{loading ? (
				<span className="bp-btn__spinner">
					<Spinner label={__('Loading', 'pointly-booking')} />
				</span>
			) : null}
		</>
	);

	if (href) {
		return (
			<a
				ref={ref}
				href={disabled ? undefined : href}
				className={classes}
				aria-disabled={disabled || loading ? 'true' : undefined}
				aria-busy={loading ? 'true' : undefined}
				{...rest}
			>
				{content}
			</a>
		);
	}

	return (
		<button
			ref={ref}
			type={type}
			className={classes}
			disabled={disabled}
			aria-disabled={loading ? 'true' : undefined}
			aria-busy={loading ? 'true' : undefined}
			{...rest}
		>
			{content}
		</button>
	);
});

export default Button;

/**
 * Square icon-only button. `label` is required for accessibility.
 */
export const IconButton = forwardRef(function IconButton(
	{ icon, label, variant = 'ghost', size = 'md', className = '', tooltip = false, ...rest },
	ref
) {
	return (
		<Button
			ref={ref}
			variant={variant}
			size={size}
			className={['bp-btn--icon', className].filter(Boolean).join(' ')}
			aria-label={label}
			title={tooltip ? label : undefined}
			{...rest}
		>
			<Icon name={icon} size={size === 'sm' ? 15 : 18} />
		</Button>
	);
});
