import { useEnvironment as De, useNetwork as Re, getPropertyByString as _e } from "@m4l/core";
import { useRef as E, useState as C, useId as be, useMemo as k, useEffect as re, useCallback as n } from "react";
import { DEFAULT_TIMEOUT as ye, DEFAULT_RESULT_FIELD as Fe, DEFAULT_PLACEHOLDER_IMAGE_SRC as ve, DEFAULT_PLACEHOLDER_ALT as xe, DEFAULT_MAX_COLUMNS as Ue, DEFAULT_MAX_ROWS as ke, DEFAULT_PRESENTATION_TYPE as Pe, OVERLAY_ICON as Me } from "../constants.js";
function $e(P) {
  return {
    target: {
      value: P
    }
  };
}
function Ke(P) {
  const {
    value: d,
    onChange: V,
    endpoint: w,
    refetchOnOpen: B = !1,
    getOptionLabel: se,
    getOptionImage: oe,
    isOptionEqualToValue: T,
    presentationType: u = Pe,
    imageSize: h,
    maxColumns: i = Ue,
    maxRows: g = ke,
    size: O = "medium",
    disabled: s = !1,
    error: I = !1,
    timeout: L = ye,
    parms: S,
    resultField: D = Fe,
    isExternalUrl: R = !1,
    isRemote: _ = !0,
    responseToCamelCase: b,
    forwardedRef: A,
    blurHandler: z
  } = P, { host_static_assets: G, environment_assets: X } = De(), { networkOperation: Y } = Re(), J = E(null), W = E(null), M = E(null), $ = E([]), p = E(null), y = E(!1), [le, F] = C(!1), [r, j] = C(!1), [o, v] = C([]), [Q, Z] = C(!1), [N, ce] = C(null), q = be(), H = k(() => JSON.stringify({
    endpoint: w,
    isExternalUrl: R,
    isRemote: _,
    parms: S ?? null,
    responseToCamelCase: b ?? null,
    resultField: D,
    timeout: L
  }), [
    w,
    R,
    _,
    S,
    b,
    D,
    L
  ]), ee = u === "grid" || r;
  if (!w)
    throw new Error("ImageSelector requires the endpoint prop.");
  re(() => {
    if (!ee)
      return;
    if (!B && W.current === H && M.current !== null) {
      F(!1), v(M.current);
      return;
    }
    let e = !1;
    J.current?.abort();
    const t = new AbortController();
    return J.current = t, F(!0), v([]), Y({
      method: "GET",
      endPoint: w,
      timeout: L,
      isExternalUrl: R,
      parms: S,
      responseToCamelCase: b,
      isRemote: _,
      signal: t.signal
    }).then((l) => {
      if (e)
        return;
      const c = _e(l, D), ne = Array.isArray(c) ? c : [];
      W.current = H, M.current = ne, v(ne), F(!1);
    }).catch(() => {
      e || (v([]), F(!1));
    }), () => {
      e = !0, t.abort();
    };
  }, [
    w,
    R,
    _,
    Y,
    S,
    B,
    H,
    b,
    D,
    ee,
    L
  ]);
  const f = d != null, ue = f ? oe(d) : `${G}/${X}/${ve}`, ae = f ? se(d) : xe, ie = `${G}/${X}/${Me}`, te = i > 0 && g > 0 && o.length > i * g, fe = k(() => ({
    disabled: s,
    error: I,
    hasValue: f,
    imageSize: h,
    isFocused: Q,
    isOpen: r,
    maxColumns: i,
    maxRows: g,
    presentationType: u,
    size: O
  }), [
    s,
    I,
    f,
    h,
    Q,
    i,
    g,
    r,
    u,
    O
  ]), de = k(() => ({
    disabled: s,
    error: I,
    hasVerticalScroll: te,
    imageSize: h,
    maxColumns: i,
    maxRows: g,
    presentationType: u,
    size: O
  }), [s, I, te, h, i, g, u, O]), pe = k(() => ({
    disabled: s,
    imageSize: h,
    isOpen: r,
    isPlaceholder: !f,
    presentationType: u,
    size: O
  }), [s, f, h, r, u, O]), x = n((e = !1) => {
    if (f) {
      const t = o.findIndex((l) => T(l, d));
      if (t >= 0)
        return t;
    }
    return e && o.length > 0 ? o.length - 1 : 0;
  }, [f, T, o, d]), U = n((e) => {
    if (o.length === 0)
      return;
    const t = Math.max(0, Math.min(e, o.length - 1));
    $.current[t]?.focus();
  }, [o.length]), he = n((e) => {
    if (ce(e), typeof A == "function") {
      A(e);
      return;
    }
    A && (A.current = e);
  }, [A]), m = n((e) => {
    s || (typeof e < "u" && (p.current = e), j(!0));
  }, [s]), K = n((e = !1) => {
    const t = e ? "selected-or-last" : "selected-or-first";
    p.current = t, r && o.length > 0 && (U(x(e)), p.current = null);
  }, [U, x, r, o.length]), a = n((e = !1) => {
    p.current = null, y.current = e, j(!1);
  }, []), ge = n(() => {
    if (r) {
      a();
      return;
    }
    m("selected-or-first");
  }, [a, m, r]), Oe = n(() => {
    Z(!0);
  }, []), me = n((e) => {
    Z(!1), z?.(e);
  }, [z]), Ee = n((e, t) => {
    $.current[e] = t;
    const l = p.current, c = typeof l == "number" ? l : l === null ? null : x(l === "selected-or-last");
    t && c === e && (p.current = null, t.focus());
  }, [x]), we = n((e) => {
    p.current = null;
  }, []), Ae = n((e) => `${q}-option-${e}`, [q]), Ce = n((e, t) => {
    if (s || o.length === 0)
      return;
    const l = typeof i == "number" && i > 0 ? i : null;
    let c = null;
    switch (t.key) {
      case "ArrowRight":
        c = e + 1;
        break;
      case "ArrowLeft":
        c = e - 1;
        break;
      case "ArrowDown":
        if (!l)
          return;
        c = e + l;
        break;
      case "ArrowUp":
        if (!l)
          return;
        c = e - l;
        break;
      case "Home":
        c = 0;
        break;
      case "End":
        c = o.length - 1;
        break;
      case "Escape":
        u === "standard" && (t.preventDefault(), a(!0));
        return;
      default:
        return;
    }
    c !== null && (t.preventDefault(), U(c));
  }, [s, U, a, i, o.length, u]), Te = n((e) => {
    if (!s)
      switch (e.key) {
        case "Enter":
        case " ": {
          if (e.preventDefault(), r) {
            a();
            return;
          }
          m("selected-or-first");
          return;
        }
        case "ArrowDown":
          if (e.preventDefault(), r) {
            K();
            return;
          }
          m("selected-or-first");
          return;
        case "ArrowUp":
          if (e.preventDefault(), r) {
            K(!0);
            return;
          }
          m("selected-or-last");
          return;
        case "Escape":
          e.preventDefault(), a();
          return;
        default:
          return;
      }
  }, [s, K, a, m, r]), Ie = n((e) => f ? T(e, d) : !1, [f, T, d]), Le = n((e) => {
    s || (V?.($e(e), e), u === "standard" && a(!0));
  }, [s, a, V, u]), Se = n(() => {
    a();
  }, [a]);
  return re(() => {
    r || ($.current = [], y.current && queueMicrotask(() => {
      y.current && (y.current = !1, N?.focus());
    }));
  }, [r, N]), {
    getOptionId: Ae,
    handleBlur: me,
    handleFocus: Oe,
    handleKeyDown: Te,
    handleOptionFocus: we,
    handleOptionKeyDown: Ce,
    handleOptionRef: Ee,
    handlePopoverClose: Se,
    handleSelect: Le,
    handleToggle: ge,
    handleTriggerRef: he,
    gridOwnerState: de,
    isOptionSelected: Ie,
    loading: le,
    open: r,
    options: o,
    optionsListId: q,
    overlayIconSrc: ie,
    previewLabel: ae,
    previewOwnerState: pe,
    previewSource: ue,
    rootOwnerState: fe,
    triggerElement: N
  };
}
export {
  Ke as useImageSelector
};
