import React, { useState } from 'react';

import PropTypes from 'prop-types';
import Select from 'react-select';
import { __ } from '@wordpress/i18n';
import Button from '@QPComponents/Button';

const propTypes = {
	data: PropTypes.any,
	applyActionHandler: PropTypes.func,
	confirmMessage: PropTypes.string,
	options: PropTypes.array,
};

export default function BulkAction( {
	data = [],
	applyActionHandler,
	confirmMessage = '',
	options = [ { value: 'delete', label: __( 'Delete', 'quizpress' ) } ],
} ) {
	const [ bulkAction, setBulkAction ] = useState( {} );
	const bulkMessage =
		bulkAction?.value === 'restore'
			? __(
					'Are you sure you want to restore selected items?',
					'quizpress'
			  )
			: confirmMessage;

	return (
		<React.Fragment>
			<div className="quizpress-bulk-actions">
				<Select
					className="quizpress-select"
					classNamePrefix="quizpress-react-select"
					placeholder={ __( 'Bulk Actions', 'quizpress' ) }
					isClearable={ true }
					value={ options?.find(
						( item ) => item?.value === bulkAction?.value
					) }
					options={ options }
					onChangeHandler={ ( e ) => setBulkAction( e ) }
				/>
				<Button
					type="button"
					label={ __( 'Apply', 'quizpress' ) }
					preset="light-purple"
					onClick={ () => {
						if (
							data.selectedRows &&
							data.selectedRows.length > 0 &&
							bulkAction.value &&
							confirm(bulkMessage) //eslint-disable-line
						) {
							applyActionHandler( data.selectedRows, bulkAction );
							setBulkAction( '' );
						}
					} }
				/>
			</div>
		</React.Fragment>
	);
}

BulkAction.propTypes = propTypes;
