/**
 * 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.
 */

import { __toESM } from "../../../../../_virtual/_rolldown/runtime.js";
import { require_classnames } from "../../../../../node_modules/classnames/index.js";
import { pkg } from "../../../../../settings.js";
import { useWindowResize } from "../../../../../global/js/hooks/useWindowResize.js";
import { useClickOutside } from "../../../../../global/js/hooks/useClickOutside.js";
import { ActionSet } from "../../../../ActionSet/ActionSet.js";
import { BATCH, CLEAR_FILTERS, FLYOUT, INSTANT, SAVED_FILTERS } from "./constants.js";
import { FilterContext } from "./FilterProvider.js";
import useSubscribeToEventEmitter from "./hooks/useSubscribeToEventEmitter.js";
import useFilters from "./hooks/useFilters.js";
import useShouldDisableButtons from "./hooks/useShouldDisableButtons.js";
import React, { useContext, useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import { IconButton, usePrefix } from "@carbon/react";
import { Filter } from "@carbon/react/icons";
import { breakpoints, px } from "@carbon/layout";

//#region src/components/Datagrid/Datagrid/addons/Filtering/FilterFlyout.jsx
/**
* 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.
*/
var import_classnames = /* @__PURE__ */ __toESM(require_classnames());
const componentClass = `${`${pkg.prefix}--datagrid`}-filter-flyout`;
const defaults = {
	flyoutIconDescription: "Open filters",
	title: "Filter",
	primaryActionLabel: "Apply",
	secondaryActionLabel: "Cancel",
	align: "bottom"
};
const emptyArray = [];
const FilterFlyout = ({ updateMethod, flyoutIconDescription = defaults.flyoutIconDescription, align = defaults.align, filters = emptyArray, title = defaults.title, primaryActionLabel = defaults.primaryActionLabel, onFlyoutOpen = () => {}, onFlyoutClose = () => {}, onApply = () => {}, onCancel = () => {}, secondaryActionLabel = defaults.secondaryActionLabel, setAllFilters, data = emptyArray, reactTableFiltersState = emptyArray }) => {
	/** State */
	const [open, setOpen] = useState(false);
	const [stackedLayout, setStackedLayout] = useState(false);
	const handleCancel = () => {
		setOpen(false);
		onCancel();
	};
	const { filtersState, prevFiltersObjectArrayRef, prevFiltersRef, cancel, reset, renderFilter, filtersObjectArray, lastAppliedFilters } = useFilters({
		updateMethod,
		filters,
		setAllFilters,
		variation: FLYOUT,
		reactTableFiltersState,
		onCancel: handleCancel
	});
	const { width } = breakpoints.md;
	const mdPxWidth = parseInt(width) * 16;
	/** Refs */
	const filterFlyoutRef = useRef(null);
	const flyoutInnerRef = useRef(null);
	const flyoutFiltersContainerRef = useRef(null);
	/** State from hooks */
	const [shouldDisableButtons, setShouldDisableButtons] = useShouldDisableButtons({
		initialValue: true,
		filtersState,
		prevFiltersRef,
		open
	});
	/* istanbul ignore next */
	const handleResize = (current) => {
		const filterFlyoutRefPosition = flyoutInnerRef?.current.getBoundingClientRect();
		const originalFlyoutWidth = parseInt(window.getComputedStyle(flyoutInnerRef?.current).getPropertyValue("width"));
		if (Math.sign(filterFlyoutRefPosition.left) === -1) {
			const newFlyoutWidth = originalFlyoutWidth - Math.abs(filterFlyoutRefPosition.left);
			flyoutInnerRef.current.style.width = px(newFlyoutWidth);
		}
		if (originalFlyoutWidth < 642 && Math.sign(filterFlyoutRefPosition.left) === 1 || Math.sign(filterFlyoutRefPosition.left).toString() === "0") {
			const newFlyoutWidth = originalFlyoutWidth + Math.abs(filterFlyoutRefPosition.left);
			flyoutInnerRef.current.style.width = px(newFlyoutWidth);
		}
		if (current?.innerWidth <= mdPxWidth + 254) setStackedLayout(true);
		else setStackedLayout(false);
	};
	useWindowResize(({ current }) => {
		handleResize(current);
	});
	/** Context */
	const { dispatch: localDispatch } = useContext(FilterContext);
	/** Memos */
	const showActionSet = updateMethod === BATCH;
	const carbonPrefix = usePrefix();
	/** Methods */
	const openFlyout = () => {
		setOpen(true);
		onFlyoutOpen();
	};
	const closeFlyout = () => {
		setOpen(false);
		onFlyoutClose();
		flyoutInnerRef.current.style.width = px(642);
	};
	useEffect(() => {
		flyoutInnerRef.current.style.width = px(642);
	}, []);
	const apply = () => {
		setAllFilters(filtersObjectArray);
		closeFlyout();
		onApply({
			filtersState,
			filtersObjectArray,
			lastAppliedFilters
		});
		setShouldDisableButtons(true);
		prevFiltersRef.current = JSON.stringify(filtersState);
		prevFiltersObjectArrayRef.current = JSON.stringify(filtersObjectArray);
		lastAppliedFilters.current = JSON.stringify(filtersObjectArray);
		localDispatch({
			type: SAVED_FILTERS,
			payload: { savedFilters: filtersObjectArray }
		});
	};
	/** Renders all filters */
	const renderFilters = () => filters.map(renderFilter);
	const renderActionSet = () => {
		return showActionSet && /* @__PURE__ */ React.createElement(ActionSet, {
			actions: [{
				key: 1,
				kind: "primary",
				label: primaryActionLabel,
				onClick: apply,
				isExpressive: false,
				disabled: shouldDisableButtons
			}, {
				key: 3,
				kind: "secondary",
				label: secondaryActionLabel,
				onClick: cancel,
				isExpressive: false
			}],
			size: "md",
			buttonSize: "md"
		});
	};
	/** Effects */
	useClickOutside(filterFlyoutRef, (target) => {
		const hasClickedOnDatePicker = target.closest(".flatpickr-calendar");
		const hasClickedOnDropdown = target.className === `${carbonPrefix}--list-box__menu-item__option`;
		if (!open || hasClickedOnDatePicker || hasClickedOnDropdown) return;
		closeFlyout();
		cancel();
	});
	useSubscribeToEventEmitter(CLEAR_FILTERS, (tableId) => {
		reset(tableId);
	});
	return /* @__PURE__ */ React.createElement("div", {
		className: `${componentClass}__container`,
		ref: filterFlyoutRef
	}, /* @__PURE__ */ React.createElement(IconButton, {
		label: flyoutIconDescription,
		kind: "ghost",
		align,
		onClick: open ? closeFlyout : openFlyout,
		className: (0, import_classnames.default)(`${componentClass}__trigger`, { [`${componentClass}__trigger--open`]: open }),
		disabled: data.length === 0
	}, /* @__PURE__ */ React.createElement(Filter, null)), /* @__PURE__ */ React.createElement("div", {
		className: (0, import_classnames.default)(componentClass, {
			[`${componentClass}--open`]: open,
			[`${componentClass}--batch`]: showActionSet,
			[`${componentClass}--instant`]: !showActionSet
		}),
		ref: flyoutInnerRef
	}, /* @__PURE__ */ React.createElement("div", { className: `${componentClass}__inner-container` }, /* @__PURE__ */ React.createElement("span", { className: `${componentClass}__title` }, title), /* @__PURE__ */ React.createElement("div", {
		className: (0, import_classnames.default)(`${componentClass}__filters`, { [`${componentClass}__stacked`]: stackedLayout }),
		ref: flyoutFiltersContainerRef
	}, renderFilters())), renderActionSet()));
};
FilterFlyout.propTypes = {
	align: PropTypes.string,
	data: PropTypes.array.isRequired,
	filters: PropTypes.arrayOf(PropTypes.shape({
		type: PropTypes.string.isRequired,
		column: PropTypes.string.isRequired,
		props: PropTypes.object.isRequired
	})).isRequired,
	flyoutIconDescription: PropTypes.string,
	onApply: PropTypes.func,
	onCancel: PropTypes.func,
	onFlyoutClose: PropTypes.func,
	onFlyoutOpen: PropTypes.func,
	primaryActionLabel: PropTypes.string,
	reactTableFiltersState: PropTypes.arrayOf(PropTypes.shape({
		id: PropTypes.string.isRequired,
		type: PropTypes.string.isRequired,
		value: PropTypes.any.isRequired
	})),
	secondaryActionLabel: PropTypes.string,
	setAllFilters: PropTypes.func.isRequired,
	title: PropTypes.string,
	updateMethod: PropTypes.oneOf([BATCH, INSTANT]).isRequired
};

//#endregion
export { FilterFlyout as default };