import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { useURLQueryState } from "../../hooks/useURLQueryState.mjs";
import { IconRefreshCw01, IconXClose } from "../../icons/index.mjs";
/* empty css                                                                                                                                                                                       */
/* empty css                                                                                                                                                                                        */
/* empty css                                                                                                                                                                                                */
/* empty css                                                                                                                                                                                           */
/* empty css                                                                                                                                                                                           */
import { Button } from "../../primitive/Button/index.mjs";
import { mergeSxList } from "../../utils/styles.mjs";
import { FormDatePicker } from "../Form/DatePicker.mjs";
import { FormTimeRangePicker } from "../Form/FormTimeRangePicker.mjs";
import { Box } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/Box/Box.mjs";
import { Form } from "../Form/Form.mjs";
import { useDebouncedValue } from "../../node_modules/.pnpm/@mantine_hooks@7.15.2_react@18.3.1/node_modules/@mantine/hooks/esm/use-debounced-value/use-debounced-value.mjs";
import { FormMultiSelect } from "../Form/MultiSelect.mjs";
import { FormSelect } from "../Form/Select.mjs";
import { FormTextInput } from "../Form/TextInput.mjs";
const SX_Y_MID = { display: "flex", alignItems: "center" };
const FORM_ITEM_SX_BASE = { minWidth: "160px" };
function FormItemRender(props) {
  const {
    data: { name, placeholder, type, sx },
    onSubmit,
    defaultValue,
    resetSeed
  } = props;
  const [keyword, setKeyword] = useState(defaultValue);
  const [debouncedKeyword] = useDebouncedValue(keyword, 800);
  useEffect(() => {
    if (resetSeed > 0) {
      setKeyword(defaultValue);
    }
  }, [resetSeed]);
  useEffect(() => {
    if (type === "text") {
      triggerSubmit();
    }
  }, [debouncedKeyword]);
  const triggerSubmit = () => onSubmit && onSubmit();
  function onKeyDownHandler(e) {
    if (e.key === "Enter") {
      e.preventDefault();
      e.stopPropagation();
      triggerSubmit();
    }
  }
  switch (type) {
    case "text":
      return /* @__PURE__ */ jsx(
        FormTextInput,
        {
          name,
          value: keyword,
          onChange: (e) => {
            setKeyword(e.target.value);
          },
          placeholder: placeholder ?? "",
          onKeyDown: onKeyDownHandler,
          rightSection: !!keyword && /* @__PURE__ */ jsx(
            IconXClose,
            {
              style: { cursor: "pointer" },
              size: 14,
              onClick: () => {
                setKeyword("");
                props.form.setValue(name, "");
                triggerSubmit();
              }
            }
          ),
          sx: mergeSxList([FORM_ITEM_SX_BASE, sx])
        }
      );
    case "select":
      return /* @__PURE__ */ jsx(
        FormSelect,
        {
          data: props.data.data,
          name,
          value: keyword || null,
          placeholder: placeholder ?? "",
          onChange: (val) => {
            setKeyword(val ?? "");
            triggerSubmit();
          },
          clearable: true,
          searchable: true,
          sx: mergeSxList([FORM_ITEM_SX_BASE, sx])
        }
      );
    case "multiselect":
      return /* @__PURE__ */ jsx(
        FormMultiSelect,
        {
          data: props.data.data,
          name,
          value: keyword,
          placeholder: placeholder ?? "",
          onChange: (val) => {
            setKeyword(val ?? []);
            triggerSubmit();
          },
          clearable: true,
          searchable: true,
          sx: mergeSxList([FORM_ITEM_SX_BASE, sx])
        }
      );
    case "datepicker":
      return /* @__PURE__ */ jsx(
        FormDatePicker,
        {
          name,
          value: typeof keyword === "string" ? new Date(keyword) : keyword,
          placeholder: placeholder ?? "",
          onChange: (val) => {
            setKeyword(val);
            triggerSubmit();
          },
          clearable: true,
          sx: mergeSxList([FORM_ITEM_SX_BASE, sx])
        }
      );
    case "timerangepicker":
      return /* @__PURE__ */ jsx(
        FormTimeRangePicker,
        {
          name,
          value: keyword,
          clearable: true,
          placeholder: placeholder ?? "",
          onChange: (val) => {
            setKeyword(val);
            triggerSubmit();
          },
          sx: mergeSxList([FORM_ITEM_SX_BASE, sx])
        }
      );
    default:
      return null;
  }
}
const DEFAULT_FORM_STATE_KEY = "__fs";
function SearchArea(props) {
  const { data, onSubmit, onRefresh, recoverFromURLEnabled, defaultValues, formStateQueryKey, ...rest } = props;
  const [resetSeed, setResetSeed] = useState(0);
  const [formState, setFormState] = useURLQueryState(formStateQueryKey ?? DEFAULT_FORM_STATE_KEY, defaultValues);
  const state = recoverFromURLEnabled ? formState : defaultValues;
  const form = useForm({ defaultValues: state });
  const handleSubmit = () => {
    const values = form.getValues();
    onSubmit(values);
    recoverFromURLEnabled && setFormState(values);
  };
  const handleReset = () => {
    setResetSeed(resetSeed + 1);
    form.reset(defaultValues);
    onSubmit(form.getValues());
    recoverFromURLEnabled && setFormState(defaultValues);
  };
  const handleRefresh = () => {
    onRefresh && onRefresh();
  };
  useEffect(() => {
    if (recoverFromURLEnabled) {
      handleSubmit();
    }
  }, []);
  return /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Form, { onSubmit, ...rest, form, errorMessageProps: { mx: 16 }, withActions: false, children: /* @__PURE__ */ jsx(Box, { sx: { display: "flex", justifyContent: "space-between", alignItems: "center" }, children: /* @__PURE__ */ jsxs(Box, { sx: { display: "flex", gap: 16, flexWrap: "wrap" }, children: [
    data.map((x) => /* @__PURE__ */ jsx(
      FormItemRender,
      {
        form,
        data: x,
        onSubmit: handleSubmit,
        defaultValue: state[x.name],
        resetSeed
      },
      x.name
    )),
    /* @__PURE__ */ jsxs(Box, { sx: SX_Y_MID, children: [
      /* @__PURE__ */ jsx(Box, { sx: SX_Y_MID, children: /* @__PURE__ */ jsx(Button, { variant: "subtle", onClick: handleReset, children: props.clearFiltersText ?? "Clear Filters" }) }),
      onRefresh && /* @__PURE__ */ jsx(Box, { ml: 16, sx: SX_Y_MID, children: /* @__PURE__ */ jsx(Button, { variant: "subtle", onClick: handleRefresh, children: /* @__PURE__ */ jsx(IconRefreshCw01, { size: 16 }) }) })
    ] })
  ] }) }) }) });
}
export {
  DEFAULT_FORM_STATE_KEY,
  SearchArea
};
