import { jsx as e } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js";
import _ from "classnames";
import { Alert as Q } from "../../../../internal/Alert/Alert.js";
import Ce from "../../../../internal/Popover/Popover.js";
import te from "../../../../internal/Typography/Typography.js";
import we from "../../../../../hooks/useUniqueId.js";
import Ae from "../../../../internal/Button/DownloadButton/useDownload.js";
import ye from "../../../../internal/ToggleSwitch/ToggleSwitch.js";
import Ee from "../../../../internal/Button/ButtonActions/ButtonActions.js";
import Se from "../../../../internal/FilterBar/components/FilterButton/FilterButton.js";
import { EXPORT_COLUMNS as h, TRANSACTION_ANALYTICS_SUBCATEGORY_LIST as be, TRANSACTION_ANALYTICS_CATEGORY as Ne, DEFAULT_EXPORT_COLUMNS as X } from "../../constants.js";
import { ButtonActionsLayoutBasic as Oe } from "../../../../internal/Button/ButtonActions/types.js";
import { useResponsiveContainer as Pe, containerQueries as Re } from "../../../../../hooks/useResponsiveContainer.js";
import { PopoverContainerVariant as Ie, PopoverContainerPosition as z } from "../../../../internal/Popover/types.js";
import { TypographyVariant as oe, TypographyElement as re } from "../../../../internal/Typography/types.js";
import { useTransactionsOverviewContext as Fe } from "../../context/TransactionsOverviewContext.js";
import { useState as y, useMemo as n, useRef as J, useCallback as x, useEffect as E } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { AlertTypeOption as K } from "../../../../internal/Alert/types.js";
import { ButtonVariant as W } from "../../../../internal/Button/types.js";
import { getTransactionsFilterQueryParams as Be } from "../utils.js";
import { Tag as _e } from "../../../../internal/Tag/Tag.js";
import { classes as r } from "./constants.js";
/* empty css                        */
import Le from "../../../../../core/Context/preact/useCoreContext.js";
import De from "../../../../../core/Context/analytics/preact/useAnalyticsContext.js";
import { downloadBlob as ke } from "../../../../../utils/file/download.js";
import { Fragment as Ye } from "../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/dist/preact.module.js";
import Me from "../../../../internal/Spinner/Spinner.js";
import { Icon as Ue } from "../../../../internal/Icon/Icon.js";
import { fixedForwardRef as qe } from "../../../../../utils/preact/fixedForwardRef.js";
import { EMPTY_ARRAY as g } from "../../../../../utils/value/constants.js";
import { useConfigContext as Ge } from "../../../../../core/ConfigContext/preact/context.js";
import F from "../../../../../utils/random/uniqueId.js";
import { isFunction as Ve } from "../../../../../utils/value/is.js";
const B = {
  category: Ne,
  subCategory: be
}, L = ({
  children: m,
  el: c = re.DIV,
  variant: u = oe.BODY,
  ...o
}) => /* @__PURE__ */ e(te, { ...o, el: c, variant: u, children: m }), Z = qe(
  ({ children: m, className: c, ...u }, o) => /* @__PURE__ */ e(ye, { ref: o, className: _([r.popoverColumn, c]), ...u, name: "columns", children: /* @__PURE__ */ e(L, { el: re.SPAN, children: m }) })
), ee = ({ children: m, ...c }) => /* @__PURE__ */ e(L, { ...c, className: r.popoverSectionTitle, stronger: !0, children: m }), Et = ({ disabled: m }) => {
  const { filters: c, lastFiltersChangeTimestamp: u } = Fe(), { i18n: o } = Le(), T = De(), S = Pe(Re.down.xs), [l, D] = y(!1), [ne, k] = y(), [b, Y] = y(!1), [p, M] = y([]), [se, ie] = n(() => {
    const {
      balanceAccount: t,
      paymentPspReference: i,
      createdDate: s,
      categories: d,
      currencies: f
      /*, statuses*/
    } = c, a = [
      ...t?.id ? ["transactions.overview.export.filters.types.account"] : g,
      ...s ? ["transactions.overview.export.filters.types.date"] : g,
      // ...(statuses.length ? (['transactions.overview.export.filters.types.status'] as const) : EMPTY_ARRAY),
      ...d.length ? ["transactions.overview.export.filters.types.category"] : g,
      ...f.length ? ["transactions.overview.export.filters.types.currency"] : g,
      ...i ? ["transactions.overview.export.filters.types.paymentPspReference"] : g
    ], v = {
      ...Be(c, u),
      sortDirection: "desc"
    };
    return [a, v];
  }, [c, u]), { downloadTransactions: ae } = Ge().endpoints, U = Ve(ae), ce = U && l && b && !!p.length, { error: q, isFetching: N } = Ae(
    "downloadTransactions",
    { query: { ...ie, columns: p } },
    ce,
    ke
  ), le = `elem-${we()}`, G = J(null), O = n(() => o.get("transactions.overview.export.button.label"), [o]), pe = n(() => o.get("transactions.overview.export.button.inProgress"), [o]), V = n(() => o.get("transactions.overview.export.actions.cancel"), [o]), H = n(() => o.get("transactions.overview.export.actions.download"), [o]), me = n(() => o.get("transactions.overview.export.filters.title"), [o]), de = n(() => o.get("transactions.overview.export.columns.title"), [o]), $ = n(F, []), P = n(
    () => h.map((t) => ({
      label: o.get(`transactions.overview.export.columns.types.${t}`),
      id: F(),
      value: t
    })),
    [o]
  ), ue = n(() => o.get("transactions.overview.export.columns.types.all", {
    values: { count: h.length }
  }), [o]), R = n(F, []), I = J(null), fe = n(() => P.map(({ id: t }) => t).join(" "), [P]), ve = p.length === h.length, j = x(
    (t) => {
      const i = t.currentTarget, s = i.value, d = i.checked, f = i.id === R;
      M((a) => {
        if (f)
          return d ? h : g;
        if (h.includes(s)) {
          const v = a.indexOf(s);
          if (d) {
            if (v < 0)
              return [...a, s];
          } else if (v >= 0)
            return [...a.slice(0, v), ...a.slice(v + 1)];
        }
        return a;
      });
    },
    [R]
  ), w = x(
    (t) => {
      t ? T.addEvent?.("Cancelled export", B) : T.addEvent?.("Clicked button", { ...B, label: "Export" });
    },
    [T]
  ), C = x(
    (t = !0) => {
      D(!1), t && w(!0);
    },
    [w]
  ), he = x(() => {
    D((t) => !t), w(l);
  }, [l, w]), A = x(() => k(void 0), []), xe = n(
    () => ({
      event: () => C(),
      variant: W.SECONDARY,
      title: V
    }),
    [V, C]
  ), ge = n(
    () => ({
      disabled: !p.length,
      event: () => Y(!0),
      variant: W.PRIMARY,
      title: H
    }),
    [H, p.length]
  );
  E(() => {
    k(q);
  }, [q]), E(() => {
    l ? A() : M(X);
  }, [l, A]), E(() => {
    if (b) {
      Y(!1), C(!1);
      let t = "Custom", i = !0, s = !0;
      h.forEach((d) => {
        const f = p.includes(d), a = X.includes(d);
        i &&= f ? a : !a, s &&= f;
      }), s ? t = "All" : i && (t = "Default"), T.addEvent?.("Completed export", {
        ...B,
        exportedFields: t
      });
    }
  }, [p, b, C, T]), E(() => {
    (function t() {
      I.current ? I.current.focus() : requestAnimationFrame(t);
    })();
  }, []);
  const Te = x(
    () => /* @__PURE__ */ e(
      Q,
      {
        onClose: A,
        className: r.errorAlert,
        type: K.CRITICAL,
        "data-testid": "transactions-export-error-alert",
        children: /* @__PURE__ */ e(te, { variant: oe.BODY, children: o.get("transactions.overview.export.actions.error") })
      }
    ),
    [o, A]
  );
  return U ? /* @__PURE__ */ e("div", { className: r.root, children: [
    /* @__PURE__ */ e(Ye, { children: [
      /* @__PURE__ */ e(
        Se,
        {
          "aria-haspopup": "dialog",
          "aria-expanded": l,
          "aria-label": O,
          ref: G,
          id: le,
          className: r.button,
          classNameModifiers: l ? ["active"] : void 0,
          disabled: m || N,
          onClick: he,
          tabIndex: 0,
          children: /* @__PURE__ */ e("div", { className: "adyen-pe-filter-button__default-container", children: /* @__PURE__ */ e(L, { className: "adyen-pe-filter-button__label", children: [
            N ? /* @__PURE__ */ e(Me, { size: "x-small" }) : /* @__PURE__ */ e(Ue, { name: "download" }),
            !S && /* @__PURE__ */ e("span", { children: N ? pe : O })
          ] }) })
        }
      ),
      ne && Te()
    ] }),
    l && /* @__PURE__ */ e(
      Ce,
      {
        disableFocusTrap: !1,
        dismissible: !1,
        dismiss: C,
        open: l,
        position: S ? z.BOTTOM : z.BOTTOM_RIGHT,
        variant: Ie.POPOVER,
        showOverlay: S,
        targetElement: G,
        title: O,
        children: /* @__PURE__ */ e("div", { className: r.popover, "data-testid": "transactions-export-popover", children: [
          /* @__PURE__ */ e("div", { className: r.popoverSections, children: [
            /* @__PURE__ */ e("div", { className: _(r.popoverSection, r.filtersSection), "data-testid": "transactions-export-filters", children: [
              /* @__PURE__ */ e(ee, { children: `${me}:` }),
              se.map((t) => /* @__PURE__ */ e(_e, { label: o.get(t) }, t))
            ] }),
            /* @__PURE__ */ e("div", { className: _(r.popoverSection, r.columnsSection), children: /* @__PURE__ */ e("div", { role: "group", "aria-labelledby": $, children: [
              /* @__PURE__ */ e(ee, { id: $, children: de }),
              /* @__PURE__ */ e("div", { className: r.popoverSectionContent, children: [
                /* @__PURE__ */ e(
                  Z,
                  {
                    ref: I,
                    className: r.popoverColumnAll,
                    "aria-controls": fe,
                    checked: ve,
                    onChange: j,
                    id: R,
                    children: ue
                  }
                ),
                P.map(({ id: t, label: i, value: s }) => /* @__PURE__ */ e(
                  Z,
                  {
                    checked: p.includes(s),
                    onChange: j,
                    value: s,
                    id: t,
                    children: i
                  },
                  s
                ))
              ] })
            ] }) })
          ] }),
          /* @__PURE__ */ e("div", { className: r.popoverActions, children: [
            /* @__PURE__ */ e(
              Q,
              {
                type: K.HIGHLIGHT,
                className: r.popoverActionsAlert,
                title: o.get("transactions.overview.export.actions.download.info")
              }
            ),
            /* @__PURE__ */ e(Ee, { actions: [ge, xe], layout: Oe.BUTTONS_END })
          ] })
        ] })
      }
    )
  ] }) : null;
};
export {
  Et as default
};
