/**
 * Numeric filter chip — operator selector + number input(s) for amount/quantity filters.
 *
 * @package RawTypeOE
 */

import { useCallback, useMemo } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Label, Notice, NumberField, Select } from '@rawtype/ui';

const OPERATORS = [
	{ value: '>', label: __( 'Greater than', 'rawtype-order-exporter-woocommerce' ) },
	{ value: '<', label: __( 'Less than', 'rawtype-order-exporter-woocommerce' ) },
	{ value: '=', label: __( 'Equal to', 'rawtype-order-exporter-woocommerce' ) },
	{ value: '>=', label: __( 'Greater than or equal', 'rawtype-order-exporter-woocommerce' ) },
	{ value: '<=', label: __( 'Less than or equal', 'rawtype-order-exporter-woocommerce' ) },
	{ value: 'between', label: __( 'Between', 'rawtype-order-exporter-woocommerce' ) },
];

const NUMERIC_TYPES = {
	order_total: {
		label: __( 'Order total', 'rawtype-order-exporter-woocommerce' ),
		isCurrency: false,
		entity: 'orders',
	},
	customer_total_spend: {
		label: __( 'Total spent by customer', 'rawtype-order-exporter-woocommerce' ),
		isCurrency: true,
		entity: 'customers',
	},
	customer_orders_count: {
		label: __( 'Customer order count', 'rawtype-order-exporter-woocommerce' ),
		isCurrency: false,
		entity: 'customers',
	},
	product_price: {
		label: __( 'Product price', 'rawtype-order-exporter-woocommerce' ),
		isCurrency: true,
		entity: 'products',
	},
};

export default function NumericFilterChip( { filter, onChange } ) {
	const filterType = filter.type || 'order_total';
	const operator = filter.operator || '>';
	const value = filter.value;
	const isBetween = 'between' === operator;
	const typeConfig = NUMERIC_TYPES[ filterType ] || NUMERIC_TYPES.order_total;

	const rangeError = useMemo( () => {
		if ( ! isBetween || ! Array.isArray( value ) ) {
			return null;
		}
		const from = parseFloat( value[ 0 ] );
		const to = parseFloat( value[ 1 ] );
		if ( ! isNaN( from ) && ! isNaN( to ) && from > to ) {
			return __( '"From" must be less than "To"', 'rawtype-order-exporter-woocommerce' );
		}
		return null;
	}, [ isBetween, value ] );

	const handleOperatorChange = useCallback(
		( newOp ) => {
			const newValue = 'between' === newOp ? [ 0, 0 ] : 0;
			onChange( { ...filter, operator: newOp, value: newValue } );
		},
		[ filter, onChange ],
	);

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

	const handleRangeChange = useCallback(
		( index, val ) => {
			const current = Array.isArray( value ) ? [ ...value ] : [ '', '' ];
			current[ index ] = val;
			onChange( { ...filter, value: current } );
		},
		[ filter, onChange, value ],
	);

	return (
		<div className="roe-numeric-filter">
			<Label size="sm">
				{ typeConfig.label }
			</Label>

			<div className="roe-numeric-filter-row">
				<Select.Root value={ operator } onValueChange={ handleOperatorChange }>
					<Select.Trigger
						placeholder={ __( 'Operator', 'rawtype-order-exporter-woocommerce' ) }
						className="roe-filter-select"
					/>
					<Select.Content>
						{ OPERATORS.map( ( op ) => (
							<Select.Item key={ op.value } value={ op.value }>
								{ op.label }
							</Select.Item>
						) ) }
					</Select.Content>
				</Select.Root>

				{ isBetween ? (
					<div className="roe-numeric-filter-range">
						<NumberField
							placeholder={ __( 'From', 'rawtype-order-exporter-woocommerce' ) }
							value={ Array.isArray( value ) ? value[ 0 ] ?? 0 : 0 }
							onChange={ ( val ) => handleRangeChange( 0, val ) }
							min={ 0 }
							step={ typeConfig.isCurrency ? '0.01' : '1' }
						/>
						<span className="roe-numeric-separator">—</span>
						<NumberField
							placeholder={ __( 'To', 'rawtype-order-exporter-woocommerce' ) }
							value={ Array.isArray( value ) ? value[ 1 ] ?? 0 : 0 }
							onChange={ ( val ) => handleRangeChange( 1, val ) }
							min={ 0 }
							step={ typeConfig.isCurrency ? '0.01' : '1' }
						/>
					</div>
				) : (
					<NumberField
						placeholder={ __( 'Value', 'rawtype-order-exporter-woocommerce' ) }
						value={ 'number' === typeof value ? value : ( parseFloat( value ) || 0 ) }
						onChange={ ( val ) => handleValueChange( val ) }
						min={ 0 }
						step={ typeConfig.isCurrency ? '0.01' : '1' }
					/>
				) }
			</div>

			{ rangeError && (
				<Notice type="error">
					{ rangeError }
				</Notice>
			) }
		</div>
	);
}

/**
 * Get the label for a numeric filter type.
 *
 * @param {string} type Numeric filter type key.
 * @return {string} Human-readable label.
 */
export function getNumericFilterLabel( type ) {
	if ( NUMERIC_TYPES[ type ] ) {
		return NUMERIC_TYPES[ type ].label;
	}
	return type || '?';
}

/**
 * Get a human-readable summary of a numeric filter.
 *
 * @param {Object} filter The numeric filter object.
 * @return {string} Summary text.
 */
export function getNumericFilterSummary( filter ) {
	const operator = filter.operator || '>';
	const value = filter.value;

	if ( 'between' === operator ) {
		if ( Array.isArray( value ) && value[ 0 ] && value[ 1 ] ) {
			return value[ 0 ] + ' — ' + value[ 1 ];
		}
		return '...';
	}

	if ( '' === value || null === value || undefined === value ) {
		return '...';
	}

	return operator + ' ' + value;
}

/**
 * Exported types for use in FilterBuilder.
 */
export { NUMERIC_TYPES };
