/**
 * Status filter chip — inline editor for status/role multi-select filters.
 *
 * @package RawTypeOE
 */

import { useCallback, useMemo } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Label, Notice, Skeleton, ToggleGroup } from '@rawtype/ui';
import useApiData from '../hooks/useApiData';

const STOCK_STATUS_OPTIONS = [
	{ value: 'instock', label: __( 'In stock', 'rawtype-order-exporter-woocommerce' ) },
	{ value: 'outofstock', label: __( 'Out of stock', 'rawtype-order-exporter-woocommerce' ) },
	{ value: 'onbackorder', label: __( 'On backorder', 'rawtype-order-exporter-woocommerce' ) },
];

const ON_SALE_OPTIONS = [
	{ value: 'true', label: __( 'On sale', 'rawtype-order-exporter-woocommerce' ) },
	{ value: 'false', label: __( 'Not on sale', 'rawtype-order-exporter-woocommerce' ) },
];

function getInlineOptions( field ) {
	if ( 'stock_status' === field ) {
		return STOCK_STATUS_OPTIONS;
	}
	if ( 'on_sale' === field ) {
		return ON_SALE_OPTIONS;
	}
	return null;
}

export default function StatusFilterChip( { filter, entity, onChange } ) {
	const inlineOptions = useMemo(
		() => getInlineOptions( filter.field ),
		[ filter.field ],
	);

	const needsFetch = ! inlineOptions;
	const { data: fetchedStatuses, loading: fetchLoading, error } = useApiData(
		'/rawtype_oe/v1/statuses/' + entity,
		{ enabled: needsFetch },
	);

	const statuses = inlineOptions || fetchedStatuses;
	const loading = needsFetch && fetchLoading;

	// All entities use single-select: a status/role can only have one value at a time.
	const selectedValues = 'string' === typeof filter.value ? filter.value : '';

	const handleValueChange = useCallback(
		( next ) => {
			const selectedOption = Array.isArray( statuses )
				? statuses.find( ( option ) => option.value === next )
				: null;

			// ToggleGroup single mode emits '' when deselected; keep that as-is.
			onChange( {
				...filter,
				value: next,
				selectedLabel: selectedOption ? selectedOption.label : '',
			} );
		},
		[ filter, onChange, statuses ],
	);

	if ( loading ) {
		return <Skeleton width="100%" height={ 36 } />;
	}

	if ( error ) {
		return (
			<Notice type="error">
				{ __( 'Error loading statuses', 'rawtype-order-exporter-woocommerce' ) }
			</Notice>
		);
	}

	const label =
		'stock_status' === filter.field
			? __( 'Stock', 'rawtype-order-exporter-woocommerce' )
			: 'on_sale' === filter.field
			? __( 'Sale', 'rawtype-order-exporter-woocommerce' )
			: 'orders' === entity
			? __( 'Order status', 'rawtype-order-exporter-woocommerce' )
			: 'cross-entity' === entity
			? __( 'Order status', 'rawtype-order-exporter-woocommerce' )
			: 'products' === entity
			? __( 'Product status', 'rawtype-order-exporter-woocommerce' )
			: __( 'Customer role', 'rawtype-order-exporter-woocommerce' );

	return (
		<div className="roe-status-filter">
			<Label size="sm">{ label }</Label>
			<ToggleGroup.Root
				type="single"
				value={ selectedValues }
				onValueChange={ handleValueChange }
				variant="pills"
				size="sm"
			>
				{ statuses.map( ( status ) => (
					<ToggleGroup.Item
						key={ status.value }
						value={ status.value }
					>
						{ status.label }
					</ToggleGroup.Item>
				) ) }
			</ToggleGroup.Root>
		</div>
	);
}

/**
 * Get a human-readable summary of a status filter for the chip label.
 *
 * @param {Object} filter The status filter object.
 * @return {string} Summary text.
 */
export function getStatusFilterSummary( filter ) {
	return filter.selectedLabel || filter.value || '...';
}
