import dayjs from "dayjs";
import { useCallback, useEffect, useRef, useState } from "react";
//#region src/plus/pisellReservation/hooks/useReservationScheduleDebounced.ts
/**
* 顶栏日程与时间轴：`schedule` 立即反映用户操作；`debouncedSchedule` 在停手后（或 flush）再更新，
* 供接口与宿主调用，避免拖动时连续打 API。
*/
function defaultScheduleValue() {
	return {
		date: dayjs().startOf("day"),
		at: dayjs()
	};
}
/**
* @returns `schedule` 绑定日程带 UI；`debouncedSchedule` 绑定 sales / patch / 外部 onSearch。
* `queueCommittedSchedule`：防抖；`flushCommittedSchedule`：立即同步（如「跟随当前时间」）。
*/
function useReservationScheduleDebounced(options) {
	const { scheduleValueProp } = options;
	const [internalSchedule, setInternalSchedule] = useState(defaultScheduleValue);
	const schedule = scheduleValueProp !== null && scheduleValueProp !== void 0 ? scheduleValueProp : internalSchedule;
	const scheduleRef = useRef(schedule);
	scheduleRef.current = schedule;
	const [debouncedSchedule, setDebouncedSchedule] = useState(() => scheduleValueProp !== null && scheduleValueProp !== void 0 ? scheduleValueProp : defaultScheduleValue());
	const scheduleCommitTimerRef = useRef(null);
	const flushCommittedSchedule = useCallback((next) => {
		if (scheduleCommitTimerRef.current != null) {
			window.clearTimeout(scheduleCommitTimerRef.current);
			scheduleCommitTimerRef.current = null;
		}
		setDebouncedSchedule(next);
	}, []);
	const queueCommittedSchedule = useCallback((next) => {
		if (scheduleCommitTimerRef.current != null) window.clearTimeout(scheduleCommitTimerRef.current);
		scheduleCommitTimerRef.current = window.setTimeout(() => {
			scheduleCommitTimerRef.current = null;
			setDebouncedSchedule(next);
		}, 300);
	}, []);
	useEffect(() => () => {
		if (scheduleCommitTimerRef.current != null) window.clearTimeout(scheduleCommitTimerRef.current);
	}, []);
	/** 受控 `scheduleValue` 从父传入时，日期/时刻变化同样走防抖，避免依赖不稳定的对象引用 */
	useEffect(() => {
		if (scheduleValueProp === void 0) return;
		queueCommittedSchedule(scheduleRef.current);
	}, [
		schedule.at != null && dayjs(schedule.at).isValid() ? dayjs(schedule.at).valueOf() : null,
		dayjs(schedule.date).startOf("day").valueOf(),
		scheduleValueProp,
		queueCommittedSchedule
	]);
	return {
		internalSchedule,
		setInternalSchedule,
		schedule,
		debouncedSchedule,
		scheduleRef,
		flushCommittedSchedule,
		queueCommittedSchedule
	};
}
//#endregion
export { useReservationScheduleDebounced };
