import { useModuleDictionary as ct } from "@m4l/core";
import { useComponentSize as ft } from "../../../hooks/useComponentSize/index.js";
import { useUtils as dt, useNow as mt } from "@mui/x-date-pickers/internals";
import { useMemo as g, useRef as B, useState as T, useLayoutEffect as Pe, useEffect as pt } from "react";
import { resolveNavigationBounds as Dt, computeDateRangeDayCount as gt, isDateDisabled as Me } from "../../DateRangeCalendarPicker/helpers.js";
import { useResolvedTimePickerDisplayVariant as Rt } from "../../TimePicker/hooks/useResolvedTimePickerDisplayVariant/useResolvedTimePickerDisplayVariant.js";
import { DATE_TIME_RANGE_PICKER_DEFAULT_SHORTCUTS as Et, DATE_TIME_RANGE_PICKER_SELECTED_RANGE_LABEL as yt, DATE_TIME_RANGE_PICKER_DAYS_LABEL as St, DATE_TIME_RANGE_PICKER_DAY_LABEL as Tt, EMPTY_DATE_TIME_RANGE_PICKER_VALUE as At, DATE_TIME_RANGE_PICKER_MIN_DESKTOP_LAYOUT_WIDTH as k, DATE_TIME_RANGE_PICKER_DEFAULT_CALENDARS as ht } from "../constants.js";
import { resolveDateTimeRangePickerDictionaryLabel as W, DICTIONARY as ne } from "../dictionary.js";
import { getDateTimeRangeValueKey as x, cloneDateTimeRangeValue as V, formatDateTimeRangeValue as L, resolveDateTimeRangeShortcutId as Ct, formatDateTimeRangeSelectedDaysText as _t, parseDateTimeRangeInput as z, isAllowedDateTimeRangeFieldValue as It, getDateTimeRangeInputMask as U, getDateTimeRangeSectionRangeFromSelection as Ke, getDateTimeRangeNextEditablePosition as G, resolveDateTimeRangePeriodRange as kt, replaceDateTimeRangeInputSubstring as be, resetDateTimeRangeInputSections as ve, getDateTimeRangeSectionsFromSelection as Ne, getAdjacentDateTimeRangeSectionRange as Vt, getDateTimeRangeBoundarySectionRange as Lt, stepDateTimeRangeInputSection as wt } from "./helpers.js";
import { useResolvedCompactMode as Pt } from "./useResolvedCompactMode.js";
import { preventInvalidMaskedPrintableKey as Mt } from "../../../utils/maskedFieldSections.js";
function Ht(Fe, H, re) {
  const {
    calendars: Be = ht,
    compact: We,
    defaultValue: O = At,
    disabled: l = !1,
    error: oe = !1,
    maxDate: ae,
    maxDays: ie,
    minDate: se,
    onChange: xe,
    readOnly: d = !1,
    shouldDisableDate: ue,
    shortcuts: le,
    size: ze = "medium",
    timeDisplayVariant: Ue = "auto",
    value: p,
    variant: ce = "outlined"
  } = Fe, { getLabel: E } = ct(), { currentSize: Y } = ft(ze), fe = Y === "small" || Y === "medium" ? Y : "medium", w = dt(), de = mt("default"), $ = g(() => de ?? /* @__PURE__ */ new Date(), [de]), n = Rt(Ue), P = Pt(We), j = g(() => (le ?? Et).map((e) => {
    const t = "dictionaryKey" in e && typeof e.dictionaryKey == "string" ? e.dictionaryKey : void 0;
    return t ? {
      ...e,
      label: W(
        E,
        t,
        e.label
      )
    } : e;
  }), [E, le]), q = $, u = B(null), me = B(
    p ? x(p) : null
  ), M = B(null), K = B(null), [y, pe] = T(null), [A, De] = T(() => V(p ?? O)), [c, J] = T(() => V(p ?? O)), [R, Q] = T(() => L(p ?? O, n)), [X, b] = T(!1), [Ge, v] = T(!1), D = !!y, N = P || X, He = N ? 1 : Math.max(1, Be), Oe = g(() => ({
    compact: N,
    disabled: l,
    error: !!oe,
    open: D,
    popoverWidth: y?.clientWidth,
    size: fe,
    variant: ce
  }), [fe, y, l, oe, D, N, ce]), ge = g(() => Dt({
    maxDate: ae,
    minDate: se,
    now: $,
    utils: w
  }), [ae, se, $, w]), Z = g(() => Ct(
    j,
    c,
    q
  ), [c, q, j]), Ye = g(() => Z ? [Z] : [], [Z]), Re = g(() => ({
    dayLabel: W(
      E,
      ne.DAY_LABEL,
      Tt
    ),
    daysLabel: W(
      E,
      ne.DAYS_LABEL,
      St
    ),
    selectedRangeLabel: W(
      E,
      ne.SELECTED_RANGE_LABEL,
      yt
    )
  }), [E]), $e = g(() => _t(c, Re), [c, Re]), je = g(() => L(c, n), [c, n]);
  Pe(() => {
    if (!D || P || X) {
      M.current = null, K.current = null;
      return;
    }
    const e = y?.ownerDocument.defaultView ?? window, t = re.current, r = () => {
      const f = t?.getBoundingClientRect().width ?? 0, s = M.current;
      if (f > 0 && s !== null && s >= k && f < k) {
        b(!0);
        return;
      }
      f > 0 && (M.current = f);
      const o = e.innerWidth, i = K.current;
      K.current = o, i !== null && i >= k && o < k && b(!0);
    }, a = !t || typeof ResizeObserver > "u" ? null : new ResizeObserver(() => {
      r();
    });
    return r(), t && a?.observe(t), e.addEventListener("resize", r), () => {
      M.current = null, K.current = null, a?.disconnect(), e.removeEventListener("resize", r);
    };
  }, [
    y,
    P,
    X,
    D,
    re
  ]), pt(() => {
    if (p === void 0)
      return;
    const e = x(p);
    if (me.current === e)
      return;
    me.current = e;
    const t = V(p);
    De(t), D || (J(t), Q(L(t, n)));
  }, [D, n, p]), Pe(() => {
    u.current === null || !H.current || (H.current.setSelectionRange(
      u.current.start,
      u.current.end
    ), u.current = null);
  }, [R, H]);
  function F(e, t = e) {
    u.current = {
      end: t,
      start: e
    };
  }
  function Ee(e, t = e.selectionStart ?? 0, r = e.selectionEnd ?? t) {
    const a = Ke(
      t,
      r,
      n
    );
    a && (e.setSelectionRange(a.start, a.end), u.current = null);
  }
  function h(e) {
    return !(e.endDate && !e.startDate || e.startDate && Me(e.startDate, ge, ue, w) || e.endDate && Me(e.endDate, ge, ue, w) || e.startDate && e.endDate && e.endDate.getTime() < e.startDate.getTime());
  }
  function ye(e) {
    return !!(ie && e.startDate && e.endDate && gt(e.startDate, e.endDate) > ie);
  }
  function Se(e) {
    return h(e) && !ye(e);
  }
  function ee(e) {
    return !!(e.startDate && e.endDate);
  }
  function Te(e) {
    return x(e) === x(A);
  }
  function qe() {
    return ee(A) && Te(c);
  }
  function Je() {
    return R === L(A, n);
  }
  function S(e) {
    const t = V(e);
    J(t), Q(L(t, n));
  }
  function Ae(e) {
    const t = V(e);
    De(t), S(t), xe?.(t);
  }
  function he() {
    S(A);
  }
  function C(e) {
    if (l || d || !It(e))
      return;
    const t = e.trim() ? e : U(n);
    Q(t);
    const r = z(
      t,
      n
    );
    r && h(r) && J(r);
  }
  function Ce() {
    if (l || d)
      return;
    const e = z(R, n);
    if (!e || !Se(e)) {
      he();
      return;
    }
    Ae(e);
  }
  function Qe() {
    Ce();
  }
  function Xe(e) {
    if (l || d)
      return;
    const t = z(R, n), r = t && h(t) ? t : A;
    S(r), b(
      !P && (e.ownerDocument.defaultView ?? window).innerWidth < k
    ), v(!1), pe(e);
  }
  function _e() {
    b(!1), v(!1), pe(null);
  }
  function Ie() {
    he(), _e();
  }
  function _() {
    Ie();
  }
  function ke() {
    if (!Se(c)) {
      _();
      return;
    }
    Ae(c), _e();
  }
  function Ze() {
    if (Te(c)) {
      _();
      return;
    }
    ke();
  }
  function et(e) {
    if (l || d)
      return;
    const t = e.resolveValue(q);
    h(t) && (S(t), v(ee(t)));
  }
  function tt(e) {
    S(e), v(ee(e));
  }
  function nt(e) {
    if (l || d || e.key !== "Backspace" && e.key !== "Delete")
      return !1;
    const t = e.target;
    if (!(t instanceof HTMLInputElement))
      return !1;
    const r = R || U(n), a = t.selectionStart ?? 0, f = t.selectionEnd ?? a, s = Ne(
      a,
      f,
      e.key,
      n
    );
    if (s.length === 0)
      return !1;
    e.preventDefault();
    const o = G(
      a,
      n
    ) ?? a, i = ve(
      r,
      s,
      n
    );
    return C(i), i === r ? (t.setSelectionRange(o, o), u.current = null) : F(o), !0;
  }
  function rt(e) {
    if (l || d)
      return !1;
    if (Mt(
      e,
      n === "ampm" ? /^[\d/:\sapm-]$/i : /^[\d/:\s-]$/
    ))
      return !0;
    const t = e.target;
    if (!(t instanceof HTMLInputElement))
      return !1;
    const r = /^\d$/.test(e.key), a = n === "ampm" && /^[ap]$/i.test(e.key), f = e.key === "/" || e.key === ":" || e.key === " " || e.key === "-" || n === "ampm" && /^m$/i.test(e.key);
    if (!r && !a && !f)
      return !1;
    const s = R || U(n), o = t.selectionStart ?? 0, i = t.selectionEnd ?? o;
    if (e.preventDefault(), f) {
      const m = G(
        i > o ? o : o + 1,
        n
      );
      return m !== null && (t.setSelectionRange(m, m), u.current = null), !0;
    }
    if (a) {
      const m = kt(
        o,
        i,
        n
      );
      if (!m)
        return !0;
      const we = be(
        s,
        m.start,
        m.end,
        e.key.toUpperCase() === "A" ? "AM" : "PM"
      );
      return C(we), we === s ? (t.setSelectionRange(m.end, m.end), u.current = null) : F(m.end), !0;
    }
    const lt = i > o ? ve(
      s,
      Ne(
        o,
        i,
        "Delete",
        n
      ),
      n
    ) : s, I = G(
      (i > o, o),
      n,
      !1
    );
    if (I === null)
      return !0;
    const Le = be(
      lt,
      I,
      I + 1,
      e.key
    ), te = G(
      I + 1,
      n
    ) ?? I + 1;
    return C(Le), Le === s ? (t.setSelectionRange(te, te), u.current = null) : F(te), !0;
  }
  function ot(e) {
    if (l || d)
      return !1;
    const t = e.target;
    if (!(t instanceof HTMLInputElement))
      return !1;
    const r = t.selectionStart ?? 0, a = t.selectionEnd ?? r, f = Ke(
      r,
      a,
      n
    );
    if (!f)
      return !1;
    if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
      e.preventDefault();
      const i = Vt(
        f,
        e.key === "ArrowRight" ? 1 : -1,
        n
      );
      return t.setSelectionRange(i.start, i.end), u.current = null, !0;
    }
    if (e.key === "Home" || e.key === "End") {
      e.preventDefault();
      const i = Lt(
        e.key === "Home" ? "start" : "end",
        n
      );
      return t.setSelectionRange(i.start, i.end), u.current = null, !0;
    }
    if (e.key !== "ArrowUp" && e.key !== "ArrowDown")
      return !1;
    const s = R || U(n), o = wt(
      s,
      r,
      a,
      e.key === "ArrowUp" ? 1 : -1,
      n
    );
    return o ? (e.preventDefault(), C(o.nextValue), o.nextValue === s ? (t.setSelectionRange(
      o.sectionRange.start,
      o.sectionRange.end
    ), u.current = null) : F(
      o.sectionRange.start,
      o.sectionRange.end
    ), !0) : !1;
  }
  function at(e) {
    if (l || d)
      return;
    const t = e.target;
    t instanceof HTMLInputElement && Ee(t);
  }
  function it(e) {
    if (l || d)
      return;
    const t = e.target;
    t instanceof HTMLInputElement && Ee(t);
  }
  function st(e) {
    if (!(rt(e) || nt(e) || ot(e))) {
      if (e.key === "Enter") {
        if (e.preventDefault(), D && Je()) {
          _();
          return;
        }
        Ce();
        return;
      }
      e.key === "Escape" && D && (e.preventDefault(), _());
    }
  }
  function ut(e) {
    if (l || d)
      return;
    const t = e.clipboardData.getData("text"), r = z(t, n);
    if (!r || !h(r)) {
      e.preventDefault();
      return;
    }
    e.preventDefault(), S(r);
  }
  const Ve = ye(c);
  return {
    anchorEl: y,
    draftValue: c,
    effectiveCalendars: He,
    fieldValue: R,
    handleCancel: _,
    handleClose: Ie,
    handleConfirm: ke,
    handleFieldBlur: Qe,
    handleFieldInputChange: C,
    handleFieldKeyDown: st,
    handleFieldFocus: at,
    handleFieldMouseUp: it,
    handleInputPaste: ut,
    handleOpen: Xe,
    handlePickerChange: tt,
    handlePopoverEnterShortcut: Ze,
    handleShortcutSelect: et,
    isConfirmDisabled: Ve,
    isPopoverEnterShortcutArmed: !Ve && (Ge || qe()),
    open: D,
    ownerState: Oe,
    resolvedCompact: N,
    resolvedDisplayVariant: n,
    resolvedShortcuts: j,
    selectedShortcutIds: Ye,
    selectedDaysText: $e,
    summaryText: je
  };
}
export {
  Ht as useDateTimeRangePicker
};
