import { FormToggle, Tooltip } from '@wordpress/components';

type ToggleProps = {
	checked: boolean;
	disabled?: boolean;
	id: string;
	label?: string;
	name?: string;
	onChange: ( event: React.ChangeEvent< HTMLInputElement > ) => void;
	tooltip?: string;
	value?: string;
};

/**
 * FormToggle component
 *
 * @param {ToggleProps} props - The component props.
 * @return                        - The form toggle component.
 */
export default function Toggle( props: ToggleProps ) {
	const { checked, disabled, id, label, name, onChange, tooltip } = props;
	const classNames = [ 'gs-toggle' ];
	if ( disabled ) {
		classNames.push( 'gs-toggle--disabled' );
	}
	if ( checked ) {
		classNames.push( 'gs-toggle--checked' );
	}

	if ( tooltip ) {
		return (
			<Tooltip text={ tooltip }>
				<label className={ classNames.join( ' ' ) } htmlFor={ id }>
					<FormToggle
						id={ id }
						name={ name }
						onChange={ onChange }
						checked={ checked }
						disabled={ disabled }
						value={ props.value }
					/>
					{ label && (
						<span className="gs-toggle__label">{ label }</span>
					) }
				</label>
			</Tooltip>
		);
	}

	return (
		<label className={ classNames.join( ' ' ) } htmlFor={ id }>
			<FormToggle
				id={ id }
				name={ name }
				onChange={ onChange }
				checked={ checked }
				disabled={ disabled }
				value={ props.value }
			/>
			{ label && <span className="gs-toggle__label">{ label }</span> }
		</label>
	);
}
