import { colors } from "../../styles/colors.js";
import { getColor } from "../../styles/themes.js";
import { Icon } from "../Icon/Icon.js";
import { Button } from "../Button.js";
import { Spacing } from "../../styles/tokens/spacing.js";
import { TextInput } from "../TextInput.js";
import { Flex } from "../Flex.js";
import { Dropdown } from "../Dropdown.js";
import { Body } from "../typography/Body.js";
import { Label } from "../typography/Label.js";
import "./filters.js";
import { isBooleanFilterState } from "./BooleanFilter.js";
import "./date_utils.js";
import { isDateFilterState } from "./DateFilter.js";
import { isEnumFilterState } from "./EnumFilter.js";
import { isIdFilterState } from "./IdFilter.js";
import { isStringFilterState } from "./StringFilter.js";
import { isBooleanFilterAndState, isDateFilterAndState, isEnumFilterAndState, isIdFilterAndState, isStringFilterAndState } from "./utils.js";
import styled from "@emotion/styled";
import { capitalize } from "lodash-es";
import { useState } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "@emotion/react/jsx-runtime";
import { ensureArray } from "@lightsparkdev/core";
import DateTimeRangePicker from "@wojtekmaj/react-datetimerange-picker";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc.js";
//#region src/components/DataManagerTable/PillFilter.tsx
dayjs.extend(utc);
function PillFilter({ filter, state, onUpdateFilter, onDelete, customComponents }) {
	return /* @__PURE__ */ jsxs(FilterContainer, { children: [
		/* @__PURE__ */ jsx(Property, { children: /* @__PURE__ */ jsx(Label, {
			size: "Small",
			content: filter.label
		}) }),
		/* @__PURE__ */ jsx(Operator, { children: /* @__PURE__ */ jsx(Body, {
			size: "Small",
			color: "secondary",
			content: getOperatorLabel(filter)
		}) }),
		/* @__PURE__ */ jsx(FilterDropdown, {
			filterAndState: {
				filter,
				state
			},
			onUpdateFilter,
			customComponents
		}),
		/* @__PURE__ */ jsx(DeleteButton, {
			onClick: onDelete,
			children: /* @__PURE__ */ jsx(Icon, {
				name: "CentralCrossSmall",
				color: "secondary",
				width: 16,
				iconProps: { strokeWidth: "3px" }
			})
		})
	] });
}
function getOperatorLabel(filter) {
	switch (filter.type) {
		case "enum": return "is";
		case "date": return "is";
		case "string": return "is";
		case "id": return "is";
		case "boolean": return "is";
		default: return "is";
	}
}
function formatDateValue(date) {
	return dayjs.utc(date).format("MMM DD, HH:mm");
}
function getFilterValue(state) {
	if (isEnumFilterState(state)) return state.appliedValues?.join(", ").replaceAll("_", " ") || "Empty";
	else if (isStringFilterState(state)) return state.appliedValues?.join(", ") || "Empty";
	else if (isIdFilterState(state)) return state.appliedValues?.join(", ") || "Empty";
	else if (isDateFilterState(state)) return state.start && state.end ? `${formatDateValue(state.start)} - ${formatDateValue(state.end)}` : "Empty";
	else if (isBooleanFilterState(state)) return state.value ? "True" : "False";
	throw new Error("Invalid filter state");
}
const commonDropdownGetCSS = ({ isOpen, theme }) => {
	return {
		borderRight: `0.5px solid ${getColor(theme, ["controls", "border"])}`,
		display: "flex",
		justifyContent: "center",
		alignItems: "center"
	};
};
const commonDropdownProps = {
	getCSS: commonDropdownGetCSS,
	align: "left"
};
function FilterDropdown({ filterAndState, onUpdateFilter, customComponents }) {
	const [stringFilterValue, setStringFilterValue] = useState("");
	const [dates, setDates] = useState(null);
	const [isOpen, setIsOpen] = useState(false);
	const DropdownComponent = customComponents?.customDropdown || Dropdown;
	if (isEnumFilterAndState(filterAndState)) {
		const { filter, state } = filterAndState;
		return /* @__PURE__ */ jsx(DropdownComponent, {
			...commonDropdownProps,
			button: { getContent: ({ isOpen, theme }) => {
				return /* @__PURE__ */ jsx(Value, { children: /* @__PURE__ */ jsx(Label, {
					size: "Small",
					content: capitalize(getFilterValue(state)),
					color: state.appliedValues?.length && state.appliedValues.length > 0 ? "text" : "secondary"
				}) });
			} },
			dropdownItems: filter.enumValues.map((option) => ({
				label: option.label,
				onClick: () => {
					const optionValues = ensureArray(option.value);
					let updatedAppliedValues = [];
					if (filter.isMulti) updatedAppliedValues = state.appliedValues ? [...state.appliedValues.filter((appliedValue) => appliedValue !== option.value), ...optionValues] : [...optionValues];
					else updatedAppliedValues = [...optionValues];
					onUpdateFilter({
						...state,
						value: option.label,
						isApplied: true,
						appliedValues: updatedAppliedValues
					});
				}
			}))
		});
	} else if (isStringFilterAndState(filterAndState) || isIdFilterAndState(filterAndState)) {
		const TextInputComponent = customComponents?.customTextInput || TextInput;
		const { filter, state } = filterAndState;
		const handleApplyFilter = () => {
			let updatedAppliedValues = [];
			if (filter.isMulti) updatedAppliedValues = state.appliedValues ? [...state.appliedValues.filter((appliedValue) => appliedValue !== stringFilterValue), stringFilterValue] : [stringFilterValue];
			else updatedAppliedValues = [stringFilterValue];
			onUpdateFilter({
				...state,
				appliedValues: updatedAppliedValues,
				value: stringFilterValue,
				isApplied: true
			});
			setIsOpen(false);
		};
		return /* @__PURE__ */ jsx(DropdownComponent, {
			...commonDropdownProps,
			isOpen,
			onOpen: () => setIsOpen(true),
			onClose: () => setIsOpen(false),
			button: { getContent: ({ isOpen, theme }) => {
				return /* @__PURE__ */ jsx(Value, { children: /* @__PURE__ */ jsx(Label, {
					size: "Small",
					content: getFilterValue(state),
					color: state.appliedValues?.length && state.appliedValues.length > 0 ? "text" : "secondary"
				}) });
			} },
			dropdownContent: /* @__PURE__ */ jsxs(Flex, {
				column: true,
				gap: 8,
				pt: 8,
				pr: 8,
				pb: 8,
				pl: 8,
				width: 240,
				children: [/* @__PURE__ */ jsx(TextInputComponent, {
					placeholder: "Enter value",
					value: stringFilterValue,
					onChange: (value) => {
						setStringFilterValue(value);
					},
					onKeyDown: (keyValue, event) => {
						if (keyValue === "Enter") handleApplyFilter();
					}
				}), /* @__PURE__ */ jsx(Button, {
					kind: "primary",
					text: "Apply",
					typography: { type: "Btn" },
					fullWidth: true,
					onClick: handleApplyFilter
				})]
			})
		});
	} else if (isBooleanFilterAndState(filterAndState)) {
		const { state } = filterAndState;
		return /* @__PURE__ */ jsx(DropdownComponent, {
			...commonDropdownProps,
			button: { getContent: ({ isOpen, theme }) => {
				return /* @__PURE__ */ jsx(Value, { children: /* @__PURE__ */ jsx(Label, {
					size: "Small",
					content: capitalize(getFilterValue(state))
				}) });
			} },
			dropdownItems: ["True", "False"].map((option) => ({
				label: option,
				onClick: () => {
					onUpdateFilter({
						...state,
						value: option,
						isApplied: true
					});
				}
			}))
		});
	} else if (isDateFilterAndState(filterAndState)) {
		const { state } = filterAndState;
		const isValidDateRange = (dates) => {
			return dates instanceof Array && dates.length === 2 && dates[0] !== null && dates[1] !== null;
		};
		const handleCalendarChange = (dates) => {
			if (!isValidDateRange(dates)) return;
			setDates(dates);
		};
		const updateCalendarState = (dates) => {
			if (!isValidDateRange(dates)) return;
			const start = dayjs.utc(dates[0]).add(dayjs().utcOffset(), "minutes").toDate();
			const end = dayjs.utc(dates[1]).add(dayjs().utcOffset(), "minutes").toDate();
			onUpdateFilter({
				...state,
				preset: "Custom",
				isApplied: true,
				customRangeOperation: "is between",
				start,
				end
			});
			setIsOpen(false);
		};
		return /* @__PURE__ */ jsx(DropdownComponent, {
			...commonDropdownProps,
			isOpen,
			onOpen: () => setIsOpen(true),
			onClose: () => setIsOpen(false),
			button: { getContent: ({ isOpen, theme }) => {
				return /* @__PURE__ */ jsx(Value, { children: /* @__PURE__ */ jsx(Label, {
					size: "Small",
					content: getFilterValue(state),
					color: state.start && state.end ? "text" : "secondary"
				}) });
			} },
			dropdownContent: /* @__PURE__ */ jsx(Fragment$1, { children: /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(DateTimeRangePicker, {
				onChange: handleCalendarChange,
				isCalendarOpen: isOpen,
				shouldCloseWidgets: () => isOpen === false,
				shouldOpenWidgets: () => isOpen === true,
				onFocus: () => setIsOpen(true),
				value: dates,
				locale: "en-US",
				autoFocus: true,
				formatShortWeekday: (locale, date) => {
					return capitalize(date.toLocaleDateString(locale, { weekday: "short" })).slice(0, 1);
				},
				css: customComponents?.customCalendarCss,
				nextLabel: /* @__PURE__ */ jsx(NextPrevCalendarButtons, { children: /* @__PURE__ */ jsx(Icon, {
					name: "CentralChevronRight",
					width: 10
				}) }),
				prevLabel: /* @__PURE__ */ jsx(NextPrevCalendarButtons, { children: /* @__PURE__ */ jsx(Icon, {
					name: "CentralChevronLeft",
					width: 10
				}) })
			}), /* @__PURE__ */ jsx(Flex, {
				pt: Spacing["3xs"],
				pr: Spacing.sm,
				pb: Spacing.sm,
				pl: Spacing.sm,
				children: /* @__PURE__ */ jsx(Button, {
					kind: "primary",
					typography: { type: "Btn" },
					fullWidth: true,
					text: "Apply",
					onClick: () => {
						updateCalendarState(dates);
					}
				})
			})] }) })
		});
	}
	return null;
}
const FilterContainer = styled.div`
  display: flex;
  flex-direction: row;
  height: 30px;
  background: ${({ theme }) => theme.bg};
  border-radius: 4px;
  border: 0.5px solid ${({ theme }) => getColor(theme, ["controls", "border"])};
`;
const Property = styled.div`
  border-right: 0.5px solid
    ${({ theme }) => getColor(theme, ["controls", "border"])};
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0px ${Spacing.px.xs};
  white-space: nowrap;
`;
const Operator = styled.div`
  border-right: 0.5px solid
    ${({ theme }) => getColor(theme, ["controls", "border"])};
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0px ${Spacing.px.xs};
`;
const Value = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0px ${Spacing.px.xs};
  white-space: nowrap;
`;
const DeleteButton = styled.div`
  padding: 0px ${Spacing.px["2xs"]};
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
  &:hover {
    background-color: ${colors["black-04"]};
  }
  &:active {
    background-color: ${colors["black-10"]};
  }
`;
const NextPrevCalendarButtons = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  min-width: 28px;
  min-height: 28px;
`;
//#endregion
export { PillFilter };
