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