import { useState, useEffect } from '@wordpress/element';
import {
	Button,
	CheckboxControl,
	Spinner,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';

export default function OptionsSelector( { blockConfig, onChange } ) {
	const [ availableOptions, setAvailableOptions ] = useState( [] );
	const [ loading, setLoading ] = useState( false );
	const options = blockConfig.options || {};

	useEffect( () => {
		setLoading( true );
		apiFetch( { path: 'wlconduit/v1/options' } )
			.then( ( data ) => setAvailableOptions( data || [] ) )
			.catch( () => setAvailableOptions( [] ) )
			.finally( () => setLoading( false ) );
	}, [] );

	function toggleOption( key ) {
		const updated = { ...options };
		if ( updated[ key ] ) {
			delete updated[ key ];
		} else {
			updated[ key ] = { as_field: true };
		}
		onChange( updated );
	}

	function handleRefresh() {
		setLoading( true );
		apiFetch( { path: 'wlconduit/v1/options?refresh=1' } )
			.then( ( data ) => setAvailableOptions( data || [] ) )
			.catch( () => {} )
			.finally( () => setLoading( false ) );
	}

	if ( loading ) {
		return <Spinner />;
	}

	return (
		<div className="aic-options-selector">
			<div className="aic-selector-header">
				<p className="aic-selector-hint">
					Select wp_options keys to include in the response.
				</p>
				<Button variant="tertiary" isSmall onClick={ handleRefresh }>
					Refresh
				</Button>
			</div>

			{ availableOptions.length === 0 ? (
				<p>No options found.</p>
			) : (
				availableOptions.map( ( item ) => {
					const key = item.key || item;
					const isInternal = item.internal || false;
					const isSelected = !! options[ key ];

					return (
						<div key={ key } className={ `aic-meta-item ${ isInternal ? 'aic-meta-item--internal' : '' }` }>
							<CheckboxControl
								label={ isInternal ? `${ key } (internal)` : key }
								checked={ isSelected }
								onChange={ () => toggleOption( key ) }
							/>
						</div>
					);
				} )
			) }
		</div>
	);
}
