import { useModuleSkeleton as Bt, useModuleDictionary as Nt } from "@m4l/core";
import Vt from "clsx";
import { useUtils as It, useLocaleText as Ft, useNow as Yt } from "@mui/x-date-pickers/internals";
import { useMemo as R, useState as F, useRef as me, useCallback as m, useEffect as ne, isValidElement as zt } from "react";
import { useComponentSize as Ht } from "../../../../hooks/useComponentSize/index.js";
import { useResolvedTimePickerDisplayVariant as Wt } from "../../../TimePicker/hooks/useResolvedTimePickerDisplayVariant/useResolvedTimePickerDisplayVariant.js";
import { DATE_RANGE_CALENDAR_PICKER_DEFAULT_CALENDARS as je, DATE_RANGE_CALENDAR_PICKER_DEFAULT_RANGE_POSITION as Kt, EMPTY_DATE_RANGE as ve, DATE_RANGE_CALENDAR_PICKER_CLASSES as Ut, DATE_RANGE_CALENDAR_PICKER_DATE_TIME_FORMAT as Xe, DATE_RANGE_CALENDAR_PICKER_FIXED_YEARS_PER_ROW as Gt } from "../../constants.js";
import { resolveDateRangeCalendarPickerDictionaryLabel as se, DICTIONARY as re, resolveDateRangeCalendarPickerMaxDaysLabel as $t, DATE_RANGE_CALENDAR_PICKER_FALLBACK_LABELS as oe } from "../../dictionary.js";
import { resolveInitialVisibleMonth as jt, resolveNavigationBounds as Xt, isDateDisabled as Zt, resolveSelectedRangeDate as tt, isDateVisibleInWindow as xe, resolveVisibleMonthForDate as Ze, findFirstEnabledVisibleDate as qe, getDateKey as Re, computeDateRangeDayCount as qt, normalizeSameMomentDateTimeRangeValue as Jt, selectRangeDate as Qt, formatHeaderLabel as Je, formatDateRangeTimeValue as Qe, createDateRangeValue as ea, mergeDateWithTimeValue as et, resolveRangeSelectionState as ta, findClosestEnabledDate as aa, isWithinSelectedRange as ie, isWithinPreviewRange as le } from "../../helpers.js";
function na(o, l, s) {
  const r = s.startOfWeek(o);
  return Array.from({ length: 7 }, (v, M) => {
    const T = s.addDays(r, M), C = s.format(T, "weekdayShort");
    return {
      ariaLabel: s.format(T, "weekday"),
      date: T,
      label: l?.(C, T) ?? C
    };
  });
}
function Be(o, l, s, r) {
  return aa({
    fallbackDirection: l,
    isDateDisabled: s,
    targetDate: o,
    utils: r
  });
}
function sa(o, l, s, r) {
  return tt(r, o) ?? l ?? s.date() ?? /* @__PURE__ */ new Date();
}
function ra(o) {
  return typeof o == "object" && o !== null && !Array.isArray(o) && !zt(o) && ("anchorOrigin" in o || "badgeContent" in o || "color" in o || "invisible" in o || "max" in o || "showZero" in o);
}
function oa(o, l, s) {
  const r = l?.(o, s) ?? null;
  if (r == null || r === !1)
    return null;
  if (ra(r)) {
    const {
      anchorOrigin: v = { horizontal: "right", vertical: "top" },
      badgeContent: M,
      color: T = "primary",
      invisible: C,
      max: b,
      showZero: x
    } = r;
    return {
      anchorOrigin: v,
      badgeContent: typeof M == "number" ? M : "",
      color: T,
      invisible: C,
      max: b,
      showZero: x,
      variant: typeof M == "number" ? "standard" : "dot"
    };
  }
  return {
    anchorOrigin: { horizontal: "right", vertical: "top" },
    badgeContent: r,
    color: "primary",
    variant: "standard"
  };
}
function ia({
  adjustedSize: o,
  currentRangePosition: l,
  currentValue: s,
  day: r,
  disableHighlightToday: v,
  firstEnabledVisibleDate: M,
  focusedDay: T,
  getDayBadgeContent: C,
  isDayDisabled: b,
  isSkeleton: x,
  month: d,
  nextDay: p,
  now: c,
  previousDay: B,
  previewDay: S,
  readOnly: K,
  utils: i
}) {
  const U = Re(r, i);
  if (x) {
    const t = {
      disabled: !0,
      isEndOfRange: !1,
      isOutsideCurrentMonth: !1,
      isPreviewing: !1,
      isSelected: !1,
      isStartOfRange: !1,
      isToday: !1,
      isWithinRange: !1
    }, X = {
      disabled: !0,
      isEndOfRange: !1,
      isOutsideCurrentMonth: !1,
      isPreviewing: !1,
      isRangeEnd: !1,
      isRangeStart: !1,
      isSkeleton: !0,
      isSelected: !1,
      isStartOfRange: !1,
      isToday: !1,
      isWithinRange: !1,
      readOnly: !0,
      size: o
    };
    return {
      ariaLabel: i.format(r, "fullDate"),
      badge: null,
      dayKey: U,
      label: i.formatByString(r, "dd"),
      metadata: t,
      ownerState: X,
      tabIndex: -1
    };
  }
  const G = !i.isSameMonth(r, d), w = !G, f = w && !!s.startDate && i.isSameDay(r, s.startDate), N = w && !!s.endDate && i.isSameDay(r, s.endDate), $ = w && ie(r, s, i), J = w && le(
    r,
    s,
    S,
    l,
    i
  ), j = $ || J, Y = w && B && i.isSameMonth(B, d) ? ie(B, s, i) || le(
    B,
    s,
    S,
    l,
    i
  ) : !1, Se = w && p && i.isSameMonth(p, d) ? ie(p, s, i) || le(
    p,
    s,
    S,
    l,
    i
  ) : !1, h = {
    disabled: b(r),
    isEndOfRange: N,
    isOutsideCurrentMonth: G,
    isPreviewing: J,
    isSelected: f || N,
    isStartOfRange: f,
    isToday: !v && i.isSameDay(r, c),
    isWithinRange: $
  }, de = {
    disabled: h.disabled,
    isEndOfRange: h.isEndOfRange,
    isOutsideCurrentMonth: h.isOutsideCurrentMonth,
    isPreviewing: h.isPreviewing,
    isRangeEnd: j && !Se,
    isRangeStart: j && !Y,
    isSkeleton: !1,
    isSelected: h.isSelected,
    isStartOfRange: h.isStartOfRange,
    isToday: h.isToday,
    isWithinRange: h.isWithinRange,
    readOnly: K,
    size: o
  };
  return {
    ariaCurrent: h.isToday ? "date" : void 0,
    ariaLabel: i.format(r, "fullDate"),
    badge: oa(r, C, h),
    dayKey: U,
    label: i.formatByString(r, "dd"),
    metadata: h,
    ownerState: de,
    tabIndex: T ? i.isSameDay(r, T) ? 0 : -1 : M && i.isSameDay(r, M) ? 0 : -1
  };
}
function la({
  currentRangePosition: o,
  currentValue: l,
  day: s,
  disableHighlightToday: r,
  firstEnabledVisibleDate: v,
  focusedDay: M,
  isDayDisabled: T,
  month: C,
  nextDay: b,
  now: x,
  previousDay: d,
  previewDay: p,
  utils: c
}) {
  const S = !!c.isSameMonth(s, C), K = S && !!l.startDate && c.isSameDay(s, l.startDate), i = S && !!l.endDate && c.isSameDay(s, l.endDate), U = S && ie(s, l, c), G = S && le(
    s,
    l,
    p,
    o,
    c
  ), w = S && d && c.isSameMonth(d, C) ? ie(d, l, c) || le(
    d,
    l,
    p,
    o,
    c
  ) : !1, f = S && b && c.isSameMonth(b, C) ? ie(b, l, c) || le(
    b,
    l,
    p,
    o,
    c
  ) : !1, N = !r && c.isSameDay(s, x), $ = c.isSameDay(s, M), J = v ? c.isSameDay(s, v) : !1;
  return [
    T(s) ? "1" : "0",
    K ? "1" : "0",
    i ? "1" : "0",
    U ? "1" : "0",
    G ? "1" : "0",
    w ? "1" : "0",
    f ? "1" : "0",
    N ? "1" : "0",
    $ ? "1" : "0",
    J ? "1" : "0"
  ].join(":");
}
function ya(o) {
  const {
    calendars: l = je,
    className: s,
    dayOfWeekFormatter: r,
    defaultCalendarMonth: v,
    defaultRangePosition: M = Kt,
    defaultValue: T,
    disableFuture: C,
    disableHighlightToday: b = !1,
    disablePast: x,
    disabled: d = !1,
    getDayBadgeContent: p,
    headerFormat: c,
    maxDate: B,
    maxDays: S,
    minDate: K,
    onChange: i,
    onMonthChange: U,
    onRangePositionChange: G,
    rangePosition: w,
    readOnly: f = !1,
    referenceDate: N,
    shouldDisableDate: $,
    size: J = "medium",
    slotProps: j,
    enableTimeRange: Y = !1,
    timeDisplayVariant: Se = "auto",
    value: h,
    variant: de = "default"
  } = o, t = It(), X = Ft(), z = Yt("default"), Z = Bt(), { getLabel: V } = Nt(), { currentSize: Ee } = Ht(J), Q = Ee === "small" || Ee === "medium" ? Ee : "medium", ee = Wt(Se), P = R(() => ({
    endSummaryEmpty: se(
      V,
      re.END_SUMMARY_EMPTY,
      oe.endSummaryEmpty
    ),
    endSummaryPrefix: se(
      V,
      re.END_SUMMARY_PREFIX,
      oe.endSummaryPrefix
    ),
    endTimeLabel: se(
      V,
      re.END_TIME_LABEL,
      oe.endTimeLabel
    ),
    startSummaryEmpty: se(
      V,
      re.START_SUMMARY_EMPTY,
      oe.startSummaryEmpty
    ),
    startSummaryPrefix: se(
      V,
      re.START_SUMMARY_PREFIX,
      oe.startSummaryPrefix
    ),
    startTimeLabel: se(
      V,
      re.START_TIME_LABEL,
      oe.startTimeLabel
    )
  }), [V]), A = de === "column" ? 1 : Math.max(1, l || je), ce = h !== void 0, ue = w !== void 0, [at, nt] = F(
    T ?? ve
  ), [st, Me] = F(null), [rt, ot] = F(M), [it, Ce] = F(null), n = ce ? st ?? h ?? ve : at, _ = ue ? it ?? w : rt, [u, Ne] = F(() => jt({
    currentRangePosition: _,
    defaultCalendarMonth: v,
    referenceDate: N,
    utils: t,
    value: n
  })), Ve = me(u), [E, q] = F(() => sa(
    _,
    N,
    t,
    n
  )), [fe, De] = F(null), [k, Pe] = F(null), [lt, Ae] = F(null), Ie = me({}), Te = m((e) => !1, []), Fe = me({
    adjustedSize: Q,
    currentRangePosition: _,
    currentValue: n,
    disableHighlightToday: b,
    firstEnabledVisibleDate: null,
    focusedDay: E,
    getDayBadgeContent: p,
    isDayDisabled: Te,
    isSkeleton: Z,
    now: z,
    previewDay: fe,
    readOnly: f,
    utils: t
  }), Ye = me({
    currentRangePosition: _,
    currentValue: n,
    disabled: d,
    isDayDisabled: Te,
    onChange: i,
    onRangePositionChange: G,
    readOnly: f,
    utils: t
  }), ze = me({
    currentRangePosition: _,
    currentValue: n,
    isDayDisabled: Te
  }), pe = R(() => ({
    calendars: A,
    disabled: d,
    isSkeleton: Z,
    readOnly: f,
    size: Q,
    enableTimeRange: Y,
    variant: de
  }), [Q, d, Z, f, A, Y, de]), H = R(() => Xt({
    disableFuture: C,
    disablePast: x,
    maxDate: B,
    minDate: K,
    now: z,
    utils: t
  }), [C, x, B, K, z, t]), I = R(() => Array.from(
    { length: A },
    (e, a) => t.addMonths(u, a)
  ), [A, t, u]), dt = R(() => na(
    N ?? u,
    r,
    t
  ), [r, N, t, u]), D = m((e) => Zt(e, H, $, t), [H, $, t]);
  ne(() => {
    if (!ce) {
      Me(null);
      return;
    }
    Me(h ?? ve);
  }, [ce, h]), ne(() => {
    if (!ue) {
      Ce(null);
      return;
    }
    Ce(w ?? M);
  }, [M, ue, w]), ne(() => {
    Ve.current = u;
  }, [u]), ne(() => {
    const e = tt(n, _);
    e && (q(e), xe(e, Ve.current, A, t) || Ne((a) => Ze(
      e,
      a,
      A,
      t
    )));
  }, [_, n, A, t]), ne(() => {
    if (!E || xe(E, u, A, t))
      return;
    const e = qe(I, D, t);
    e && q(e);
  }, [E, D, A, t, u, I]), ne(() => {
    const e = E ? Re(E, t) : null;
    e && Ie.current[e]?.focus();
  }, [E, t, u]);
  const ge = R(() => qe(I, D, t), [D, t, I]), ct = R(() => !S || !n.startDate || !n.endDate ? null : qt(n.startDate, n.endDate) > S ? $t(V, S) : null, [n.endDate, n.startDate, V, S]);
  Fe.current = {
    adjustedSize: Q,
    currentRangePosition: _,
    currentValue: n,
    disableHighlightToday: b,
    firstEnabledVisibleDate: ge,
    focusedDay: E,
    getDayBadgeContent: p,
    isDayDisabled: D,
    isSkeleton: Z,
    now: z,
    previewDay: fe,
    readOnly: f,
    utils: t
  }, Ye.current = {
    currentRangePosition: _,
    currentValue: n,
    disabled: d,
    isDayDisabled: D,
    onChange: i,
    onRangePositionChange: G,
    readOnly: f,
    utils: t
  }, ze.current = {
    currentRangePosition: _,
    currentValue: n,
    isDayDisabled: D
  };
  const ut = R(() => {
    if (!H.minBound)
      return !1;
    const e = t.endOfMonth(
      t.addMonths(u, A - 2)
    );
    return t.isBefore(e, H.minBound);
  }, [H.minBound, A, t, u]), mt = R(() => {
    if (!H.maxBound)
      return !1;
    const e = t.startOfMonth(
      t.addMonths(u, 1)
    );
    return t.isAfter(e, H.maxBound);
  }, [H.maxBound, t, u]), He = m((e) => Y ? Jt(e) : e, [Y]), be = m((e) => {
    const a = He(e);
    return ce ? (Me(a), a) : (nt(a), a);
  }, [ce, He]), We = m((e) => {
    if (!ue) {
      ot(e);
      return;
    }
    Ce(e);
  }, [ue]), te = m((e) => {
    Ne(e), U?.(e);
  }, [U]), ft = m((e) => {
    De(null), Pe(null), Ae(null);
    const a = Be(
      t.addMonths(E, e),
      e >= 0 ? "forward" : "backward",
      D,
      t
    ) ?? E;
    q(a), te(
      t.startOfMonth(t.addMonths(u, e))
    );
  }, [te, E, D, t, u]), Dt = m((e, a) => {
    d || (Pe(e), Ae(a));
  }, [d]), he = m(() => {
    Pe(null), Ae(null);
  }, []), gt = m((e) => {
    if (k === null)
      return;
    const a = t.startOfMonth(
      t.setYear(
        I[k],
        t.getYear(e)
      )
    ), y = t.startOfMonth(
      t.addMonths(a, k * -1)
    ), L = Be(
      t.setYear(E, t.getYear(e)),
      "forward",
      D,
      t
    ) ?? a;
    q(L), te(y), he();
  }, [te, E, he, D, k, t, I]), we = m((e) => {
    const {
      currentRangePosition: a,
      currentValue: y,
      disabled: L,
      isDayDisabled: g,
      onChange: O,
      onRangePositionChange: W,
      readOnly: Le,
      utils: Oe
    } = Ye.current;
    if (L || Le || g(e))
      return;
    const ae = Qt(
      y,
      a,
      e,
      Oe
    ), ke = be(ae.nextValue);
    We(ae.nextRangePosition), q(e), De(null), O?.(ke, ae.nextSelectionState), W?.(ae.nextRangePosition);
  }, [We, be]), bt = m((e, a, y, L) => {
    if (d)
      return;
    let g = null, O = "forward";
    switch (e.key) {
      case "ArrowLeft":
        g = t.addDays(a, -1), O = "backward";
        break;
      case "ArrowRight":
        g = t.addDays(a, 1), O = "forward";
        break;
      case "ArrowUp":
        g = t.addDays(a, -7), O = "backward";
        break;
      case "ArrowDown":
        g = t.addDays(a, 7), O = "forward";
        break;
      case "Home":
        g = y, O = "forward";
        break;
      case "End":
        g = L, O = "backward";
        break;
      case "PageUp":
        g = e.shiftKey ? t.addYears(a, -1) : t.addMonths(a, -1), O = "backward";
        break;
      case "PageDown":
        g = e.shiftKey ? t.addYears(a, 1) : t.addMonths(a, 1), O = "forward";
        break;
      case "Enter":
      case " ":
        e.preventDefault(), we(a);
        return;
      default:
        return;
    }
    if (e.preventDefault(), !g)
      return;
    const W = Be(
      g,
      O,
      D,
      t
    );
    W && (q(W), xe(W, u, A, t) || te(
      Ze(
        W,
        u,
        A,
        t
      )
    ));
  }, [te, d, we, D, A, t, u]), ht = m(() => {
    De(null);
  }, []), yt = m((e) => {
    q(e);
  }, []), Rt = m((e) => {
    const {
      currentRangePosition: a,
      currentValue: y,
      isDayDisabled: L
    } = ze.current;
    L(e) || a !== "end" || !y.startDate || y.endDate || De(e);
  }, []), St = m((e, a) => {
    Ie.current[e] = a;
  }, []), Et = R(() => I.map((e, a) => ({
    headerButtonAriaLabel: X.calendarViewSwitchingButtonAriaLabel(
      k === a ? "year" : "day"
    ),
    headerLabel: Je(e, c, t),
    index: a,
    isYearPopoverOpen: k === a,
    key: Re(e, t),
    month: e,
    monthAriaLabel: Je(e, c, t),
    weeks: t.getWeekArray(e)
  })), [c, X, k, t, I]), Mt = Vt(
    s,
    j?.root?.className,
    Ut.root
  ), ye = k === null ? null : I[k], Ke = R(() => Qe(
    n.startDate,
    ee
  ), [n.startDate, ee]), Ue = R(() => Qe(
    n.endDate,
    ee
  ), [n.endDate, ee]), Ge = R(() => n.startDate ? `${P.startSummaryPrefix}: ${t.formatByString(n.startDate, Xe)}` : `${P.startSummaryPrefix}: ${P.startSummaryEmpty}`, [n.startDate, P.startSummaryEmpty, P.startSummaryPrefix, t]), $e = R(() => n.endDate ? `${P.endSummaryPrefix}: ${t.formatByString(n.endDate, Xe)}` : `${P.endSummaryPrefix}: ${P.endSummaryEmpty}`, [n.endDate, P.endSummaryEmpty, P.endSummaryPrefix, t]), _e = m((e, a) => {
    const y = n[e];
    if (!y)
      return;
    const L = ea(
      e === "startDate" ? et(y, a) : n.startDate,
      e === "endDate" ? et(y, a) : n.endDate
    ), g = be(L);
    i?.(g, ta(g));
  }, [be, n, i]), Ct = R(() => Y ? {
    endSummary: $e,
    endTimeLabel: P.endTimeLabel,
    endTimeValue: Ue,
    handleEndTimeChange: (e) => {
      _e("endDate", e);
    },
    handleStartTimeChange: (e) => {
      _e("startDate", e);
    },
    isEndDisabled: d || f || !n.endDate,
    isStartDisabled: d || f || !n.startDate,
    startSummary: Ge,
    startTimeLabel: P.startTimeLabel,
    startTimeValue: Ke,
    timeDisplayVariant: ee
  } : null, [n.endDate, n.startDate, d, $e, Ue, _e, f, ee, Ge, Ke, Y, P.endTimeLabel, P.startTimeLabel]), Pt = ye === null ? null : {
    ...j?.yearCalendar,
    disableFuture: C,
    disableHighlightToday: b,
    disablePast: x,
    disabled: d,
    maxDate: B,
    minDate: K,
    onChange: gt,
    ownerState: pe,
    readOnly: f,
    referenceDate: ye,
    value: ye,
    yearsPerRow: Gt
  }, At = {
    ...j?.yearPopover,
    anchorEl: lt,
    anchorOrigin: {
      horizontal: "left",
      vertical: "bottom"
    },
    disableScrollLock: !0,
    onClose: he,
    open: k !== null,
    ownerState: pe,
    transformOrigin: {
      horizontal: "left",
      vertical: "top"
    }
  }, Tt = m((e, a, y, L) => {
    const {
      adjustedSize: g,
      currentRangePosition: O,
      currentValue: W,
      disableHighlightToday: Le,
      firstEnabledVisibleDate: Oe,
      focusedDay: ae,
      getDayBadgeContent: ke,
      isDayDisabled: _t,
      isSkeleton: Lt,
      now: Ot,
      previewDay: kt,
      readOnly: vt,
      utils: xt
    } = Fe.current;
    return ia({
      adjustedSize: g,
      currentRangePosition: O,
      currentValue: W,
      day: e,
      disableHighlightToday: Le,
      firstEnabledVisibleDate: Oe,
      focusedDay: ae,
      getDayBadgeContent: ke,
      isDayDisabled: _t,
      isSkeleton: Lt,
      month: a,
      nextDay: L,
      now: Ot,
      previousDay: y,
      previewDay: kt,
      readOnly: vt,
      utils: xt
    });
  }, []), pt = m((e, a, y, L) => la({
    currentRangePosition: _,
    currentValue: n,
    day: e,
    disableHighlightToday: b,
    firstEnabledVisibleDate: ge,
    focusedDay: E,
    isDayDisabled: D,
    month: a,
    nextDay: L,
    now: z,
    previousDay: y,
    previewDay: fe,
    utils: t
  }), [_, n, b, ge, E, D, z, fe, t]), wt = R(() => ({
    adjustedSize: Q,
    disableHighlightToday: b,
    getDayBadgeContent: p,
    isDayDisabled: D,
    isSkeleton: Z,
    readOnly: f,
    todayKey: Re(z, t)
  }), [Q, b, p, D, Z, z, f, t]);
  return {
    activeYearMonth: ye,
    currentRangePosition: _,
    currentValue: n,
    dayModelConfig: wt,
    firstEnabledVisibleDate: ge,
    maxDaysError: ct,
    getDayModel: Tt,
    getDayRenderToken: pt,
    handleCalendarMouseLeave: ht,
    handleCloseYearPopover: he,
    handleDayFocus: yt,
    handleDayKeyDown: bt,
    handleDayMouseEnter: Rt,
    handleOpenYearPopover: Dt,
    handleSelectDay: we,
    isNextDisabled: mt,
    isPreviousDisabled: ut,
    isSkeleton: Z,
    labels: {
      dateTableLabel: X.dateTableLabel,
      nextMonth: X.nextMonth,
      previousMonth: X.previousMonth
    },
    monthModels: Et,
    openYearPopoverIndex: k,
    ownerState: pe,
    rootClassName: Mt,
    rootSlotProps: j?.root,
    setDayRef: St,
    shiftVisibleMonths: ft,
    timeRange: Ct,
    weekdayHeaders: dt,
    yearCalendarProps: Pt,
    yearPopoverProps: At
  };
}
export {
  ya as useDateRangeCalendarPicker
};
