/**
 * Tag filter chip — flat multi-select for product tags.
 *
 * @package RawTypeOE
 */

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

export default function TagFilterChip( { filter, onChange } ) {
	const { data: tags, loading, error } = useApiData( '/rawtype_oe/v1/tags' );

	const selectedValues = Array.isArray( filter.value ) ? filter.value : [];

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

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

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

	if ( 0 === tags.length ) {
		return (
			<EmptyState
				title={ __( 'No tags', 'rawtype-order-exporter-woocommerce' ) }
				description={ __( 'No product tags found', 'rawtype-order-exporter-woocommerce' ) }
			/>
		);
	}

	return (
		<div className="roe-tag-filter">
			<Label size="sm">
				{ __( 'Product tag', 'rawtype-order-exporter-woocommerce' ) }
			</Label>
			<ToggleGroup.Root
				type="multiple"
				value={ selectedValues }
				onValueChange={ handleValueChange }
				variant="pills"
			>
				{ tags.map( ( tag ) => (
					<ToggleGroup.Item
						key={ tag.id }
						value={ tag.id }
					>
						{ tag.name }
					</ToggleGroup.Item>
				) ) }
			</ToggleGroup.Root>
		</div>
	);
}

/**
 * Get a human-readable summary of a tag filter.
 *
 * @param {Object} filter The tag filter object.
 * @return {string} Summary text.
 */
export function getTagFilterSummary( filter ) {
	const values = Array.isArray( filter.value ) ? filter.value : [];
	if ( 0 === values.length ) {
		return '...';
	}
	return sprintf(
		_n(
			/* translators: %d: number of selected tags */
			'%d tag',
			'%d tags',
			values.length,
			'rawtype-order-exporter-woocommerce',
		),
		values.length,
	);
}
