import { jsx as t } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js";
import ge from "classnames";
import { useState as T, useMemo as a, useCallback as u, useRef as Q, useEffect as b } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { useCustomColumnsData as we } from "../../../../../hooks/useCustomColumnsData.js";
import Me from "../../../../utils/customData/hasCustomField.js";
import Ne from "../../../../utils/customData/mergeRecords.js";
import ye, { ALL_BALANCE_ACCOUNTS_SELECTION_ID as Ge } from "../../../../../hooks/useBalanceAccountSelection.js";
import Be from "../../../../../hooks/useDefaultOverviewFilterParams.js";
import xe from "../../../../internal/FilterBar/filters/DateFilter/DateFilter.js";
import { EARLIEST_DISPUTES_SINCE_DATE as je, TABS_CONTAINER_CLASS as ke, BASE_CLASS as He, BASE_XS_CLASS as Ve } from "./constants.js";
import { LIMIT_OPTIONS as Ye, DEFAULT_PAGE_LIMIT as Ke } from "../../../../internal/Pagination/constants.js";
import { DISPUTE_REASON_CATEGORIES as z, DISPUTE_PAYMENT_SCHEMES as ee, DISPUTE_STATUS_GROUPS as N } from "../../../../utils/disputes/constants.js";
import { useResponsiveContainer as qe, containerQueries as Qe } from "../../../../../hooks/useResponsiveContainer.js";
import { FilterParam as I } from "../../../../types.js";
import { DisputesTable as Xe, FIELDS as Ze } from "../DisputesTable/DisputesTable.js";
import { DisputeManagementModal as Je } from "../DisputeManagementModal/DisputeManagementModal.js";
import We from "../../../../internal/Tabs/Tabs.js";
/* empty css                      */
import te from "../../../../../core/Context/preact/useCoreContext.js";
import $e from "../../../../internal/Pagination/hooks/useCursorPaginatedRecords.js";
import X from "../../../TransactionsOverview/components/MultiSelectionFilter/useMultiSelectionFilter/useMultiSelectionFilter.js";
import ze from "../../../../../hooks/useModalDetails/useModalDetails.js";
import { useFilterBarState as et, FilterBarMobileSwitch as tt, FilterBar as st } from "../../../../internal/FilterBar/FilterBar.js";
import rt from "../../../../internal/FormFields/Select/BalanceAccountSelector/BalanceAccountSelector.js";
import Z from "../../../TransactionsOverview/components/MultiSelectionFilter/MultiSelectionFilter.js";
import it from "../../../../internal/FormFields/Select/Select.js";
import { useConfigContext as ot } from "../../../../../core/ConfigContext/preact/context.js";
import { listFrom as J } from "../../../../../utils/collection/main.js";
import { isFunction as nt } from "../../../../../utils/value/is.js";
import { Header as at } from "../../../../internal/Header/Header.js";
import { noop as W } from "../../../../../utils/common.js";
const $ = "CHARGEBACKS", w = "schemeCodes", A = "reasonCategories", M = "_t", lt = Object.keys(ee), ct = Object.keys(z), mt = Object.keys(N), se = Object.entries(N).map(([l, o]) => ({
  id: l,
  label: o,
  content: null
})), ut = ({
  ["aria-label"]: l,
  activeTab: o,
  onChange: E
}) => {
  const { i18n: F } = te(), [_, D] = T(o), P = a(() => Object.entries(N).map(([i, d]) => ({
    id: i,
    name: F.get(d)
  })), [F]);
  return b(() => {
    const i = se.find((d) => d.id === _);
    i && E(i);
  }, [E, _]), b(() => D(o), [o]), /* @__PURE__ */ t(
    it,
    {
      "aria-label": l,
      items: P,
      selected: _,
      onChange: ({ target: i }) => D(i.value),
      showOverlay: !0,
      multiSelect: !1,
      filterable: !1
    }
  );
}, Yt = ({
  onFiltersChanged: l,
  balanceAccounts: o,
  allowLimitSelection: E = !0,
  preferredLimit: F = Ke,
  isLoadingBalanceAccount: _,
  onContactSupport: D,
  hideTitle: P,
  onRecordSelection: i,
  showDetails: d,
  dataCustomization: c
}) => {
  const { i18n: p } = te(), { getDisputeList: L } = ot().endpoints, { activeBalanceAccount: r, balanceAccountSelectionOptions: re, onBalanceAccountSelection: ie } = ye({
    balanceAccounts: o,
    allowAllSelection: !0
  }), { defaultParams: R, nowTimestamp: O, refreshNowTimestamp: U } = Be("disputes", r, "last90Days"), [y, oe] = T(!1), [ne, ae] = T(), [S, le] = T($), [ce, G] = T(!1), [B, x] = T(S), j = a(() => p.get("disputes.overview.common.filters.types.statusGroup"), [p]), k = a(
    () => ({
      showDetails: d ?? !0,
      callback: i
    }),
    [d, i]
  ), me = a(() => ({ dispute: k }), [k]), ue = u(
    async ({ [M]: e, ...s }, n) => L({ signal: n, errorLevel: "error" }, {
      query: {
        ...s,
        ...r?.id !== Ge && {
          balanceAccountId: r?.id ?? ""
        },
        reasonCategories: J(s[A]),
        schemeCodes: J(s[w]),
        createdSince: s[I.CREATED_SINCE] ?? R.current.defaultFilterParams[I.CREATED_SINCE],
        createdUntil: s[I.CREATED_UNTIL] ?? R.current.defaultFilterParams[I.CREATED_UNTIL]
      }
    }),
    [r?.id, R, L]
  ), H = et(), de = a(() => nt(l) ? l : void 0, [l]), pe = a(() => E ? Ye : void 0, [E]), h = Object.assign(R.current.defaultFilterParams, {
    [A]: void 0,
    [w]: void 0,
    [M]: performance.now(),
    statusGroup: $
  }), { canResetFilters: Se, error: fe, fetching: Ae, filters: f, limit: Te, limitOptions: Ee, records: V, resetFilters: dt, updateFilters: m, updateLimit: _e, ...De } = $e({
    fetchRecords: ue,
    dataField: "data",
    filterParams: h,
    initialFiltersSameAsDefault: !0,
    onFiltersChanged: de,
    preferredLimit: F,
    preferredLimitOptions: pe,
    enabled: !!r?.id && !!L
  }), g = Q(void 0), Re = X({
    mapFilterOptionName: u((e) => p.get(z[e]), [p]),
    filterParam: A,
    filterValues: ct,
    defaultFilters: { ...h, [A]: g.current },
    updateFilters: m,
    filters: f
  }), Fe = X({
    mapFilterOptionName: u((e) => ee[e], []),
    filterParam: w,
    filterValues: lt,
    defaultFilters: h,
    updateFilters: m,
    filters: f
  }), ve = u(
    ({ records: e, retrievedData: s }) => Ne(e, s, (n, q) => n.disputePspReference === q.disputePspReference),
    []
  ), Ce = a(() => Me(c?.list?.fields, Ze), [c?.list?.fields]), { customRecords: Ie, loadingCustomRecords: be } = we({
    records: V,
    hasCustomColumn: Ce,
    onDataRetrieve: c?.list?.onDataRetrieve,
    mergeCustomData: ve
  }), { updateDetails: Y, resetDetails: Pe, selectedDetail: Le } = ze(me), Oe = u(
    ({ disputePspReference: e }) => {
      Y({
        selection: {
          type: "dispute",
          data: e
        },
        modalSize: "small"
      }).callback({ id: e });
    },
    [Y]
  ), Ue = a(() => {
    const e = new Date(O), s = e.setFullYear(e.getFullYear() - 1), n = new Date(je).getTime();
    return new Date(Math.max(n, s)).toString();
  }, [O]), v = Q(null), K = u(
    ({ id: e }) => {
      v.current && clearTimeout(v.current), v.current = setTimeout(() => {
        requestAnimationFrame(() => G(!1));
        const s = A, n = { statusGroup: e, [s]: void 0 };
        e !== "FRAUD_ALERTS" && (n[s] = g.current), m(n), v.current = null;
      }, 500), le(e), G(!0), x(void 0);
    },
    [m]
  ), he = u(
    (e) => {
      e && mt.includes(e) && e !== S ? x(e) : m({ [M]: performance.now() });
    },
    [S, m]
  ), C = qe(Qe.down.xs);
  return b(() => {
    ae(C && y ? { maxHeight: 0, overflowY: "hidden" } : void 0);
  }, [C, y]), b(() => {
    U(), f.statusGroup !== "FRAUD_ALERTS" && (g.current = f[A]);
  }, [f, U]), /* @__PURE__ */ t("div", { style: ne, className: ge(He, { [Ve]: C }), children: [
    /* @__PURE__ */ t(at, { hideTitle: P, titleKey: "disputes.overview.common.title", children: /* @__PURE__ */ t(tt, { ...H }) }),
    /* @__PURE__ */ t("div", { children: [
      /* @__PURE__ */ t("div", { children: [
        /* @__PURE__ */ t("div", { className: ke, children: C ? /* @__PURE__ */ t(
          ut,
          {
            "aria-label": j,
            activeTab: B ?? S,
            onChange: K
          }
        ) : /* @__PURE__ */ t(
          We,
          {
            "aria-label": j,
            tabs: se,
            activeTab: B,
            onChange: K
          }
        ) }),
        /* @__PURE__ */ t(st, { ...H, ariaLabelKey: "disputes.overview.common.filters.a11y.label", children: [
          /* @__PURE__ */ t(
            rt,
            {
              activeBalanceAccount: r,
              balanceAccountSelectionOptions: re,
              onBalanceAccountSelection: ie
            }
          ),
          /* @__PURE__ */ t(
            xe,
            {
              canResetFilters: Se,
              defaultParams: R,
              filters: f,
              nowTimestamp: O,
              refreshNowTimestamp: U,
              sinceDate: Ue,
              timezone: r?.timeZone,
              updateFilters: m
            }
          ),
          /* @__PURE__ */ t(
            Z,
            {
              ...Fe,
              placeholder: p.get("disputes.overview.common.filters.types.paymentMethod"),
              onResetAction: W
            }
          ),
          S !== "FRAUD_ALERTS" && /* @__PURE__ */ t(
            Z,
            {
              ...Re,
              placeholder: p.get("disputes.overview.common.filters.types.disputeReason"),
              onResetAction: W
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ t(
        Je,
        {
          dataCustomization: c?.details && { details: c?.details },
          selectedDetail: Le,
          resetDetails: Pe,
          onContactSupport: D,
          refreshDisputesList: he,
          setModalVisible: oe,
          children: /* @__PURE__ */ t(
            Xe,
            {
              activeBalanceAccount: r,
              balanceAccountId: r?.id,
              loading: ce || Ae || _ || !o || !r || be,
              data: c?.list?.onDataRetrieve ? Ie : V,
              showPagination: !0,
              limit: Te,
              limitOptions: Ee,
              onContactSupport: D,
              onLimitSelection: _e,
              error: fe,
              onRowClick: Oe,
              statusGroup: S,
              customColumns: c?.list?.fields,
              ...De
            }
          )
        }
      )
    ] })
  ] });
};
export {
  Yt as DisputesOverview
};
