/**
 * SKU filter chip — text input with exact/contains toggle.
 *
 * @package RawTypeOE
 */

import { useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Label, Switch, TextField } from '@rawtype/ui';

export default function SkuFilterChip( { filter, onChange } ) {
	const value = 'string' === typeof filter.value ? filter.value : '';
	const mode = filter.mode || 'exact';

	const handleValueChange = useCallback(
		( e ) => {
			onChange( { ...filter, value: e.target.value } );
		},
		[ filter, onChange ],
	);

	const handleModeToggle = useCallback(
		( checked ) => {
			onChange( { ...filter, mode: checked ? 'contains' : 'exact' } );
		},
		[ filter, onChange ],
	);

	return (
		<div className="roe-sku-filter">
			<Label size="sm">
				{ __( 'Filter by SKU', 'rawtype-order-exporter-woocommerce' ) }
			</Label>

			<TextField
				placeholder={ __( 'Enter SKU...', 'rawtype-order-exporter-woocommerce' ) }
				value={ value }
				onChange={ handleValueChange }
			/>

			<div className="roe-sku-mode">
				<Label className="roe-sku-mode-label">
					<Switch
						checked={ 'contains' === mode }
						onCheckedChange={ handleModeToggle }
					/>
					<span>
						{ 'contains' === mode
							? __( 'Contains', 'rawtype-order-exporter-woocommerce' )
							: __( 'Exact match', 'rawtype-order-exporter-woocommerce' ) }
					</span>
				</Label>
			</div>
		</div>
	);
}

/**
 * Get a human-readable summary of a SKU filter.
 *
 * @param {Object} filter The SKU filter object.
 * @return {string} Summary text.
 */
export function getSkuFilterSummary( filter ) {
	const value = 'string' === typeof filter.value ? filter.value : '';
	if ( ! value ) {
		return '...';
	}
	const mode = filter.mode || 'exact';
	const prefix = 'contains' === mode ? '~' : '=';
	return prefix + ' ' + value;
}
