import { bp, useBreakpoints } from "../../styles/breakpoints.js";
import { colors } from "../../styles/colors.js";
import { getColor, themeOr, themeOrWithKey } from "../../styles/themes.js";
import { standardBorderRadius, standardContentInset } from "../../styles/common.js";
import { Icon } from "../Icon/Icon.js";
import { z } from "../../styles/z-index.js";
import { Button, StyledButton } from "../Button.js";
import { Spacing } from "../../styles/tokens/spacing.js";
import { StyledButtonRow } from "../ButtonRow.js";
import { CardPageFullWidth } from "../CardPage.js";
import { Flex } from "../Flex.js";
import { Dropdown } from "../Dropdown.js";
import { Modal } from "../Modal.js";
import { Table } from "../Table/Table.js";
import { TextIconAligner } from "../TextIconAligner.js";
import { Body } from "../typography/Body.js";
import { Label } from "../typography/Label.js";
import { LabelModerate } from "../typography/LabelModerate.js";
import "./filters.js";
import { BooleanFilter, getDefaultBooleanFilterState } from "./BooleanFilter.js";
import { CurrencyFilter, getDefaultCurrencyFilterState } from "./CurrencyFilter.js";
import { DateFilter, getDefaultDateFilterState } from "./DateFilter.js";
import { EnumFilter, getDefaultEnumFilterState, isEnumFilterState } from "./EnumFilter.js";
import { IdFilter, getDefaultIdFilterState, isIdFilterState } from "./IdFilter.js";
import { StringFilter, getDefaultStringFilterState, isStringFilterState } from "./StringFilter.js";
import { PillFilter } from "./PillFilter.js";
import styled from "@emotion/styled";
import { Fragment, useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { css } from "@emotion/react";
import { Fragment as Fragment$1, jsx, jsxs } from "@emotion/react/jsx-runtime";
import { CurrencyUnit, ensureArray } from "@lightsparkdev/core";
//#region src/components/DataManagerTable/DataManagerTable.tsx
function getDefaultFilterState(filter) {
	switch (filter.type) {
		case "date": return getDefaultDateFilterState();
		case "enum": return getDefaultEnumFilterState();
		case "string": return getDefaultStringFilterState();
		case "id": return getDefaultIdFilterState(filter.allowedEntities);
		case "boolean": return getDefaultBooleanFilterState();
		case "currency": return getDefaultCurrencyFilterState();
		default: throw new Error("Invalid filter type");
	}
}
function initialFilterState(filters) {
	let state = {};
	filters.forEach((filter) => {
		state = {
			...state,
			[filter.accessorKey]: getDefaultFilterState(filter)
		};
	});
	return state;
}
function saveFiltersToURL(searchParams, filters, filterStates, currentPage) {
	filters.forEach((filter) => {
		searchParams.delete(String(filter.accessorKey));
	});
	filters.forEach((filter) => {
		const filterState = filterStates[filter.accessorKey];
		if (filterState && filterState.isApplied) {
			if (filter.type === "string" || filter.type === "enum" || filter.type === "id") {
				const appliedValues = filterState.appliedValues;
				searchParams.set(String(filter.accessorKey), appliedValues?.join(",") || "");
			} else if (filter.type === "boolean") {
				const appliedValue = filterState.value || "";
				searchParams.set(String(filter.accessorKey), String(appliedValue));
			} else if (filter.type === "date") {
				const dateFilter = filterState;
				const startStr = dateFilter.start ? dateFilter.start.toISOString() : "";
				const endStr = dateFilter.end ? dateFilter.end.toISOString() : "";
				searchParams.set(String(filter.accessorKey), `${startStr},${endStr}`);
			} else if (filter.type === "currency") {
				const currencyFilter = filterState;
				const minValue = currencyFilter.min_amount?.value;
				const maxValue = currencyFilter.max_amount?.value;
				if (minValue !== void 0 || maxValue !== void 0) {
					const currencyValue = minValue !== void 0 && maxValue !== void 0 ? `${minValue}-${maxValue}` : minValue !== void 0 ? `>${minValue}` : `<${maxValue}`;
					searchParams.set(String(filter.accessorKey), currencyValue);
				}
			}
		}
	});
	return searchParams;
}
function loadFiltersFromURL(searchParams, filters, currentFilterStates) {
	const newFilterStates = { ...currentFilterStates };
	filters.forEach((filter) => {
		const paramValue = searchParams.get(String(filter.accessorKey));
		if (paramValue !== null && paramValue !== void 0 && paramValue !== "") {
			if (filter.type === "string") {
				const stringFilter = newFilterStates[filter.accessorKey];
				const appliedValues = paramValue.includes(",") ? paramValue.split(",").filter((v) => v.trim() !== "") : [paramValue];
				newFilterStates[filter.accessorKey] = {
					...stringFilter,
					appliedValues,
					isApplied: true
				};
			} else if (filter.type === "enum") {
				const enumFilter = newFilterStates[filter.accessorKey];
				const appliedValues = paramValue.includes(",") ? paramValue.split(",").filter((v) => v.trim() !== "") : [paramValue];
				newFilterStates[filter.accessorKey] = {
					...enumFilter,
					appliedValues,
					isApplied: true
				};
			} else if (filter.type === "id") {
				const idFilter = newFilterStates[filter.accessorKey];
				const appliedValues = paramValue.includes(",") ? paramValue.split(",").filter((v) => v.trim() !== "") : [paramValue];
				newFilterStates[filter.accessorKey] = {
					...idFilter,
					appliedValues,
					isApplied: true
				};
			} else if (filter.type === "boolean") {
				const booleanFilter = newFilterStates[filter.accessorKey];
				const boolValue = paramValue === "true";
				newFilterStates[filter.accessorKey] = {
					...booleanFilter,
					value: boolValue,
					isApplied: true
				};
			} else if (filter.type === "date") {
				const dateFilter = newFilterStates[filter.accessorKey];
				if (paramValue.includes(",")) {
					const [startStr, endStr] = paramValue.split(",");
					const startDate = startStr ? new Date(startStr) : null;
					const endDate = endStr ? new Date(endStr) : null;
					const isValidParams = startDate && !isNaN(startDate.getTime()) || endDate && !isNaN(endDate.getTime());
					newFilterStates[filter.accessorKey] = {
						...dateFilter,
						start: isValidParams ? startDate : null,
						end: isValidParams ? endDate : null,
						isApplied: true
					};
				} else {
					const dateValue = new Date(paramValue);
					newFilterStates[filter.accessorKey] = {
						...dateFilter,
						start: !isNaN(dateValue.getTime()) ? dateValue : null,
						end: null,
						isApplied: true
					};
				}
			} else if (filter.type === "currency") {
				const currencyFilter = newFilterStates[filter.accessorKey];
				if (paramValue.includes("-")) {
					const [min, max] = paramValue.split("-").map((v) => parseInt(v));
					const isValidParams = !isNaN(min) && !isNaN(max);
					newFilterStates[filter.accessorKey] = {
						...currencyFilter,
						min_amount: isValidParams ? {
							value: min,
							unit: CurrencyUnit.SATOSHI
						} : null,
						max_amount: isValidParams ? {
							value: max,
							unit: CurrencyUnit.SATOSHI
						} : null,
						isApplied: true
					};
				} else if (paramValue.startsWith(">")) {
					const min = parseInt(paramValue.substring(1));
					newFilterStates[filter.accessorKey] = {
						...currencyFilter,
						min_amount: !isNaN(min) ? {
							value: min,
							unit: CurrencyUnit.SATOSHI
						} : null,
						max_amount: null,
						isApplied: true
					};
				} else if (paramValue.startsWith("<")) {
					const max = parseInt(paramValue.substring(1));
					newFilterStates[filter.accessorKey] = {
						...currencyFilter,
						min_amount: null,
						max_amount: !isNaN(max) ? {
							value: max,
							unit: CurrencyUnit.SATOSHI
						} : null,
						isApplied: true
					};
				}
			}
		} else {
			const isKeyInURL = searchParams.has(String(filter.accessorKey));
			newFilterStates[filter.accessorKey] = {
				...getDefaultFilterState(filter),
				isApplied: isKeyInURL
			};
		}
	});
	return newFilterStates;
}
function DataManagerTable(props) {
	const [searchParams, setSearchParams] = useSearchParams();
	const isCardPageFullWidth = typeof props.cardPageFullWidth === "boolean" ? props.cardPageFullWidth : true;
	const cardPageMt = typeof props.cardPageMt === "undefined" ? 24 : props.cardPageMt;
	const showPaginationPreviousNext = typeof props.paginationDisplayOptions?.showPaginationPreviousNext === "boolean" ? props.paginationDisplayOptions.showPaginationPreviousNext : true;
	const pageSizeString = typeof props.paginationDisplayOptions?.pageSizeStringTemplate === "string" ? props.paginationDisplayOptions.pageSizeStringTemplate : "Show {pageSize} items";
	const showFooter = typeof props.showFooter === "boolean" ? props.showFooter : true;
	const breakPoint = useBreakpoints();
	const [pageSize, setPageSize] = useState(props.pageSizes?.[0] || 20);
	const [pageCursorState, setPageCursorState] = useState({
		startResult: void 0,
		nextPageCursor: props.nextPageCursor,
		cursorCache: {}
	});
	const [isLoading, setIsLoading] = useState(props.loading || false);
	const [hasLoadedFiltersFromURL, setHasLoadedFiltersFromURL] = useState(false);
	const [numFiltersApplied, setNumFiltersApplied] = useState(0);
	const [showFilterEditor, setShowFilterEditor] = useState(false);
	const [filterStates, setFilterStates] = useState(props.filterOptions ? initialFilterState(props.filterOptions.filters) : {});
	const [fetchVariables, setFetchVariables] = useState(props.filterOptions?.initialQueryVariables || {});
	const DropdownComponent = props.customComponents?.dropdownComponent || Dropdown;
	const isSm = breakPoint.isSm();
	useEffect(() => {
		setIsLoading(Boolean(props.loading));
	}, [props.loading]);
	useEffect(() => {
		if (!props.filterOptions || !props.enableURLFilters) return;
		const { filters, getFilterQueryVariables } = props.filterOptions;
		const newFilterStates = loadFiltersFromURL(searchParams, filters, filterStates);
		setFilterStates(newFilterStates);
		const newFetchVariables = getFilterQueryVariables(filters, newFilterStates, pageSize);
		setFetchVariables(newFetchVariables);
		setNumFiltersApplied(Object.values(newFilterStates).reduce((acc, state) => {
			return state.isApplied ? acc + 1 : acc;
		}, 0));
		if (props.filterOptions && Object.values(newFilterStates).some((state) => state.isApplied)) {
			setIsLoading(true);
			setPageCursorState((prevState) => ({
				...prevState,
				startResult: void 0
			}));
			props.filterOptions.refetch(newFetchVariables).then(() => {
				setIsLoading(false);
			}).catch((e) => {
				setIsLoading(false);
				throw e;
			});
		}
		setHasLoadedFiltersFromURL(true);
	}, [searchParams, pageSize]);
	useEffect(() => {
		if (props.refetchOnPropsChange && props.filterOptions && hasLoadedFiltersFromURL) handleApplyFilters(filterStates, props.filterOptions, pageSize);
	}, [...props.refetchOnPropsChange || [], hasLoadedFiltersFromURL]);
	useEffect(() => {
		if (!props.nextPageCursor) return;
		const cursorCacheResult = Object.entries(pageCursorState.cursorCache[pageSize] || {}).find(([_, cursor]) => cursor === props.nextPageCursor);
		if (cursorCacheResult) setPageCursorState((prevState) => ({
			...prevState,
			startResult: parseInt(cursorCacheResult[0]),
			nextPageCursor: cursorCacheResult[1]
		}));
		else setPageCursorState((prevState) => {
			if (prevState.nextPageCursor === props.nextPageCursor && prevState.startResult !== void 0) return prevState;
			const startResult = prevState.startResult === void 0 ? 1 : prevState.startResult + pageSize;
			return {
				...prevState,
				startResult,
				nextPageCursor: props.nextPageCursor,
				cursorCache: {
					...prevState.cursorCache,
					[pageSize]: {
						...prevState.cursorCache[pageSize],
						[startResult]: props.nextPageCursor
					}
				}
			};
		});
	}, [
		props.nextPageCursor,
		pageSize,
		pageCursorState.cursorCache
	]);
	function updateFilterState(filter) {
		return (state) => {
			setFilterStates((prevState) => ({
				...prevState,
				[filter.accessorKey]: state
			}));
		};
	}
	const handleApplyFilters = async (filterStates, filterOptions, pageSize) => {
		const { filters, refetch, getFilterQueryVariables } = filterOptions;
		const appliedFilterStates = { ...filterStates };
		const filterStatesArray = Object.values(appliedFilterStates);
		let isValid = true;
		for (let i = 0; i < filterStatesArray.length; i++) {
			const filterState = filterStatesArray[i];
			if (filterState.isApplied && filterState.onValidate) {
				const filter = filters[i];
				const validResult = filterState.onValidate(filterState, filter.isMulti);
				if (validResult) {
					appliedFilterStates[filter.accessorKey] = validResult;
					if (isIdFilterState(filterState)) {
						const appliedValues = validResult.appliedValues;
						updateFilterState(filter)({
							...filterStates[filter.accessorKey],
							value: "",
							appliedValues: appliedValues ? [...appliedValues] : []
						});
					}
				} else {
					filterState.errorMessage = filter.errorMessage || "Error validating input";
					isValid = false;
				}
			}
		}
		if (!isValid) {
			setFilterStates((prevState) => ({ ...prevState }));
			return;
		}
		for (let i = 0; i < filterStatesArray.length; i++) {
			const filterState = filterStatesArray[i];
			if (!filterState.isApplied) continue;
			const filter = filters[i];
			if (isStringFilterState(filterState)) {
				if (filterState.value) {
					const value = filterState.value;
					let updatedAppliedValues = [];
					if (filter.isMulti) updatedAppliedValues = filterState.appliedValues?.filter((appliedValue) => appliedValue !== value) || [];
					updatedAppliedValues.push(value);
					const newFilterState = {
						...filterStates[filter.accessorKey],
						value: "",
						appliedValues: updatedAppliedValues
					};
					appliedFilterStates[filter.accessorKey] = newFilterState;
					updateFilterState(filter)(newFilterState);
				}
			} else if (isEnumFilterState(filterState)) {
				if (filterState.value) {
					const newFilterState = {
						...filterStates[filter.accessorKey],
						value: "",
						appliedValues: filterState.appliedValues
					};
					appliedFilterStates[filter.accessorKey] = newFilterState;
					updateFilterState(filter)(newFilterState);
				}
			}
		}
		setNumFiltersApplied(filterStatesArray.reduce((acc, state) => {
			return state.isApplied ? acc + 1 : acc;
		}, 0));
		setShowFilterEditor(false);
		setIsLoading(true);
		const newFetchVariables = getFilterQueryVariables(filters, appliedFilterStates, pageSize);
		setFetchVariables(newFetchVariables);
		if (props.enableURLFilters) setSearchParams(saveFiltersToURL(searchParams, filters, appliedFilterStates, currentPage));
		setPageCursorState((prevState) => ({
			...prevState,
			startResult: void 0
		}));
		try {
			await refetch(newFetchVariables);
		} catch (e) {
			setIsLoading(false);
			throw e;
		}
		setIsLoading(false);
	};
	const handleClearFilters = () => {
		if (props.filterOptions) {
			const { filters } = props.filterOptions;
			const newFilterStates = initialFilterState(filters);
			setFilterStates(newFilterStates);
			handleApplyFilters(newFilterStates, props.filterOptions, pageSize);
		}
	};
	const handleNext = async () => {
		if (!props.filterOptions) return;
		const { refetch } = props.filterOptions;
		setIsLoading(true);
		const newFetchVariables = {
			...fetchVariables,
			after: pageCursorState === void 0 ? void 0 : pageCursorState.nextPageCursor
		};
		setFetchVariables(newFetchVariables);
		try {
			await refetch(newFetchVariables);
		} catch (e) {
			setIsLoading(false);
			throw e;
		}
		setIsLoading(false);
	};
	const handlePrev = async () => {
		if (!props.filterOptions) return;
		const { refetch } = props.filterOptions;
		setIsLoading(true);
		const newFetchVariables = {
			...fetchVariables,
			after: pageCursorState.startResult ? pageCursorState.cursorCache[pageSize][pageCursorState.startResult - pageSize - pageSize] : void 0
		};
		setFetchVariables(newFetchVariables);
		try {
			await refetch(newFetchVariables);
		} catch (e) {
			setIsLoading(false);
			throw e;
		}
		setIsLoading(false);
	};
	const currentPage = Math.floor((pageCursorState.startResult || 0) / pageSize) + 1;
	const handleChangePage = async (page) => {
		const pageCursorIndex = (page - 1) * pageSize + 1 - pageSize;
		const cachedCursorState = pageCursorState.cursorCache[pageSize][pageCursorIndex];
		if (!props.filterOptions || pageCursorIndex > 0 && !cachedCursorState || page === currentPage) return;
		const { refetch } = props.filterOptions;
		setIsLoading(true);
		const newFetchVariables = {
			...fetchVariables,
			after: cachedCursorState
		};
		setFetchVariables(newFetchVariables);
		try {
			await refetch(newFetchVariables);
		} catch (e) {
			setIsLoading(false);
			throw e;
		}
		setIsLoading(false);
	};
	const handleChangePageSize = async (size) => {
		setPageSize(size);
		if (props.showMoreOptions) {
			const { refetch, initialQueryVariables } = props.showMoreOptions;
			setIsLoading(true);
			let pageSizeQueryVariables;
			if (props.showMoreOptions.pageSizeVariables) {
				pageSizeQueryVariables = {};
				for (const variable of props.showMoreOptions.pageSizeVariables) pageSizeQueryVariables[variable] = size;
			} else pageSizeQueryVariables = { first: size };
			const newFetchVariables = {
				...initialQueryVariables,
				...pageSizeQueryVariables
			};
			setFetchVariables(newFetchVariables);
			try {
				await refetch(newFetchVariables);
			} catch (e) {
				setIsLoading(false);
				throw e;
			}
			setIsLoading(false);
		} else if (props.filterOptions) handleApplyFilters(filterStates, props.filterOptions, size);
	};
	const createFilterStateUpdater = (filter) => (state) => {
		setFilterStates((prevState) => ({
			...prevState,
			[filter.accessorKey]: state
		}));
		props.filterOptions?.onFilterStateChange?.(filter.accessorKey, state, setFilterStates);
	};
	const filterSections = props.filterOptions ? props.filterOptions.filters.map((filter) => {
		switch (filter.type) {
			case "date": return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(DateFilter, {
				updateFilterState: createFilterStateUpdater(filter),
				state: filterStates[filter.accessorKey]
			}) }, filter.label);
			case "enum": return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(EnumFilter, {
				updateFilterState: createFilterStateUpdater(filter),
				options: filter.enumValues,
				label: filter.label,
				placeholder: filter.placeholder,
				state: filterStates[filter.accessorKey],
				isMulti: filter.isMulti
			}) }, filter.label);
			case "string": return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(StringFilter, {
				updateFilterState: createFilterStateUpdater(filter),
				label: filter.label,
				placeholder: filter.placeholder,
				state: filterStates[filter.accessorKey]
			}) }, filter.label);
			case "id": return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(IdFilter, {
				updateFilterState: createFilterStateUpdater(filter),
				label: filter.label,
				placeholder: filter.placeholder,
				state: filterStates[filter.accessorKey]
			}) }, filter.label);
			case "boolean": return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(BooleanFilter, {
				updateFilterState: createFilterStateUpdater(filter),
				label: filter.label,
				state: filterStates[filter.accessorKey]
			}) }, filter.label);
			case "currency": return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(CurrencyFilter, {
				updateFilterState: createFilterStateUpdater(filter),
				label: filter.label,
				state: filterStates[filter.accessorKey]
			}) }, filter.label);
			default: return null;
		}
	}) : [];
	let filters;
	const isFilterButtonSmall = isSm && props.header;
	function onApply() {
		handleApplyFilters(filterStates, props.filterOptions, pageSize);
	}
	const filterContent = /* @__PURE__ */ jsxs(FilterContentInner, {
		onKeyDownCapture: (e) => {
			if (e.key === "Enter") onApply();
		},
		isSm,
		children: [filterSections, /* @__PURE__ */ jsxs(FilterContentFooter, { children: [/* @__PURE__ */ jsx(Button, {
			text: "Clear",
			onClick: handleClearFilters
		}), /* @__PURE__ */ jsxs(FilterContentFooterRight, { children: [/* @__PURE__ */ jsx(Button, {
			text: "Cancel",
			onClick: () => setShowFilterEditor(false)
		}), /* @__PURE__ */ jsx(Button, {
			text: "Apply",
			kind: "primary",
			onClick: onApply
		})] })] })]
	});
	const commonButtonProps = {
		kind: isFilterButtonSmall ? "roundIcon" : "secondary",
		size: "ExtraSmall",
		typography: { color: "c6Neutral" },
		icon: { name: "Sort" },
		text: !isFilterButtonSmall ? `Filter${numFiltersApplied > 0 && props.filterEditorStyle !== "pills" ? ` | ${numFiltersApplied}` : ""}` : void 0
	};
	if (props.filterOptions && props.filterOptions.filters.length > 0) {
		const FilterContainerComponent = props.customComponents?.filterContainerComponent || DataManagerTableFilterContainer;
		const defaultFilterContent = /* @__PURE__ */ jsx(Fragment$1, { children: isSm ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
			...commonButtonProps,
			...props.filterButtonProps,
			onClick: () => setShowFilterEditor(!showFilterEditor)
		}), /* @__PURE__ */ jsx(Modal, {
			visible: showFilterEditor,
			onClose: () => setShowFilterEditor(false),
			smKind: "fullscreen",
			children: filterContent
		})] }) : /* @__PURE__ */ jsx(DropdownComponent, {
			borderRadius: 12,
			maxDropdownItemsWidth: 400,
			dropdownContent: /* @__PURE__ */ jsx(FilterDropdownContent, {
				visible: showFilterEditor,
				children: filterContent
			}),
			isOpen: showFilterEditor,
			onOpen: () => {
				setShowFilterEditor(true);
			},
			onClose: () => {
				setShowFilterEditor(false);
			},
			button: {
				...commonButtonProps,
				...props.filterButtonProps
			},
			align: props.filterDropdownAlign || "right"
		}) });
		const pillsFilterContent = /* @__PURE__ */ jsxs(PillFiltersContainer, { children: [/* @__PURE__ */ jsxs(Flex, {
			gap: 4,
			align: "center",
			flexWrap: "wrap",
			children: [props.filterOptions ? props.filterOptions.filters.filter((filter) => {
				return filterStates[filter.accessorKey]?.isApplied;
			}).map((filter) => {
				return /* @__PURE__ */ jsx(PillFilter, {
					filter,
					state: filterStates[filter.accessorKey],
					onDelete: () => {
						setFilterStates((prevStates) => {
							const newStates = { ...prevStates };
							newStates[filter.accessorKey] = getDefaultFilterState(filter);
							handleApplyFilters(newStates, props.filterOptions, pageSize);
							return newStates;
						});
					},
					customComponents: {
						customDropdown: props.customComponents?.dropdownComponent,
						customTextInput: props.customComponents?.textInputComponent,
						customCalendarCss: props.customComponents?.customCalendarCss
					},
					onUpdateFilter: (newFilterState) => {
						setFilterStates((prevStates) => {
							let newStates = { ...prevStates };
							newStates[filter.accessorKey] = newFilterState;
							props.filterOptions?.onFilterStateChange?.(filter.accessorKey, newFilterState, (updater) => {
								if (typeof updater === "function") newStates = updater(newStates);
								else newStates = updater;
							});
							handleApplyFilters(newStates, props.filterOptions, pageSize);
							setShowFilterEditor(false);
							return newStates;
						});
					}
				}, filter.label);
			}) : [], /* @__PURE__ */ jsx(DropdownComponent, {
				borderRadius: 12,
				maxDropdownItemsWidth: 200,
				dropdownItems: getPillDropdownItems({
					filterOptions: props.filterOptions,
					filterStates,
					setFilterStates,
					handleApplyFilters,
					pageSize,
					setShowFilterEditor,
					customDropdownComponent: props.customComponents?.dropdownComponent,
					onFilterStateChange: props.filterOptions.onFilterStateChange
				}),
				isOpen: showFilterEditor,
				onOpen: () => {
					setShowFilterEditor(true);
				},
				onClose: () => {
					setShowFilterEditor(false);
				},
				button: {
					...commonButtonProps,
					...props.filterButtonProps,
					iconSide: "left"
				},
				align: props.filterDropdownAlign || "right"
			})]
		}), /* @__PURE__ */ jsx(Flex, { children: numFiltersApplied > 0 && /* @__PURE__ */ jsx(Button, {
			...commonButtonProps,
			...props.filterButtonProps,
			icon: {
				name: "CentralCrossSmall",
				width: 16,
				color: "text",
				iconProps: { strokeWidth: 3 }
			},
			text: "Clear",
			typography: { color: "secondary" },
			onClick: handleClearFilters,
			kind: "transparent"
		}) })] });
		filters = /* @__PURE__ */ jsxs(FilterContainerComponent, { children: [(!props.filterEditorStyle || props.filterEditorStyle === "default") && defaultFilterContent, props.filterEditorStyle === "pills" && pillsFilterContent] });
	}
	let showMoreDropdown;
	if (props.pageSizes?.length > 1) showMoreDropdown = /* @__PURE__ */ jsx(Dropdown, {
		align: "right",
		verticalPlacement: "top",
		getCSS: ({ isOpen }) => ({
			height: "fit-content",
			alignSelf: "center"
		}),
		button: {
			getCSS: ({ isOpen }) => ({
				display: "flex",
				alignItems: "center",
				height: "100%",
				width: "100%"
			}),
			getContent: ({ isOpen }) => /* @__PURE__ */ jsx(TextIconAligner, {
				content: pageSizeString.replace("{pageSize}", `${pageSize}`),
				typography: { size: "ExtraSmall" },
				rightIcon: {
					name: "Chevron",
					ml: 4,
					width: 14,
					color: isOpen ? "onPrimaryText" : "mcNeutral"
				}
			})
		},
		dropdownItems: props.pageSizes.map((size) => ({
			label: `${size}`,
			onClick: () => {
				handleChangePageSize(size);
			}
		}))
	});
	let footer;
	if (showFooter) {
		if (props.showMoreOptions) footer = /* @__PURE__ */ jsxs(DataManagerTableFooter, { children: [/* @__PURE__ */ jsx(Button, {
			text: "Show more",
			paddingY: "short",
			onClick: () => void handleChangePageSize(pageSize + (props.pageSizes?.[0] || 20))
		}), showMoreDropdown] });
		else if (props.resultCount) {
			const startResult = pageCursorState.startResult || 1;
			const endResult = Math.min(props.resultCount, startResult + pageSize - 1);
			const countString = props.isFullCount ?? true ? props.resultCount : props.resultCount + "+";
			const resultsString = props.paginationDisplayOptions?.showPageNumberButtons ? /* @__PURE__ */ jsx("div", {}) : /* @__PURE__ */ jsxs("div", { children: [
				/* @__PURE__ */ jsx(Label, { children: "Viewing " }),
				/* @__PURE__ */ jsx(LabelModerate, { children: `${startResult}-${endResult}` }),
				/* @__PURE__ */ jsx(Label, { children: " of " }),
				/* @__PURE__ */ jsx(LabelModerate, { children: `${countString}` }),
				/* @__PURE__ */ jsx(Label, { children: " results" })
			] });
			const hasNext = props.resultCount ? startResult + pageSize - 1 < props.resultCount : false;
			const hasPrev = startResult > 1;
			const pageNumbers = Array.from({ length: Math.ceil(props.resultCount / pageSize) }, (_, i) => i);
			footer = /* @__PURE__ */ jsxs(DataManagerTableFooter, { children: [
				resultsString,
				props.paginationDisplayOptions?.showPageNumberButtons ? /* @__PURE__ */ jsxs(PageNumberPaginationButtonsContainer, { children: [
					/* @__PURE__ */ jsx(Button, {
						icon: {
							name: "CentralChevronLeftSmall",
							width: 24,
							color: "text"
						},
						kind: "ghost",
						paddingY: "short",
						onClick: () => void handlePrev(),
						disabled: !hasPrev
					}),
					pageNumbers.slice(0, 2).map((pageNumber) => /* @__PURE__ */ jsx(PageNumberButton, {
						onClick: () => void handleChangePage(pageNumber + 1),
						isCurrentPage: currentPage === pageNumber + 1,
						children: /* @__PURE__ */ jsx(Body, { content: `${pageNumber + 1}` })
					}, pageNumber)),
					pageNumbers.length >= 4 && currentPage - 2 > 1 && /* @__PURE__ */ jsx(Icon, {
						name: "CentralDotGrid1x3Horizontal",
						width: 18,
						ml: 7,
						mr: 7,
						color: "text"
					}),
					currentPage - 1 > 1 && currentPage < pageNumbers.length && /* @__PURE__ */ jsx(PageNumberButton, {
						isCurrentPage: true,
						onClick: () => void handleChangePage(currentPage),
						children: /* @__PURE__ */ jsx(Body, { content: `${currentPage}` })
					}, currentPage),
					pageNumbers.length >= 4 && currentPage + 1 < pageNumbers.length && /* @__PURE__ */ jsx(Icon, {
						name: "CentralDotGrid1x3Horizontal",
						width: 18,
						ml: 7,
						mr: 7,
						color: "text"
					}),
					pageNumbers.length >= 3 && /* @__PURE__ */ jsx(PageNumberButton, {
						isCurrentPage: currentPage === pageNumbers.length,
						onClick: () => void handleChangePage(pageNumbers.length),
						children: /* @__PURE__ */ jsx(Body, { content: `${pageNumbers.length}` })
					}, pageNumbers.length),
					/* @__PURE__ */ jsx(Button, {
						icon: {
							name: "CentralChevronRightSmall",
							width: 24,
							color: "text"
						},
						kind: "ghost",
						paddingY: "short",
						onClick: () => void handleNext(),
						disabled: !hasNext
					})
				] }) : /* @__PURE__ */ jsx(Fragment$1, {}),
				/* @__PURE__ */ jsxs(PaginationContainer, { children: [showMoreDropdown, showPaginationPreviousNext && /* @__PURE__ */ jsxs(PaginationButtonsContainer, { children: [/* @__PURE__ */ jsx(Button, {
					text: "Previous",
					paddingY: "short",
					onClick: () => {
						handlePrev();
					},
					disabled: !hasPrev
				}), /* @__PURE__ */ jsx(Button, {
					text: "Next",
					paddingY: "short",
					onClick: () => {
						handleNext();
					},
					disabled: !hasNext
				})] })] })
			] });
		}
	}
	const DataManagerTableHeaderComponent = props.customComponents?.dataManagerTableHeaderComponent || DataManagerTableHeader;
	const content = /* @__PURE__ */ jsxs(Fragment$1, { children: [
		props.showHeader && /* @__PURE__ */ jsxs(DataManagerTableHeaderComponent, { children: [props.header, filters] }),
		/* @__PURE__ */ jsx(Table, {
			...props,
			loading: isLoading
		}),
		footer
	] });
	return /* @__PURE__ */ jsx(StyledDataManagerTable, {
		fullHeight: props.fullHeight,
		children: isCardPageFullWidth ? /* @__PURE__ */ jsx(CardPageFullWidth, {
			css: { marginTop: `${cardPageMt}px` },
			children: content
		}) : content
	});
}
function getPillDropdownItems({ filterOptions, filterStates, setFilterStates, handleApplyFilters, pageSize, setShowFilterEditor, customDropdownComponent, onFilterStateChange }) {
	const applyFilterState = (filter, newFilterState) => {
		setFilterStates((prevStates) => {
			let newStates = { ...prevStates };
			newStates[filter.accessorKey] = newFilterState;
			onFilterStateChange?.(filter.accessorKey, newFilterState, (updater) => {
				if (typeof updater === "function") newStates = updater(newStates);
				else newStates = updater;
			});
			handleApplyFilters(newStates, filterOptions, pageSize);
			setShowFilterEditor(false);
			return newStates;
		});
	};
	const getDropdownItemForFilter = (filter) => {
		let filterSubDropdownOptions = [];
		if (filter.type === "enum") filterSubDropdownOptions = filter.enumValues.map((option) => ({
			label: option.label,
			onClick: () => {
				const optionValues = ensureArray(option.value);
				const state = filterStates[filter.accessorKey];
				let updatedAppliedValues = [];
				if (filter.isMulti) updatedAppliedValues = state.appliedValues ? [...state.appliedValues.filter((appliedValue) => appliedValue !== option.value), ...optionValues] : [...optionValues];
				else updatedAppliedValues = [...optionValues];
				applyFilterState(filter, {
					...getDefaultFilterState(filter),
					value: updatedAppliedValues.join(", "),
					isApplied: true,
					appliedValues: updatedAppliedValues
				});
			}
		}));
		return {
			label: filter.label,
			getIcon: ({ dropdownItem, theme }) => ({
				name: "CentralChevronRightSm",
				width: 18,
				color: theme.secondary
			}),
			iconSide: "right",
			onClick: () => {
				if (filter.type === "string") {
					const state = filterStates[filter.accessorKey];
					let updatedAppliedValues = [];
					updatedAppliedValues = filter.isMulti && state.appliedValues ? [...state.appliedValues.filter((appliedValue) => appliedValue !== filter.value)] : state.appliedValues ? [...state.appliedValues] : [];
					applyFilterState(filter, {
						...getDefaultFilterState(filter),
						value: updatedAppliedValues.join(", "),
						isApplied: true,
						appliedValues: updatedAppliedValues
					});
				} else if (filter.type === "boolean") applyFilterState(filter, {
					...getDefaultFilterState(filter),
					value: filter.value,
					isApplied: true
				});
				else if (filter.type === "id") {
					const state = filterStates[filter.accessorKey];
					let updatedAppliedValues = [];
					updatedAppliedValues = filter.isMulti && state.appliedValues ? [...state.appliedValues.filter((appliedValue) => appliedValue !== filter.value)] : state.appliedValues ? [...state.appliedValues] : [];
					applyFilterState(filter, {
						...getDefaultFilterState(filter),
						value: updatedAppliedValues.join(", "),
						isApplied: true,
						appliedValues: updatedAppliedValues
					});
				} else if (filter.type === "currency") {} else if (filter.type === "date") applyFilterState(filter, {
					...getDefaultFilterState(filter),
					preset: "Custom",
					start: null,
					end: null,
					isApplied: true
				});
			},
			subDropdown: filterSubDropdownOptions.length > 0 ? {
				subItems: filterSubDropdownOptions,
				customDropdown: customDropdownComponent
			} : void 0
		};
	};
	return filterOptions.filters.map((filter) => getDropdownItemForFilter(filter));
}
const StyledDataManagerTable = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  ${({ fullHeight }) => fullHeight && css`
      flex-grow: 1;
    `}
`;
const commonPadding = `
  ${bp.lg(`
  padding-left: ${standardContentInset.lgPx}px;
  padding-right: ${standardContentInset.lgPx}px;
  `)}
  ${bp.sm(`
  padding-left: ${standardContentInset.smPx}px;
  padding-right: ${standardContentInset.smPx}px;
  `)}
  ${bp.minSmMaxLg(`
  padding-left: ${standardContentInset.minSmMaxLgPx}px;
  padding-right: ${standardContentInset.minSmMaxLgPx}px;
  `)}
`;
const DataManagerTableHeader = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: ${Spacing.px.xs} 0;
  position: relative;
`;
const DataManagerTableFooter = styled.div`
  border-top: 1px solid ${({ theme }) => theme.c1Neutral};
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  ${commonPadding}
  padding-top: ${Spacing.px.md};
  padding-bottom: ${Spacing.px.md};

  ${StyledButton} {
    align-self: end;
  }
`;
const PaginationContainer = styled.div`
  display: flex;
  flex-direction: row;
`;
const PaginationButtonsContainer = styled.div`
  display: flex;
  flex-direction: row;
  margin-left: ${Spacing.px.md};
  gap: ${Spacing.px.xs};
`;
const PageNumberPaginationButtonsContainer = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
`;
const PageNumberButton = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  padding: 0;
  cursor: pointer;
  ${standardBorderRadius(8)}
  border: none;
  background-color: transparent;
  &:hover {
    background-color: ${colors["black-04"]};
  }
  &:active {
    background-color: ${colors["black-10"]};
  }
  ${({ isCurrentPage }) => isCurrentPage ? `
      border: 0.5px solid ${colors["black-10"]};
    ` : ""}
`;
const DataManagerTableFilterContainer = styled.div`
  position: absolute;
  z-index: 3;
  right: 0;
  ${StyledButtonRow} + & {
    background: linear-gradient(
      to right,
      ${({ theme }) => themeOr("rgba(0, 0, 0, 0)", "rgba(0, 0, 0, 0)")({ theme })}
        0%,
      ${({ theme }) => getColor(theme, "bg")} 15%
    );
  }
  ${commonPadding}
`;
const FilterDropdownContent = styled.div`
  width: 400px;
  background: ${({ theme }) => theme.bg};
  border: 0.5px solid
    ${({ theme }) => themeOrWithKey("c1Neutral", "c4Neutral")({ theme })};
  ${standardBorderRadius(12)}
  box-shadow:
    0px 1px 4px 0px rgba(0, 0, 0, 0.1),
    0px 4px 8px 0px rgba(0, 0, 0, 0.08);
  ${({ visible }) => !visible && "display: none;"}
`;
const FilterContentInner = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${Spacing.px.xl};
  padding: ${({ isSm }) => isSm ? "0px" : Spacing.px.lg};
  z-index: ${z.dropdown + 1};
  position: relative;
`;
const FilterContentFooter = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
`;
const FilterContentFooterRight = styled.div`
  display: flex;
  gap: ${Spacing.px.xs};
`;
const PillFiltersContainer = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: ${Spacing.px["2xs"]};
`;
//#endregion
export { DataManagerTable };
