'use strict';
'use client';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useRef, useEffect, useImperativeHandle } from 'react';
import { getFilterDisplayValues, onInitFilter, shouldFilterInputBeVisible, updateFilterWidthContainer, onCreateOnRightHandChange, createOnOperatorTypeChange, createOnShowFieldFilter, onFilterKeyDown, isSimpleFilterInput, onFilterOpenChange, isIntegerField, onInputBlur, disableFilterInput, onDateChange, onBrowserChanged, createOnGuidFilterClose } from './Filter.funcs.js';
import { getFilterRightHand } from './filter-display.js';
import { isDefaultInputField } from '../../edit-resource/services/edit-resource-components.js';
import { isEnum, isBooleanField, isDateOnly, isDateTime, isGuid, isFlagsEnum } from '../../core/property-types.js';
import { filterOperatorTypes } from '../../../../fd-toolbox/enums/enums.js';
import { useForm, FormProvider } from 'react-hook-form';
import { EnumFlagFilter } from './EnumFlagFilter.js';
import { EnumFilter } from './filters/EnumFilter.js';
import { IntegerFilter } from './filters/IntegerFilter.js';
import { BooleanFilter } from './filters/boolean-filter/BooleanFilter.js';
import { DateFilter } from './filters/DateFilter.js';
import { TextFilter } from './filters/TextFilter.js';
import { GuidFilter } from './filters/GuidFilter.js';
import { cn } from '../../../../fd-toolbox/lib/utils.js';
import { elementSuffixes } from '../../../../fd-toolbox/constants/element-suffixes.js';
import { filterTypes } from './filter-enums.js';
import { useEmptyRef } from '../../../../fd-toolbox/hooks/use-empty-ref.js';
import { useElementId } from '../../../../fd-toolbox/hooks/use-element-id.js';
import { getElementId } from '../../../../fd-toolbox/html/element-ids.js';
import { useAsyncEffect } from '../../../../fd-toolbox/hooks/use-async-effect.js';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", {
  value,
  configurable: true
});
function Filter({
  propertyMeta,
  onChange,
  className,
  state,
  onStateChange,
  type,
  resetCounter,
  ref,
  parentContextName,
  disabled: disabledProp
}) {
  const form = useForm({
    defaultValues: {
      [propertyMeta.name]: ""
    }
  });
  const [filterOperatorType, setFilterOperatorType] = useState(filterOperatorTypes.none);
  const inputId = useElementId(propertyMeta.name + elementSuffixes.filter, parentContextName);
  const [disableEnumFilter, setDisableEnumFilter] = useState(false);
  const [disabled, setDisabled] = useState(disabledProp ?? false);
  const [selectedResourceIds, setSelectedResourceIds] = useState([]);
  const [displayName, setDisplayName] = useState(propertyMeta.displayName);
  const [displayDate, setDisplayDate] = useState("");
  const rightHandResult = getFilterRightHand(state, filterOperatorType);
  const [isInputShowed, setIsInputShowed] = useState(false);
  const [filterContainerWidth, setFilterContainerWidth] = useState();
  const inputRef = useEmptyRef();
  const buttonRef = useEmptyRef();
  const openTriggerRef = useEmptyRef();
  const filterDisplayNameRef = useEmptyRef();
  const filterContainerRef = useEmptyRef();
  const shouldRestoreFocus = useRef(false);
  const rightHandResultForMultiselect = rightHandResult ? rightHandResult.split(",") : [...rightHandResult];
  const displayValues = getFilterDisplayValues(state, propertyMeta);
  useAsyncEffect(async () => {
    onInitFilter(state, displayName, setDisplayName, propertyMeta, setFilterOperatorType, setSelectedResourceIds, setDisplayDate);
  }, [displayName, propertyMeta, state, parentContextName]);
  useEffect(() => {
    setIsInputShowed(shouldFilterInputBeVisible(state));
  }, [state.rightSide, state.operator, state]);
  useEffect(() => {
    updateFilterWidthContainer(filterDisplayNameRef, isInputShowed, setFilterContainerWidth);
  }, [displayName, isInputShowed]);
  useImperativeHandle(ref, () => ({
    getWidth: /* @__PURE__ */__name(() => filterContainerWidth, "getWidth")
  }), [filterContainerWidth]);
  useEffect(() => {
    if (!isInputShowed && shouldRestoreFocus.current) {
      filterDisplayNameRef.current?.focus();
      shouldRestoreFocus.current = false;
    }
  }, [isInputShowed]);
  useEffect(() => {
    if (resetCounter !== void 0) {
      setIsInputShowed(false);
    }
  }, [resetCounter]);
  const onRightHandChangeCallback = onCreateOnRightHandChange(state, onStateChange, filterOperatorType, setDisabled, setDisableEnumFilter, setFilterOperatorType, shouldRestoreFocus, onChange, setIsInputShowed);
  const onOperatorTypeChangeCallback = createOnOperatorTypeChange(state, onStateChange, setFilterOperatorType, setDisabled, setDisabled, onChange);
  const onShowFieldFilter = createOnShowFieldFilter(disabled, setIsInputShowed, inputRef, buttonRef, openTriggerRef, propertyMeta, inputId);
  const dynamicWidthStyle = filterContainerWidth ? {
    width: `${filterContainerWidth}px`
  } : void 0;
  return /* @__PURE__ */jsx(FormProvider, {
    ...form,
    children: /* @__PURE__ */jsx("div", {
      ref: filterContainerRef,
      className,
      style: dynamicWidthStyle,
      children: state && /* @__PURE__ */jsxs(Fragment, {
        children: [type === filterTypes.default && !isInputShowed && /* @__PURE__ */jsx("div", {
          ref: filterDisplayNameRef,
          className: "bg-popover focus-visible:ring-primary flex h-8 min-w-32 cursor-pointer items-center justify-start rounded-md px-2 outline-none focus-visible:ring-1",
          onClick: onShowFieldFilter,
          onFocus: isSimpleFilterInput(propertyMeta) ? onShowFieldFilter : void 0,
          onKeyDown: event => onFilterKeyDown(event, isSimpleFilterInput(propertyMeta), onShowFieldFilter),
          id: getElementId(elementSuffixes.button, inputId),
          tabIndex: disabled ? -1 : 0,
          "aria-disabled": disabled,
          children: /* @__PURE__ */jsx("p", {
            className: "text-fd-accent text-sm font-medium whitespace-nowrap",
            children: displayName
          })
        }), /* @__PURE__ */jsxs("div", {
          className: cn("hidden", isInputShowed && "block"),
          style: dynamicWidthStyle,
          children: [isEnum(propertyMeta.type, propertyMeta.typeFormat) && /* @__PURE__ */jsx(EnumFilter, {
            filterOperatorType,
            onOperatorTypeChange: onOperatorTypeChangeCallback,
            rightHandResult: rightHandResultForMultiselect,
            onRightHandChange: onRightHandChangeCallback,
            displayValues,
            disableEnumFilter,
            displayName,
            propertyMeta,
            inputId,
            onOpenChangeCallback: open => onFilterOpenChange(open, shouldRestoreFocus, rightHandResult, setIsInputShowed),
            ref: openTriggerRef
          }), isDefaultInputField(propertyMeta) && isIntegerField(propertyMeta) && /* @__PURE__ */jsx(IntegerFilter, {
            filterOperatorType,
            onOperatorTypeChange: onOperatorTypeChangeCallback,
            rightHandResult,
            onRightHandChange: onRightHandChangeCallback,
            displayName,
            disableFilterInput,
            inputId,
            inputRef,
            onBlur: (value, event_0) => onInputBlur(value, event_0, setIsInputShowed, filterContainerRef)
          }), isBooleanField(propertyMeta) && /* @__PURE__ */jsx(BooleanFilter, {
            rightHandResult,
            onRightHandChange: onRightHandChangeCallback,
            displayName: propertyMeta.displayName,
            state,
            filterOperatorType,
            inputId,
            buttonRef,
            onOpenChangeCallback: open_0 => onFilterOpenChange(open_0, shouldRestoreFocus, rightHandResult, setIsInputShowed)
          }), (isDateOnly(propertyMeta.type, propertyMeta.typeFormat) || isDateTime(propertyMeta.type, propertyMeta.typeFormat)) && /* @__PURE__ */jsx(DateFilter, {
            displayName: propertyMeta.displayName,
            displayDate,
            onDateChange: async date => onDateChange(state, onStateChange, filterOperatorType, setDisabled, setDisableEnumFilter, setIsInputShowed, date, onChange),
            onOpenChangeCallback: open_1 => onFilterOpenChange(open_1, shouldRestoreFocus, rightHandResult, setIsInputShowed),
            ref: openTriggerRef
          }), !isGuid(propertyMeta.typeFormat, propertyMeta.relation) && isDefaultInputField(propertyMeta) && !isIntegerField(propertyMeta) && !isDateOnly(propertyMeta.type, propertyMeta.typeFormat) && /* @__PURE__ */jsx(TextFilter, {
            displayName,
            rightHandResult,
            onRightHandChange: onRightHandChangeCallback,
            inputId,
            inputRef,
            onBlur: (value_0, event_1) => onInputBlur(value_0, event_1, setIsInputShowed, filterContainerRef)
          }), isGuid(propertyMeta.typeFormat, propertyMeta.relation) && /* @__PURE__ */jsx(GuidFilter, {
            onClose: createOnGuidFilterClose(shouldRestoreFocus, setIsInputShowed),
            filterOperatorType,
            onOperatorTypeChange: onOperatorTypeChangeCallback,
            selectedResourceIds,
            propertyMeta,
            onBrowserChange: (selectedResources, resourceMeta) => onBrowserChanged(selectedResources, propertyMeta, state, filterOperatorType, onStateChange, setDisabled, setDisableEnumFilter, setSelectedResourceIds, form, resourceMeta, onChange, setIsInputShowed),
            disabled,
            inputId,
            ref: openTriggerRef,
            parentContextName
          }), isFlagsEnum(propertyMeta.type, propertyMeta.typeFormat) && /* @__PURE__ */jsx(EnumFlagFilter, {
            rightHandResult,
            displayName,
            propertyMeta,
            onOperatorTypeChangeCallback,
            onRightHandChangeCallback,
            inputId,
            buttonRef,
            onOpenChangeCallback: open_2 => onFilterOpenChange(open_2, shouldRestoreFocus, rightHandResult, setIsInputShowed)
          })]
        })]
      })
    })
  });
}
__name(Filter, "Filter");

export { Filter };
