import P from "../../../../hooks/useMutation/useMutation.js";
import { useRef as N, useEffect as O, useCallback as T } from "../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { MenuItem as U } from "../components/PaymentLinkSettingsContainer/context/constants.js";
import { getThemePayload as R } from "../components/PaymentLinkSettingsContainer/utils/getThemePayload.js";
import { isThemePayload as A } from "../components/PaymentLinkThemeContainer/types.js";
import { useConfigContext as W } from "../../../../core/ConfigContext/preact/context.js";
import { isFunction as d, isUndefined as q } from "../../../../utils/value/is.js";
const J = (o, u, f, t, r, m, i, l, c, s, p) => {
  const { updatePayByLinkTheme: F, savePayByLinkSettings: k } = W().endpoints, h = N(null);
  O(() => () => {
    h.current && clearTimeout(h.current);
  }, []);
  const x = T(() => {
    p && d(p) ? h.current = setTimeout(() => {
      p();
    }, 500) : o(!1);
  }, [p, o]), y = P({
    queryFn: F,
    options: {
      onSuccess: (n) => {
        const e = { brandName: n?.brandName, logo: n?.logoUrl, fullWidthLogo: n?.fullWidthLogoUrl };
        c(e), s(R(e)), u(!1), f(!0), o(!1);
      },
      onError: () => {
        u(!0), f(!1), o(!1);
      }
    }
  }), C = T(() => {
    !t || q(r) || !i() || A(r) && (o(!0), y.mutate({ contentType: "multipart/form-data", body: r }, { path: { storeId: t } }));
  }, [y, t, r, i, o]), L = P({
    queryFn: k,
    options: {
      onSuccess: (n) => {
        const e = !n || !n?.termsOfServiceUrl ? { termsOfServiceUrl: "" } : n;
        c(e), s(e), u(!1), f(!0), x();
      },
      onError: () => {
        u(!0), f(!1), o(!1);
      }
    }
  }), b = T(() => {
    !t || q(r) || !i() || A(r) || (o(!0), L.mutate(
      {
        contentType: "application/json",
        body: r
      },
      { path: { storeId: t } }
    ));
  }, [L, t, r, i, o]);
  return { onSave: T(() => {
    if (m) {
      if (l(!0), m === U.theme) return C();
      if (m === U.termsAndConditions) return b();
    }
  }, [m, b, C, l]) };
};
export {
  J as useSaveAction
};
