import { jsx as e } from "../../../../external/.pnpm/preact@10.28.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js";
import { DEFAULT_PAYMENT_LINK_STATUS_GROUP as ce, PAYMENT_LINK_STATUS_GROUPS_FILTER_MAPPING as at, PAYMENT_LINK_STATUSES as Le, PAYMENT_LINK_TYPES as ot, BASE_ACTIONS_CLASS as st, TABS_CONTAINER_CLASS as rt, PAYMENT_LINK_STATUS_GROUPS_TABS as j, FILTERS_CONTAINER_CLASS as lt, ACTION_BUTTONS_CONTAINER_CLASS as ct, ACTION_BUTTON_CLASS as me, FILTERS_ALERT_CONTAINER_CLASS as pe, BASE_CLASS as mt, BASE_XS_CLASS as pt, EARLIEST_PAYMENT_LINK_DATE as Tt, ACTION_BUTTON_MOBILE_CLASS as Te } from "./constants.js";
import { FilterParam as i } from "../../../types.js";
import ut from "../../../../hooks/useDefaultOverviewFilterParams.js";
import { useState as S, useCallback as r, useMemo as p, useEffect as I, useRef as dt } from "../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { LIMIT_OPTIONS as St, DEFAULT_PAGE_LIMIT as Et } from "../../../internal/Pagination/constants.js";
import { PaymentLinksTable as _t } from "./PaymentLinksTable.js";
import At from "../../../internal/Tabs/Tabs.js";
/* empty css                          */
import Y from "classnames";
import { useResponsiveContainer as yt, containerQueries as Lt } from "../../../../hooks/useResponsiveContainer.js";
import { PopoverContainerSize as ue } from "../../../internal/Popover/types.js";
import { PaymentLinkDetailsModal as Nt } from "./PaymentLinkDetailsModal/PaymentLinkDetailsModal.js";
import { ButtonVariant as K } from "../../../internal/Button/types.js";
import { PaymentLinksOverviewModal as ft } from "./PaymentLinksOverviewModal.js";
import { Alert as de } from "../../../internal/Alert/Alert.js";
import { AlertVariantOption as Se, AlertTypeOption as Ee } from "../../../internal/Alert/types.js";
import Ne from "../../../../core/Context/preact/useCoreContext.js";
import vt from "../../../internal/Pagination/hooks/useCursorPaginatedRecords.js";
import G from "../../TransactionsOverview/components/MultiSelectionFilter/useMultiSelectionFilter/useMultiSelectionFilter.js";
import It from "../../../../hooks/useModalDetails/useModalDetails.js";
import Ct from "../../../internal/Calendar/calendar/timerange/presets/lastNDays.js";
import { Fragment as Pt } from "../../../../external/.pnpm/preact@10.28.2/node_modules/preact/dist/preact.module.js";
import x from "../../TransactionsOverview/components/MultiSelectionFilter/MultiSelectionFilter.js";
import Rt from "../../../internal/FilterBar/filters/DateFilter/DateFilter.js";
import _e from "../../../internal/FilterBar/filters/TextFilter/TextFilter.js";
import F from "../../../internal/Button/Button.js";
import { Icon as V } from "../../../internal/Icon/Icon.js";
import kt from "../../../internal/FormFields/Select/Select.js";
import { useConfigContext as Ft } from "../../../../core/ConfigContext/preact/context.js";
import { getTimeRangeSelectionDefaultPresetOptions as Mt, TIME_RANGE_SELECTION_PRESET_OPTION_KEYS as gt } from "../../../internal/DatePicker/components/TimeRangeSelector/useTimeRangeSelection.js";
import { listFrom as M } from "../../../../utils/collection/main.js";
import { useFilterBarState as ht, FilterBarMobileSwitch as Dt, FilterBar as Ot } from "../../../internal/FilterBar/FilterBar.js";
import { isFunction as bt } from "../../../../utils/value/is.js";
import { Header as wt } from "../../../internal/Header/Header.js";
const Ae = "linkTypes", H = "statuses", ye = "storeIds", z = "_t", Bt = Object.keys(Le), Ut = ({
  ["aria-label"]: L,
  activeTab: E,
  onChange: C
}) => {
  const { i18n: N } = Ne(), [_, A] = S(E), g = p(() => j.map(({ id: c, label: l }) => ({ id: c, name: N.get(l) })), [N]);
  return I(() => {
    const c = j.find((l) => l.id === _);
    c && C(c);
  }, [C, _]), I(() => A(E), [E]), /* @__PURE__ */ e(
    kt,
    {
      "aria-label": L,
      items: g,
      selected: _,
      onChange: ({ target: c }) => A(c.value),
      showOverlay: !0,
      multiSelect: !1,
      filterable: !1
    }
  );
}, Ni = ({
  onFiltersChanged: L,
  allowLimitSelection: E = !0,
  preferredLimit: C = Et,
  onRecordSelection: N,
  showDetails: _,
  onContactSupport: A,
  hideTitle: g,
  isFiltersLoading: c,
  filterParams: l,
  stores: m,
  allStores: Q,
  paymentLinkCreation: fe,
  paymentLinkSettings: ve,
  storeIds: f,
  filterError: T,
  storeError: y
}) => {
  const { i18n: n } = Ne(), { getPaymentLinks: h, createPBLPaymentLink: D, savePayByLinkSettings: O } = Ft().endpoints, Ie = Mt({ exclude: [gt.YEAR_TO_DATE] }), { defaultParams: u, nowTimestamp: Ce, refreshNowTimestamp: b } = ut(
    "paymentLinks",
    void 0,
    void 0,
    Ie
  ), [v, Pe] = S(ce), [X, Re] = S(v), [ke, J] = S(!1), d = yt(Lt.down.xs), [W, w] = S(!1), Fe = r(
    async ({ [z]: t, ...o }, k) => {
      const U = { signal: k, errorLevel: "error" }, le = M(o[i.STORE_IDS]), nt = f ? M(f) : void 0;
      return h(U, {
        query: {
          ...o,
          storeIds: le?.length ? le : nt,
          statuses: M(o[i.STATUSES]),
          linkTypes: M(o[i.LINK_TYPES]),
          createdSince: o[i.CREATED_SINCE] ?? u.current.defaultFilterParams[i.CREATED_SINCE],
          createdUntil: o[i.CREATED_UNTIL] ?? u.current.defaultFilterParams[i.CREATED_UNTIL],
          merchantReference: o[i.MERCHANT_REFERENCE] ?? u.current.defaultFilterParams[i.MERCHANT_REFERENCE],
          paymentLinkId: o[i.PAYMENT_LINK_ID] ?? u.current.defaultFilterParams[i.PAYMENT_LINK_ID]
        }
      });
    },
    [u, h, f]
  ), Z = ht(), Me = p(() => bt(L) ? L : void 0, [L]), ge = p(() => E ? St : void 0, [E]), P = Object.assign(u.current.defaultFilterParams, {
    [Ae]: void 0,
    [H]: void 0,
    statusGroup: ce,
    [ye]: void 0,
    [z]: performance.now()
  }), { canResetFilters: he, error: De, fetching: Oe, filters: s, limit: be, limitOptions: we, records: Be, resetFilters: Yt, updateFilters: a, updateLimit: Ue, ...Ye } = vt({
    fetchRecords: Fe,
    dataField: "data",
    filterParams: P,
    initialFiltersSameAsDefault: !0,
    onFiltersChanged: Me,
    preferredLimit: C,
    preferredLimitOptions: ge,
    enabled: !!h && !!Q?.length
  }), Ke = G({
    mapFilterOptionName: r((t) => n.get(Le[t]), [n]),
    filterParam: H,
    filterValues: l?.statuses?.[at[v]] ?? Bt,
    defaultFilters: P,
    updateFilters: a,
    filters: s
  }), Ge = G({
    mapFilterOptionName: r((t) => n.get(ot[t]), [n]),
    filterParam: Ae,
    filterValues: l?.linkTypes,
    defaultFilters: P,
    updateFilters: a,
    filters: s
  }), xe = G({
    mapFilterOptionName: r((t) => m?.find((o) => o.id === t)?.storeCode ?? t, [m]),
    filterParam: ye,
    filterValues: p(() => m && m.length > 0 ? m.filter((t) => t.id).map((t) => t.id) : void 0, [m]),
    defaultFilters: P,
    updateFilters: a,
    filters: s
  });
  I(() => {
    a({
      [i.CURRENCIES]: void 0
    });
  }, [a]), I(() => {
    b();
  }, [s, b]);
  const $ = p(
    () => ({
      showDetails: _ ?? !0,
      callback: N
    }),
    [_, N]
  ), Ve = p(() => ({ paymentLink: $ }), [$]), { updateDetails: q, resetDetails: He, selectedDetail: ze } = It(Ve), je = r(
    ({ paymentLinkId: t }) => {
      q({
        selection: {
          type: "paymentLink",
          data: t
        },
        modalSize: "small"
      }).callback({ id: t });
    },
    [q]
  ), Qe = r(
    (t) => {
      t || (t = void 0), a({ merchantReference: t });
    },
    [a]
  ), Xe = r(
    (t) => {
      t || (t = void 0), a({ paymentLinkId: t });
    },
    [a]
  ), R = dt(null), ee = r(
    ({ id: t }) => {
      R.current && clearTimeout(R.current), R.current = setTimeout(() => {
        requestAnimationFrame(() => J(!1));
        const k = { statusGroup: t, [H]: void 0 };
        a(k), R.current = null;
      }, 500), Pe(t), J(!0), Re(void 0);
    },
    [a]
  ), te = p(() => n.get("payByLink.overview.list.filters.types.statusGroup"), [n]), Je = l?.linkTypes && l?.linkTypes?.length > 0 || !!T, We = l?.statuses && l?.statuses?.[v] && l?.statuses?.[v]?.length > 0 || !!T, Ze = m && m?.length > 1 || !!y, $e = p(() => new Date(Ct(Tt).from).toString(), []), [qe, B] = S(!1), [et, ie] = S(void 0), ne = r(() => {
    ie("Creation"), B(!0);
  }, []), ae = r(() => {
    ie("Settings"), B(!0);
  }, []), tt = r(() => {
    B(!1);
  }, []), oe = r(() => {
    const t = /* @__PURE__ */ new Date(), o = s?.[i.CREATED_UNTIL], U = (o ? new Date(o) : null)?.toDateString() === t.toDateString();
    a({
      ...U && { [i.CREATED_UNTIL]: t.toISOString() },
      [z]: performance.now()
    });
  }, [s, a]), se = p(() => ({
    onContactSupport: A,
    storeIds: f
  }), [A, f]);
  I(() => {
    w(!!y || !!T);
  }, [y, T]);
  const re = r(() => {
    w(!1);
  }, [w]), it = !!(O || D);
  return /* @__PURE__ */ e("div", { className: Y(mt, { [pt]: d }), children: [
    /* @__PURE__ */ e(wt, { hideTitle: g, titleKey: "payByLink.overview.title", children: /* @__PURE__ */ e("div", { className: st, children: [
      d && D && /* @__PURE__ */ e(
        F,
        {
          iconButton: !0,
          "aria-label": n.get("payByLink.overview.list.actions.createPaymentLink"),
          className: Te,
          onClick: ne,
          children: /* @__PURE__ */ e(V, { name: "plus" })
        }
      ),
      /* @__PURE__ */ e(Dt, { ...Z }),
      d && O && /* @__PURE__ */ e(
        F,
        {
          iconButton: !0,
          "aria-label": n.get("payByLink.overview.actions.settings.a11y.label"),
          variant: K.SECONDARY,
          className: Te,
          onClick: ae,
          children: /* @__PURE__ */ e(V, { name: "cog" })
        }
      )
    ] }) }),
    /* @__PURE__ */ e("div", { className: rt, children: d ? /* @__PURE__ */ e(
      Ut,
      {
        "aria-label": te,
        activeTab: X ?? v,
        onChange: ee
      }
    ) : /* @__PURE__ */ e(
      At,
      {
        "aria-label": te,
        tabs: j,
        activeTab: X,
        onChange: ee
      }
    ) }),
    /* @__PURE__ */ e(Pt, { children: [
      !c && /* @__PURE__ */ e("div", { className: lt, children: [
        /* @__PURE__ */ e(Ot, { ...Z, ariaLabelKey: "payByLink.overview.filters.label", children: [
          Ze && /* @__PURE__ */ e(
            x,
            {
              ...xe,
              isInvalid: !!y,
              readonly: !!y,
              placeholder: n.get("payByLink.overview.filters.types.stores.label")
            }
          ),
          /* @__PURE__ */ e(
            Rt,
            {
              canResetFilters: he,
              defaultParams: u,
              filters: s,
              sinceDate: $e,
              nowTimestamp: Ce,
              refreshNowTimestamp: b,
              updateFilters: a
            }
          ),
          Je && /* @__PURE__ */ e(
            x,
            {
              ...Ge,
              isInvalid: !!T,
              readonly: !!T,
              placeholder: n.get("payByLink.overview.filters.types.linkTypes.label")
            }
          ),
          We && /* @__PURE__ */ e(
            x,
            {
              ...Ke,
              isInvalid: !!T,
              readonly: !!T,
              placeholder: n.get("payByLink.overview.filters.types.status.label")
            }
          ),
          /* @__PURE__ */ e(
            _e,
            {
              name: n.get("payByLink.overview.filters.types.merchantReference.label"),
              label: s[i.MERCHANT_REFERENCE] ? s[i.MERCHANT_REFERENCE] : n.get("payByLink.overview.filters.types.merchantReference.label"),
              value: s[i.MERCHANT_REFERENCE],
              onChange: Qe,
              type: "text",
              containerSize: ue.MEDIUM
            }
          ),
          /* @__PURE__ */ e(
            _e,
            {
              name: n.get("payByLink.overview.filters.types.paymentLinkID.label"),
              label: s[i.PAYMENT_LINK_ID] ? s[i.PAYMENT_LINK_ID] : n.get("payByLink.overview.filters.types.paymentLinkID.label"),
              value: s[i.PAYMENT_LINK_ID],
              onChange: Xe,
              type: "text",
              containerSize: ue.MEDIUM
            }
          ),
          d && W && /* @__PURE__ */ e(
            de,
            {
              className: Y(pe),
              type: Ee.CRITICAL,
              variant: Se.TIP,
              closeButton: !0,
              onClose: re,
              description: n.get("payByLink.overview.filters.errors.networkError")
            }
          )
        ] }),
        it && !d && /* @__PURE__ */ e("div", { className: ct, children: [
          D && /* @__PURE__ */ e(F, { variant: K.PRIMARY, className: me, onClick: ne, children: n.get("payByLink.overview.list.actions.createPaymentLink") }),
          O && /* @__PURE__ */ e(
            F,
            {
              "aria-label": n.get("payByLink.overview.actions.settings.a11y.label"),
              variant: K.SECONDARY,
              className: me,
              onClick: ae,
              children: /* @__PURE__ */ e(V, { name: "cog" })
            }
          )
        ] })
      ] }),
      !d && W && /* @__PURE__ */ e(
        de,
        {
          className: Y(pe),
          type: Ee.CRITICAL,
          variant: Se.TIP,
          closeButton: !0,
          onClose: re,
          description: n.get("payByLink.overview.filters.errors.networkError")
        }
      )
    ] }),
    /* @__PURE__ */ e(
      Nt,
      {
        selectedDetail: ze,
        resetDetails: He,
        onUpdate: oe,
        children: /* @__PURE__ */ e(
          _t,
          {
            stores: m,
            storeError: y,
            error: De,
            limit: be,
            allStores: Q,
            limitOptions: we,
            loading: ke || Oe || c,
            onContactSupport: A,
            onLimitSelection: Ue,
            onRowClick: je,
            showPagination: !0,
            paymentLinks: Be,
            ...Ye
          }
        )
      }
    ),
    /* @__PURE__ */ e(
      ft,
      {
        modalType: et,
        isModalVisible: qe,
        onCloseModal: tt,
        paymentLinkSettings: ve,
        paymentLinkCreation: fe,
        storeIds: se.storeIds,
        onContactSupport: se.onContactSupport,
        refreshPaymentLinkList: oe
      }
    )
  ] });
};
export {
  Ni as PaymentLinksOverview
};
