import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { S as SvgAdd } from './add-BcQkAUip.js';
import { S as SvgEdit } from './edit-DQOiktcu.js';
import { B as Button } from './Button-BNzCI47m.js';
import { T as Text } from './Text-mDcQHC2U.js';
import { F as Flex } from './Flex-Bb3iHExM.js';
import { a as OptionsPopover } from './useAdaptiveView-AvsDkChF.js';
import { O as OptionsPanel } from './syncFilterUtils-BVclVovw.js';
import { u as useMenuInteraction } from './useMenuInteraction-NEJXUD4I.js';
import { c as cloneFiltersWithItemRefs, u as updateSingleFilter, b as getAdapter, D as DateListDialog, e as FilterTriggerButton } from './filter-state-DKXF5MeW.js';
import { D as Drawer } from './Drawer-DzvM9MRB.js';
import { T as TextField } from './TextField-WQTlqKso.js';
import { A as Alert } from './Alert-CPe0yh6A.js';
import { D as Divider } from './Divider-C7fp5Xb6.js';
import { DndSort } from './DndSort.js';
import { u as useDrillDown, D as DrillDown } from './useDrilldown-PmrZ4BXn.js';

import './SavedFiltersButton.css';const footer = "_footer_1cnkf_7";
const styles = {
	"empty-state": "_empty-state_1cnkf_1",
	footer: footer
};

const AddSavedFilterDrawer = ({
  open,
  onClose,
  filtersSnapshot,
  onSave,
  validateName
}) => {
  const [name, setName] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(void 0);
  const [justSubmitted, setJustSubmitted] = useState(false);
  useEffect(() => {
    if (open) {
      setName("");
      setSubmitting(false);
      setSubmitError(void 0);
      setJustSubmitted(false);
    }
  }, [open]);
  const trimmed = name.trim();
  const validationError = !justSubmitted && validateName ? validateName(trimmed) : void 0;
  const canSubmit = trimmed.length > 0 && !validationError && !submitting;
  const handleAdd = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    setSubmitError(void 0);
    try {
      await onSave({ name: trimmed, filters: filtersSnapshot });
      setJustSubmitted(true);
      onClose();
    } catch (err) {
      setSubmitError(
        err instanceof Error && err.message ? err.message : "Failed to save filter."
      );
      setSubmitting(false);
    }
  };
  const handleCancel = () => {
    if (submitting) return;
    onClose();
  };
  return /* @__PURE__ */ jsxs(Drawer, { open, onClose: handleCancel, children: [
    /* @__PURE__ */ jsx(Drawer.Header, { children: "Save Current Filter" }),
    /* @__PURE__ */ jsx(Drawer.Content, { children: /* @__PURE__ */ jsx(Flex, { direction: "column", gap: "4", grow: 1, children: /* @__PURE__ */ jsx(
      TextField,
      {
        label: "Filter Name",
        placeholder: "Name this filter",
        value: name,
        onChange: (e) => setName(e?.target.value ?? ""),
        disabled: submitting,
        required: true,
        error: submitError ?? validationError,
        onKeyDown: (e) => {
          if (e.key === "Enter" && canSubmit) {
            e.preventDefault();
            handleAdd();
          }
        }
      }
    ) }) }),
    /* @__PURE__ */ jsx(Drawer.Footer, { children: /* @__PURE__ */ jsxs(Flex, { justifyContent: "flex-end", gap: "3", grow: 1, children: [
      /* @__PURE__ */ jsx(Button, { onClick: handleCancel, disabled: submitting, children: "Cancel" }),
      /* @__PURE__ */ jsx(
        Button,
        {
          appearance: "primary",
          onClick: handleAdd,
          disabled: !canSubmit,
          loading: submitting,
          children: "Add Saved Filter"
        }
      )
    ] }) })
  ] });
};

const DEFAULT_ALERT_TEXT = {
  saveSuccess: "Filter saved.",
  saveError: "Failed to save filter.",
  updateSuccess: "Filter updated.",
  updateError: "Failed to update filter.",
  deleteSuccess: "Filter deleted.",
  deleteError: "Failed to delete filter.",
  reorderError: "Failed to reorder filters."
};
const EDIT_INDEX = 0;
const EditSavedFiltersDrawer = ({
  open,
  onClose,
  savedFilters,
  onUpdate,
  onDelete,
  onReorder,
  validateName,
  alertText
}) => {
  const { setIndex, back, drillDownProps } = useDrillDown();
  const [editingId, setEditingId] = useState(null);
  const [drilldownName, setDrilldownName] = useState("");
  const [drilldownDraft, setDrilldownDraft] = useState([]);
  const [dateListDialogState, setDateListDialogState] = useState(null);
  const [submitting, setSubmitting] = useState(
    null
  );
  const [submitError, setSubmitError] = useState(null);
  const seededForRef = useRef(null);
  const [listAlert, setListAlert] = useState(null);
  const [drilldownAlert, setDrilldownAlert] = useState(
    null
  );
  useEffect(() => {
    if (!open) {
      setEditingId(null);
      seededForRef.current = null;
      setSubmitError(null);
      setSubmitting(null);
      setListAlert(null);
      setDrilldownAlert(null);
      setIndex(void 0);
    }
  }, [open, setIndex]);
  const drilldownTarget = editingId ? savedFilters.find((s) => s.id === editingId) : void 0;
  useEffect(() => {
    if (!editingId || !drilldownTarget) return;
    if (seededForRef.current === editingId) return;
    seededForRef.current = editingId;
    setDrilldownName(drilldownTarget.name);
    setDrilldownDraft(cloneFiltersWithItemRefs(drilldownTarget.filters));
    setSubmitError(null);
  }, [editingId, drilldownTarget]);
  const resolvedAlertText = useMemo(
    () => ({ ...DEFAULT_ALERT_TEXT, ...alertText }),
    [alertText]
  );
  const handleEdit = useCallback(
    (id) => {
      setListAlert(null);
      setEditingId(id);
      setIndex(EDIT_INDEX);
    },
    [setIndex]
  );
  const handleDrop = useCallback(
    (event) => {
      if (!onReorder || !event.valid || !event.zoneSort) return;
      Promise.resolve(onReorder(event.zoneSort.map((id) => String(id)))).catch(
        (err) => {
          console.error(
            "SavedFiltersButton onReorderSavedFilters failed:",
            err
          );
          setListAlert({
            status: "danger",
            title: err instanceof Error && err.message ? err.message : resolvedAlertText.reorderError
          });
        }
      );
    },
    [onReorder, resolvedAlertText]
  );
  const sortedIds = useMemo(
    () => savedFilters.map((s) => s.id),
    [savedFilters]
  );
  const handleBackToList = useCallback(() => {
    seededForRef.current = null;
    setEditingId(null);
    setSubmitError(null);
    setDrilldownAlert(null);
    back();
  }, [back]);
  const handleDraftChange = useCallback((filterId, value) => {
    setDrilldownDraft((prev) => updateSingleFilter(prev, filterId, value));
  }, []);
  const requestDateListDialog = useCallback(
    (filterId, libraryId) => {
      setDateListDialogState({ filterId, libraryId });
    },
    []
  );
  const drilldownForm = useMemo(() => {
    if (!drilldownTarget) return null;
    return drilldownDraft.map((draftFilter) => {
      const originalFilter = drilldownTarget.filters.find((f) => f.id === draftFilter.id) ?? draftFilter;
      return getAdapter(draftFilter).renderDrawer({
        originalFilter,
        draftFilter,
        onDraftChange: handleDraftChange,
        requestDateListDialog
      });
    });
  }, [
    drilldownDraft,
    drilldownTarget,
    handleDraftChange,
    requestDateListDialog
  ]);
  const trimmedName = drilldownName.trim();
  const validationError = validateName && editingId ? validateName(trimmedName, editingId) : void 0;
  const canSubmit = editingId !== null && trimmedName.length > 0 && !validationError && submitting === null;
  const handleUpdate = useCallback(async () => {
    if (!editingId || !onUpdate || !canSubmit) return;
    setSubmitting("update");
    setSubmitError(null);
    setDrilldownAlert(null);
    try {
      await onUpdate(editingId, {
        name: trimmedName,
        filters: drilldownDraft
      });
      seededForRef.current = null;
      setEditingId(null);
      back();
      setSubmitting(null);
      setListAlert({
        status: "success",
        title: resolvedAlertText.updateSuccess
      });
    } catch (err) {
      setDrilldownAlert({
        status: "danger",
        title: err instanceof Error && err.message ? err.message : resolvedAlertText.updateError
      });
      setSubmitting(null);
    }
  }, [
    editingId,
    onUpdate,
    canSubmit,
    trimmedName,
    drilldownDraft,
    resolvedAlertText,
    back
  ]);
  const handleDelete = useCallback(async () => {
    if (!editingId || !onDelete || submitting !== null) return;
    if (drilldownTarget?.disableDelete) return;
    setSubmitting("delete");
    setSubmitError(null);
    setDrilldownAlert(null);
    try {
      await onDelete(editingId);
      seededForRef.current = null;
      setEditingId(null);
      back();
      setSubmitting(null);
      setListAlert({
        status: "success",
        title: resolvedAlertText.deleteSuccess
      });
    } catch (err) {
      seededForRef.current = null;
      setEditingId(null);
      back();
      setSubmitting(null);
      setListAlert({
        status: "danger",
        title: err instanceof Error && err.message ? err.message : resolvedAlertText.deleteError
      });
    }
  }, [
    editingId,
    onDelete,
    submitting,
    drilldownTarget,
    resolvedAlertText,
    back
  ]);
  const dateListDialogTarget = dateListDialogState ? drilldownDraft.find(
    (f) => f.id === dateListDialogState.filterId && f.type === "dateList"
  ) : void 0;
  const dateListDialogSelected = dateListDialogTarget?.selectedOption;
  const dateListDialogInitialValue = dateListDialogSelected && dateListDialogSelected.id === dateListDialogState?.libraryId && dateListDialogSelected.value !== null ? dateListDialogSelected.value : void 0;
  const drilldownTitle = drilldownTarget?.name ?? "Edit Saved Filter";
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(Drawer, { open, onClose, ...drillDownProps, children: [
      /* @__PURE__ */ jsx(Drawer.Header, { children: "Edit Saved Filters" }),
      /* @__PURE__ */ jsx(Drawer.Content, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", gap: "4", grow: 1, children: [
        listAlert && /* @__PURE__ */ jsx(Alert, { title: listAlert.title, status: listAlert.status }),
        savedFilters.length === 0 ? /* @__PURE__ */ jsx(Text, { subdued: true, size: "small", children: "No saved filters to edit." }) : onReorder ? /* @__PURE__ */ jsx(DndSort, { onDrop: handleDrop, children: /* @__PURE__ */ jsx(
          DndSort.Zone,
          {
            sortable: true,
            id: "saved-filters-zone",
            label: "Saved filters",
            orientation: "vertical",
            sortedIds,
            gap: "2",
            children: savedFilters.map((saved) => /* @__PURE__ */ jsx(
              DndSort.Card,
              {
                id: saved.id,
                label: saved.name,
                dragOnlyWithHandle: true,
                children: /* @__PURE__ */ jsxs(
                  Flex,
                  {
                    alignItems: "center",
                    justifyContent: "space-between",
                    gap: "2",
                    grow: 1,
                    children: [
                      /* @__PURE__ */ jsx(Text, { children: saved.name }),
                      !saved.disableEdit && /* @__PURE__ */ jsx(
                        Button,
                        {
                          appearance: "secondary",
                          size: "small",
                          icon: SvgEdit,
                          "aria-label": `Edit ${saved.name}`,
                          onClick: () => handleEdit(saved.id)
                        }
                      )
                    ]
                  }
                )
              },
              saved.id
            ))
          }
        ) }) : /* @__PURE__ */ jsx(Flex, { direction: "column", gap: "2", children: savedFilters.map((saved) => /* @__PURE__ */ jsxs(
          Flex,
          {
            alignItems: "center",
            justifyContent: "space-between",
            gap: "2",
            children: [
              /* @__PURE__ */ jsx(Text, { children: saved.name }),
              !saved.disableEdit && /* @__PURE__ */ jsx(
                Button,
                {
                  appearance: "secondary",
                  size: "small",
                  icon: SvgEdit,
                  "aria-label": `Edit ${saved.name}`,
                  onClick: () => handleEdit(saved.id)
                }
              )
            ]
          },
          saved.id
        )) })
      ] }) }),
      /* @__PURE__ */ jsx(Drawer.Footer, { children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", grow: 1, children: /* @__PURE__ */ jsx(Button, { onClick: onClose, children: "Close" }) }) }),
      /* @__PURE__ */ jsxs(DrillDown, { index: EDIT_INDEX, children: [
        /* @__PURE__ */ jsx(DrillDown.Header, { children: drilldownTitle }),
        /* @__PURE__ */ jsx(DrillDown.Content, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", gap: "4", grow: 1, children: [
          drilldownAlert && /* @__PURE__ */ jsx(
            Alert,
            {
              title: drilldownAlert.title,
              status: drilldownAlert.status
            }
          ),
          /* @__PURE__ */ jsx(
            TextField,
            {
              label: "Filter Name",
              placeholder: "Name this filter",
              value: drilldownName,
              onChange: (e) => setDrilldownName(e?.target.value ?? ""),
              disabled: submitting !== null,
              required: true,
              error: submitError ?? validationError
            }
          ),
          /* @__PURE__ */ jsx(Divider, {}),
          drilldownForm
        ] }) }),
        /* @__PURE__ */ jsx(DrillDown.Footer, { children: /* @__PURE__ */ jsxs(
          Flex,
          {
            justifyContent: drilldownTarget?.disableDelete ? "flex-end" : "space-between",
            gap: "3",
            grow: 1,
            children: [
              !drilldownTarget?.disableDelete && /* @__PURE__ */ jsx(
                Button,
                {
                  appearance: "danger-secondary",
                  onClick: handleDelete,
                  loading: submitting === "delete",
                  disabled: submitting !== null,
                  children: "Delete Filter"
                }
              ),
              /* @__PURE__ */ jsxs(Flex, { gap: "3", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    onClick: handleBackToList,
                    disabled: submitting !== null,
                    children: "Cancel"
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    appearance: "primary",
                    onClick: handleUpdate,
                    disabled: !canSubmit,
                    loading: submitting === "update",
                    children: "Update Filter"
                  }
                )
              ] })
            ]
          }
        ) })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      DateListDialog,
      {
        libraryId: dateListDialogState?.libraryId ?? null,
        parentFilterId: dateListDialogState?.filterId ?? "",
        initialValue: dateListDialogInitialValue,
        mode: dateListDialogTarget?.mode,
        dialogCtaLabel: "Save",
        onCommit: (option) => {
          if (dateListDialogState) {
            handleDraftChange(dateListDialogState.filterId, option);
          }
          setDateListDialogState(null);
        },
        onCancel: () => setDateListDialogState(null)
      }
    )
  ] });
};

const SavedFiltersButton = (props) => {
  const {
    savedFilters,
    currentFilters,
    onApplySavedFilter,
    onSaveCurrentFilter,
    onUpdateSavedFilter,
    onDeleteSavedFilter,
    onReorderSavedFilters,
    validateName,
    alertText,
    activeSavedFilterId,
    label: labelProp,
    emptyState
  } = props;
  const DEFAULT_LABEL = "Saved Filters";
  const label = labelProp ? labelProp : activeSavedFilterId ? savedFilters.find((sf) => sf.id === activeSavedFilterId)?.name || DEFAULT_LABEL : DEFAULT_LABEL;
  const triggerRef = useRef(null);
  const items = useMemo(
    () => savedFilters.map((saved) => ({
      id: saved.id,
      type: "option",
      original: { id: saved.id, label: saved.name }
    })),
    [savedFilters]
  );
  const selectedItemIds = useMemo(
    () => activeSavedFilterId ? /* @__PURE__ */ new Set([activeSavedFilterId]) : /* @__PURE__ */ new Set(),
    [activeSavedFilterId]
  );
  const getCheckedState = useCallback(
    (item) => item.id === activeSavedFilterId ? "checked" : "unchecked",
    [activeSavedFilterId]
  );
  const handleItemActivate = useCallback(
    (item) => {
      const saved = savedFilters.find((s) => s.id === item.id);
      if (saved) onApplySavedFilter(saved);
    },
    [savedFilters, onApplySavedFilter]
  );
  const [isOpen, setIsOpen] = useState(false);
  const {
    closeMenu,
    highlightedIndex,
    getTriggerProps,
    getMenuProps,
    getItemProps
  } = useMenuInteraction({
    items,
    sectionsMeta: [],
    onItemActivate: handleItemActivate,
    selectedItemIds,
    displayAs: "popover",
    closeOnActivate: true,
    id: "saved-filters",
    triggerRef,
    label,
    isOpen,
    setIsOpen
  });
  const handleClickOutside = useCallback(() => {
    closeMenu({ restoreFocus: false });
  }, [closeMenu]);
  const triggerProps = getTriggerProps();
  const [addOpen, setAddOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [filtersSnapshot, setFiltersSnapshot] = useState(
    []
  );
  const handleSaveCurrentClick = useCallback(() => {
    setFiltersSnapshot(currentFilters);
    closeMenu({ restoreFocus: false });
    setAddOpen(true);
  }, [closeMenu, currentFilters]);
  const handleEditClick = useCallback(() => {
    closeMenu({ restoreFocus: false });
    setEditOpen(true);
  }, [closeMenu]);
  const handleFooterKeyDown = (e) => {
    if (e.key === "Escape") {
      e.preventDefault();
      closeMenu();
    }
  };
  const footer = /* @__PURE__ */ jsxs(
    Flex,
    {
      direction: "column",
      gap: "2",
      className: styles["footer"],
      onKeyDown: handleFooterKeyDown,
      children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            appearance: "secondary",
            size: "small",
            icon: { before: SvgAdd },
            style: { width: "100%" },
            onClick: handleSaveCurrentClick,
            children: "Save Current Filter"
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            appearance: "secondary",
            size: "small",
            icon: { before: SvgEdit },
            style: { width: "100%" },
            onClick: handleEditClick,
            disabled: savedFilters.length === 0,
            children: "Edit Saved Filters"
          }
        )
      ]
    }
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      FilterTriggerButton,
      {
        ...triggerProps,
        filterId: "saved-filters",
        label,
        isSelected: !!(activeSavedFilterId ?? false)
      }
    ),
    /* @__PURE__ */ jsx(
      OptionsPopover,
      {
        id: "saved-filters-popover",
        referenceElement: triggerRef,
        open: isOpen,
        onClose: handleClickOutside,
        width: 280,
        footer,
        children: items.length === 0 ? /* @__PURE__ */ jsx(
          Flex,
          {
            direction: "column",
            alignItems: "center",
            justifyContent: "center",
            className: styles["empty-state"],
            children: typeof emptyState === "string" || emptyState == null ? /* @__PURE__ */ jsx(Text, { subdued: true, size: "small", children: emptyState ?? "No saved filters yet." }) : emptyState
          }
        ) : /* @__PURE__ */ jsx(
          OptionsPanel,
          {
            isOpen,
            items,
            getMenuProps,
            getItemProps,
            highlightedIndex,
            getCheckedState,
            selectionType: "single",
            hasMore: false,
            onLoadMore: () => {
            },
            loading: false,
            loadingMore: false
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      AddSavedFilterDrawer,
      {
        open: addOpen,
        onClose: () => setAddOpen(false),
        filtersSnapshot,
        onSave: onSaveCurrentFilter,
        validateName: validateName ? (name) => validateName(name) : void 0
      }
    ),
    /* @__PURE__ */ jsx(
      EditSavedFiltersDrawer,
      {
        open: editOpen,
        onClose: () => setEditOpen(false),
        savedFilters,
        onUpdate: onUpdateSavedFilter,
        onDelete: onDeleteSavedFilter,
        onReorder: onReorderSavedFilters,
        validateName,
        alertText
      }
    )
  ] });
};
SavedFiltersButton.displayName = "SavedFiltersButton";

export { SavedFiltersButton as S };
//# sourceMappingURL=SavedFiltersButton-BHgS4akL.js.map
