/**
 * Copyright IBM Corp. 2020, 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

const require_runtime = require("../../../../../_virtual/_rolldown/runtime.js");
const require_constants = require("./constants.js");
let react = require("react");
react = require_runtime.__toESM(react);
let prop_types = require("prop-types");
prop_types = require_runtime.__toESM(prop_types);
//#region src/components/Datagrid/Datagrid/addons/Filtering/FilterProvider.tsx
/**
* Copyright IBM Corp. 2022, 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const FilterContext = (0, react.createContext)({});
const EventEmitter = {
	events: {},
	dispatch: function(event, data) {
		if (!this.events[event]) return;
		this.events[event].forEach((callback) => callback(data));
	},
	subscribe: function(event, callback) {
		if (!this.events[event]) this.events[event] = [];
		else this.events[event].push(callback);
	}
};
const removeFilterItem = (state, index) => state.splice(index, 1);
const updateFilterState = (state, type, value) => {
	if (type === "checkbox" || type === "multiSelect") return;
	if (type === "date") return removeFilterItem(state, state.findIndex((val) => formatDateRange(val.value[0], val.value[1]) === formatDateRange(value[0], value[1])));
	return removeFilterItem(state, state.findIndex((val) => val.value === value));
};
const clearSingleFilter = ({ key, value, tableId }, setAllFilters, state, contextTableId) => {
	if (tableId !== contextTableId) return;
	const tempState = [...state.filters];
	tempState.forEach((f, filterIndex) => {
		if (f.id === key) {
			const filterValues = f.value;
			const filterType = f.type;
			updateFilterState(tempState, filterType, value);
			if (filterType === "checkbox" || filterType === "multiSelect") {
				/**
				When all checkboxes of a group are all unselected the value still exists in the filtersObjectArray
				This checks if all the checkboxes are selected = false and removes it from the array
				*/
				const valueIndex = filterValues.findIndex((val) => val.value === value);
				filterValues[valueIndex].selected = false;
				tempState[filterIndex] = {
					...f,
					value: [...filterValues]
				};
				const index = tempState.findIndex((filter) => filter.id === key);
				if (tempState[index].value.every((val) => val.selected === false)) removeFilterItem(tempState, index);
			}
		}
	});
	setAllFilters(tempState);
};
const handleSingleFilterRemoval = (key, value, tableId) => {
	EventEmitter.dispatch(require_constants.CLEAR_SINGLE_FILTER, {
		key,
		value,
		tableId
	});
};
const formatDateRange = (startDate, endDate) => {
	const startDateObj = new Date(startDate);
	const endDateObj = new Date(endDate);
	return `${startDateObj.toLocaleDateString()} - ${endDateObj.toLocaleDateString()}`;
};
const prepareFiltersForTags = (filters, renderDateLabel, tableId) => {
	const tags = [];
	filters.forEach(({ id, type, value }) => {
		const sharedFilterProps = {
			filter: true,
			onClose: () => handleSingleFilterRemoval(id, value, tableId)
		};
		if (type === "dropdown" || type === "radio" || type === "number") tags.push({
			key: id,
			value,
			...sharedFilterProps
		});
		else if (type === "date") {
			const [startDate, endDate] = value;
			tags.push({
				key: id,
				value: renderDateLabel?.(startDate, endDate) ?? formatDateRange(startDate, endDate),
				...sharedFilterProps
			});
		} else if (type === "checkbox" || type === "multiSelect") value.forEach((option) => {
			if (option.selected) tags.push({
				key: id,
				value: option.value,
				...sharedFilterProps,
				onClose: () => handleSingleFilterRemoval(id, option.value, tableId)
			});
		});
	});
	return tags;
};
const filteringReducer = (state, action) => {
	switch (action.type) {
		case require_constants.SAVED_FILTERS: {
			const { savedFilters } = action.payload || {};
			return {
				...state,
				savedFilters
			};
		}
		default: return state;
	}
};
const FilterProvider = ({ children, filters, filterProps, tableId }) => {
	const { renderDateLabel } = filterProps || {};
	const filterTags = prepareFiltersForTags(filters, renderDateLabel, tableId);
	const [panelOpen, setPanelOpen] = (0, react.useState)(false);
	const [state, dispatch] = (0, react.useReducer)(filteringReducer, { savedFilters: [] });
	const value = {
		filterTags,
		EventEmitter,
		panelOpen,
		setPanelOpen,
		state,
		dispatch,
		tableId
	};
	return /* @__PURE__ */ react.default.createElement(FilterContext.Provider, { value }, children);
};
FilterProvider.propTypes = {
	children: prop_types.default.oneOfType([prop_types.default.arrayOf(prop_types.default.node), prop_types.default.node]).isRequired,
	filterProps: prop_types.default.object,
	filters: prop_types.default.arrayOf(prop_types.default.object).isRequired,
	tableId: prop_types.default.string
};
//#endregion
exports.FilterContext = FilterContext;
exports.FilterProvider = FilterProvider;
exports.clearSingleFilter = clearSingleFilter;
