import { useRef as Re, useState as x, useEffect as Q, useMemo as k, useLayoutEffect as Te, useCallback as ke } from "react";
import { TIME_PICKER_PERIOD_OPTIONS as Ce, TIME_PICKER_MINUTE_SECOND_OPTIONS as W, TIME_PICKER_HOUR_OPTIONS_12H as Me, TIME_PICKER_HOUR_OPTIONS_24H as Oe } from "../../constants.js";
import { normalizeTimeValue as U, parseTimeValue as D, createDefaultTimeValueParts as h, toDisplayParts as _e, getVisibleSegments as we, formatTimeValue as S, areTimeValuePartsEqual as xe, isAllowedTimeInputValue as Ae, fromDisplayParts as X, formatDisplayPartsValue as A, getTimeInputSectionRangeFromSelection as Y, getNextEditableTimePosition as K, replaceTimeInputSubstring as Z, resetTimeInputSegments as v, getSegmentsToResetFromSelection as ee, isProtectedTimeCharacterSelection as Ke, getAdjacentTimeInputSectionRange as He, getTimeInputBoundarySectionRange as be, stepTimeInputSection as Ne } from "../../helpers.js";
import { useResolvedTimePickerDisplayVariant as Le } from "../useResolvedTimePickerDisplayVariant/useResolvedTimePickerDisplayVariant.js";
import { preventInvalidMaskedPrintableKey as Ue } from "../../../../utils/maskedFieldSections.js";
function je(te) {
  const {
    value: $,
    defaultValue: ne,
    onChange: re,
    displayVariant: ae,
    granularity: r,
    disabled: l,
    inputElementRef: H,
    readOnly: c
  } = te, n = Le(ae), C = $ !== void 0, m = Re(null), [M, F] = x(() => U(ne ?? "", n, r)), d = C ? U($ ?? "", n, r) : M, [f, y] = x(d), [P, V] = x(() => D(d, r) ?? h()), [B, q] = x(null), b = !!B;
  Q(() => {
    if (C)
      return;
    const e = U(
      M,
      n,
      r
    );
    e !== M && F(e);
  }, [r, M, C, n]);
  const I = k(() => _e(P, n), [P, n]), oe = k(() => we(r, n), [r, n]), ie = k(() => S(h(), n, r), [r, n]), se = k(() => S(P, n, r), [P, r, n]), ue = k(() => ({
    hours: n === "ampm" ? Me : Oe,
    minutes: W,
    seconds: W,
    period: Ce
  }), [n]);
  Te(() => {
    if (!m.current || !H.current)
      return;
    const e = m.current;
    H.current.setSelectionRange(e.start, e.end), m.current = null;
  }, [f, H]);
  function O(e, t = e) {
    m.current = { end: t, start: e };
  }
  function R(e) {
    C || F(e), re?.(e);
  }
  const _ = ke(() => {
    const e = D(d, r) ?? h();
    y((t) => t === d ? t : d), V((t) => xe(t, e) ? t : e);
  }, [d, r]);
  Q(() => {
    _();
  }, [_]);
  function le() {
    return D(f, r) ?? D(d, r) ?? h();
  }
  function E(e) {
    if (l || c || !Ae(e))
      return;
    y(e);
    const t = D(e, r);
    t && V(t);
  }
  function z() {
    if (l || c)
      return;
    if (!f.trim()) {
      V(h()), y(""), R("");
      return;
    }
    const e = A(
      {
        hours: "00",
        minutes: "00",
        seconds: "00",
        period: "AM"
      },
      n,
      r
    );
    if (n === "ampm" && f === e) {
      const i = h(), s = S(i, n, r);
      y(s), V(i), R(s);
      return;
    }
    const t = D(f, r);
    if (!t) {
      _();
      return;
    }
    const o = S(t, n, r);
    y(o), V(t), R(o);
  }
  function ce() {
    return f === d;
  }
  function fe() {
    return S(P, n, r) === d;
  }
  function pe(e) {
    if (l || c)
      return;
    const t = le();
    V(t), y(S(t, n, r)), q(e);
  }
  function N() {
    q(null);
  }
  function w() {
    _(), N();
  }
  function j() {
    const e = S(P, n, r);
    y(e), R(e), N();
  }
  function me() {
    if (fe()) {
      w();
      return;
    }
    j();
  }
  function de(e, t) {
    if (l || c)
      return;
    const o = {
      ...I,
      [e]: t
    }, i = X(o, n), s = S(i, n, r);
    V(i), y(s), R(s);
  }
  function ge(e, t) {
    const o = {
      ...I,
      [e]: t
    };
    V(X(o, n));
  }
  function G(e) {
    const t = Y(
      e.selectionStart ?? 0,
      e.selectionEnd ?? e.selectionStart ?? 0,
      r,
      n
    );
    t && e.setSelectionRange(t.start, t.end);
  }
  function Se(e) {
    if (l || c || e.key !== "Backspace" && e.key !== "Delete")
      return !1;
    const t = e.target;
    if (!(t instanceof HTMLInputElement))
      return !1;
    const o = f || A(I, n, r);
    if (!o)
      return !1;
    const i = t.selectionStart ?? 0, s = t.selectionEnd ?? i, u = Ke(
      o,
      i,
      s,
      e.key
    ), a = ee(
      o,
      i,
      s,
      e.key,
      r,
      n
    );
    return !u && a.length === 0 ? !1 : (e.preventDefault(), a.length > 0 && (O(
      K(
        i,
        r,
        n
      ) ?? i
    ), E(
      v(
        o,
        a,
        r,
        n,
        I.period
      )
    )), !0);
  }
  function ye(e) {
    if (l || c)
      return !1;
    if (Ue(
      e,
      n === "ampm" ? /^[\d:\sapm]$/i : /^[\d:\s]$/
    ))
      return !0;
    const t = e.target;
    if (!(t instanceof HTMLInputElement))
      return !1;
    const o = /^\d$/.test(e.key), i = n === "ampm" && /^[ap]$/i.test(e.key), s = e.key === ":" || e.key === " " || n === "ampm" && /^m$/i.test(e.key);
    if (!o && !i && !s)
      return !1;
    const u = f || A(I, n, r), a = t.selectionStart ?? 0, p = t.selectionEnd ?? a;
    if (e.preventDefault(), s) {
      const g = K(
        p > a ? a : a + 1,
        r,
        n
      );
      return g !== null && t.setSelectionRange(g, g), !0;
    }
    if (i) {
      const g = Z(
        u,
        u.length - 2,
        u.length,
        e.key.toUpperCase() === "A" ? "AM" : "PM"
      );
      return E(g), g === u ? (t.setSelectionRange(g.length, g.length), m.current = null) : O(g.length), !0;
    }
    const he = p > a ? v(
      u,
      ee(
        u,
        a,
        p,
        "Delete",
        r,
        n
      ),
      r,
      n,
      I.period
    ) : u, T = K(
      (p > a, a),
      r,
      n,
      !1
    );
    if (T === null)
      return !0;
    const J = Z(
      he,
      T,
      T + 1,
      e.key
    ), L = K(
      T + 1,
      r,
      n
    ) ?? T + 1;
    return E(J), J === u ? (t.setSelectionRange(L, L), m.current = null) : O(L), !0;
  }
  function Ve(e) {
    if (l || c)
      return !1;
    const t = e.target;
    if (!(t instanceof HTMLInputElement))
      return !1;
    const o = t.selectionStart ?? 0, i = t.selectionEnd ?? o, s = Y(
      o,
      i,
      r,
      n
    );
    if (!s)
      return !1;
    if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
      e.preventDefault();
      const p = He(
        s,
        e.key === "ArrowRight" ? 1 : -1,
        r,
        n
      );
      return t.setSelectionRange(p.start, p.end), m.current = null, !0;
    }
    if (e.key === "Home" || e.key === "End") {
      e.preventDefault();
      const p = be(
        e.key === "Home" ? "start" : "end",
        r,
        n
      );
      return t.setSelectionRange(p.start, p.end), m.current = null, !0;
    }
    if (e.key !== "ArrowUp" && e.key !== "ArrowDown")
      return !1;
    const u = f || A(I, n, r), a = Ne(
      u,
      o,
      i,
      e.key === "ArrowUp" ? 1 : -1,
      r,
      n
    );
    return a ? (e.preventDefault(), E(a.nextValue), a.nextValue === u ? (t.setSelectionRange(
      a.sectionRange.start,
      a.sectionRange.end
    ), m.current = null) : O(
      a.sectionRange.start,
      a.sectionRange.end
    ), !0) : !1;
  }
  function Ie(e) {
    if (l || c)
      return;
    const t = e.target;
    t instanceof HTMLInputElement && G(t);
  }
  function De(e) {
    if (l || c)
      return;
    const t = e.target;
    t instanceof HTMLInputElement && G(t);
  }
  function Pe(e) {
    if (l || c)
      return;
    const t = e.clipboardData.getData("text"), o = D(t, r);
    if (!o) {
      e.preventDefault();
      return;
    }
    e.preventDefault(), E(S(o, n, r));
  }
  function Ee(e) {
    if (!(ye(e) || Se(e) || Ve(e))) {
      if (e.key === "Enter") {
        if (e.preventDefault(), b && ce()) {
          w();
          return;
        }
        z();
        return;
      }
      e.key === "Escape" && b && (e.preventDefault(), w());
    }
  }
  return {
    anchorEl: B,
    defaultPlaceholder: ie,
    displayParts: I,
    draftInputValue: f,
    draftSummary: se,
    open: b,
    resolvedDisplayVariant: n,
    segmentOptions: ue,
    visibleSegments: oe,
    commitDraftInputValue: z,
    commitDisplaySegmentChange: de,
    handleCancel: w,
    handleClose: N,
    handleConfirm: j,
    handlePopoverEnterShortcut: me,
    handleDisplaySegmentChange: ge,
    handleInputFocus: Ie,
    handleInputKeyDown: Ee,
    handleInputMouseUp: De,
    handleInputPaste: Pe,
    handleInputValueChange: E,
    handleOpen: pe
  };
}
export {
  je as useTimePicker
};
