import { DATE_KEY, SEARCH_KEY } from '../../utils';
import { sprintf } from '@gravityforms/utils';

/**
 * @function getActiveFilterLabel
 * @description Get active filter label.
 *
 * @since 5.1.0
 *
 * @param {string}       key       The key of the filter.
 * @param {Array|string} value     The value of the filter.
 * @param {string}       pillLabel The pill label.
 * @param {object}       options   The options for the filter.
 *
 * @return {string} The active filter label.
 */
export const getActiveFilterLabel = ( key = '', value = '', pillLabel = '', options = {} ) => {
	if ( key === SEARCH_KEY ) {
		return sprintf( pillLabel, value );
	}
	if ( key === DATE_KEY && Array.isArray( value ) && value.length === 2 ) {
		const startLabel = value[ 0 ].toLocaleDateString( undefined, options );
		const endLabel = value[ 1 ].toLocaleDateString( undefined, options );
		return startLabel === endLabel
			? sprintf( pillLabel, startLabel )
			: sprintf( pillLabel, `${ startLabel } - ${ endLabel }` );
	}
	return '';
};

/**
 * @function getUpdatedFilters
 * @description Get the updated filters.
 * This function updates or adds a filter based on the key and value.
 * Generally used for date and search filters.
 *
 * @since 5.1.0
 *
 * @param {Array}        filters   The array of filters.
 * @param {string}       key       The key of the filter.
 * @param {Array|string} value     The value of the filter.
 * @param {string}       pillLabel The pill label.
 * @param {object}       options   The options for the filter.
 *
 * @return {Array} The updated filters.
 */
export const getUpdatedFilters = (
	filters = [],
	key = '',
	value = '',
	pillLabel = '',
	options = {},
) => {
	const hasFilter = filters.find( ( filter ) => filter.key === key );
	const hasValue = value.length > 0;
	let updatedFilters;
	if ( hasValue && hasFilter ) {
		updatedFilters = filters.map( ( filter ) => {
			if ( filter.key === key ) {
				return {
					...filter,
					value,
					label: getActiveFilterLabel( key, value, pillLabel, options ),
				};
			}
			return filter;
		} );
	} else if ( hasValue ) {
		updatedFilters = [
			...filters,
			{
				id: key,
				key,
				label: getActiveFilterLabel( key, value, pillLabel, options ),
				value,
			},
		];
	} else {
		updatedFilters = filters.filter( ( filter ) => filter.key !== key );
	}

	return updatedFilters;
};
