import React, { useContext } from 'react';
import { __ } from '@wordpress/i18n';
import { Button } from '@wordpress/components';
import { cancelCircleFilled, plusCircleFilled } from '@wordpress/icons';
import {
	Filter,
	FilterOperator,
	FiltersControlContext,
} from '../FiltersControl';
import { FilterPropertyControl } from './FilterPropertyControl';
import { FilterValueControl } from './FilterValueControl';
import { FilterOperatorControl } from './FilterOperatorControl';

export function FilterControl( {
	index,
	groupIndex,
	property,
	operator,
	value,
}: Filter & {
	index: number;
	groupIndex: number;
} ): JSX.Element {
	const {
		operators,
		addFilter,
		removeFilter,
		updateFilter,
		properties,
		propertyGroups,
		getPropertyValues,
	} = useContext( FiltersControlContext );

	const propertyValues = getPropertyValues( property );

	const updateProperty = ( newProperty: string ) => {
		updateFilter( index, groupIndex, {
			property: newProperty,
			operator,
			value: '',
		} );
	};

	const updateOperator = ( newOperator: FilterOperator ) => {
		updateFilter( index, groupIndex, {
			property,
			operator: newOperator,
			value,
		} );
	};

	const updateValue = ( newValue: string ) => {
		updateFilter( index, groupIndex, {
			property,
			operator,
			value: newValue,
		} );
	};

	return (
		<div className="gpeb-filter">
			<div className="gpeb-filter-property-operator">
				<FilterPropertyControl
					onChange={ updateProperty }
					value={ property }
					propertyGroups={ propertyGroups }
					properties={ properties }
				/>

				<FilterOperatorControl
					onChange={ updateOperator }
					operators={ operators }
					value={ operator }
				/>
			</div>

			<FilterValueControl
				onChange={ updateValue }
				value={ value }
				propertyValues={ propertyValues }
			/>

			<div className="gpeb-filter-buttons">
				<Button
					onClick={ () => addFilter( index, groupIndex ) }
					icon={ plusCircleFilled }
					label={ __( 'Add Filter', 'gp-entry-blocks' ) }
					iconSize={ 20 }
				/>

				<Button
					onClick={ () => removeFilter( index, groupIndex ) }
					icon={ cancelCircleFilled }
					label={ __( 'Remove Filter', 'gp-entry-blocks' ) }
					iconSize={ 22 }
				/>
			</div>
		</div>
	);
}
