import Clipboard from 'clipboard';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { createRef, Component } from 'react';
import Button from 'components/button';

const noop = () => {};

export default class ClipboardButton extends Component {
	static displayName = 'ClipboardButton';

	static propTypes = {
		className: PropTypes.string,
		text: PropTypes.string,
		prompt: PropTypes.string,
		onCopy: PropTypes.func,
		rna: PropTypes.bool,
	};

	static defaultProps = {
		onCopy: noop,
		rna: false,
	};

	buttonRef = createRef();

	componentDidMount() {
		const button = this.buttonRef.current.domNode;
		this.clipboard = new Clipboard( button, {
			text: () => this.props.text,
		} );
		this.clipboard.on( 'success', this.props.onCopy );
		this.clipboard.on( 'error', this.displayPrompt );
	}

	componentWillUnmount() {
		this.clipboard.destroy();
		delete this.clipboard;
	}

	displayPrompt = () => {
		// eslint-disable-next-line no-alert -- Fallback if clipboard doesn't work, lets the user copy it manually.
		window.prompt( this.props.prompt, this.props.text );
	};

	render() {
		const classes = clsx( 'dops-clipboard-button', this.props.className );
		return (
			<Button
				rna={ this.props.rna }
				ref={ this.buttonRef }
				{ ...Object.fromEntries(
					Object.entries( this.props ).filter(
						( [ k ] ) => ! Object.hasOwn( this.constructor.propTypes, k )
					)
				) }
				className={ classes }
			/>
		);
	}
}
