import useEngineContext from "../../../../hooks/useEngineContext.js";
import CompensatedPisellContainer from "../../../../pro/compensatedPisellContainer/index.js";
import withResponsive from "../../../../responsive/withResponsive.js";
import { subscribeBookingDateChange } from "../../../../plus/salesSdk/utils/bookingDate.js";
import { useSalesSdkBookingContext } from "../../../../plus/salesSdk/context/SalesSdkBookingContext.js";
import "../../../../plus/salesSdk/index.js";
import locales_default from "../../locales/index.js";
import dayjs from "dayjs";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
import { DatePicker as DatePicker$1, Iconfont, SelectTime } from "@pisell/materials";
import classNames from "classnames";
import { useMemoizedFn } from "ahooks";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";
import "./index.less";
//#region src/components/bigSale/components/TimeBar/index.tsx
const DISPLAY_DATE_FORMAT = "YYYY-MM-DD";
function resolveDate(rawDate) {
	if (rawDate && dayjs(rawDate).isValid()) return dayjs(rawDate);
	return dayjs();
}
/**
* BigSaleTimeBar 只同步 SalesSdk BookingContext，不依赖 ticketBooking 的 mini-redux。
*/
const BigSaleTimeBar = ({ dataSource, productLoadParams, locale = "en", orderId, variant = "desktop", mobileDrawerOpen = false, onMobileDrawerClose }) => {
	var _context$appHelper, _context$appHelper$ge, _context$appHelper$ge2, _dataSource$sales$tem, _dataSource$sales$sal;
	const context = useEngineContext();
	const bookingContext = useSalesSdkBookingContext();
	const intervalRef = useRef(null);
	const [currentDate, setCurrentDate] = useState(() => resolveDate(bookingContext.getDate()));
	const [collapsed, setCollapsed] = useState(true);
	const [scaleCompensation, setScaleCompensation] = useState(1);
	const [intervalSetTime, setIntervalSetTime] = useState(true);
	const [isDateChange, setIsDateChange] = useState(false);
	const [isTimeChange, setIsTimeChange] = useState(false);
	locales.init(locales_default, (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getApp) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.call(_context$appHelper)) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.locales) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge2 = _context$appHelper$ge.getLocale) === null || _context$appHelper$ge2 === void 0 ? void 0 : _context$appHelper$ge2.call(_context$appHelper$ge)) || locale);
	useEffect(() => {
		setCurrentDate(resolveDate(bookingContext.getDate()));
	}, [bookingContext, dataSource.sales.bookingTicket]);
	/** 订阅 OS BookingContext 日期变更，保持 TimeBar 与 store 同步。 */
	useEffect(() => {
		if (!dataSource.sales.bookingTicket) return;
		return subscribeBookingDateChange(dataSource.sales.bookingTicket, (rawDate) => {
			setCurrentDate(resolveDate(rawDate));
		});
	}, [dataSource.sales.bookingTicket]);
	/**
	* SDK ready 后启动「跟随当前时间」定时器（对齐 ticketBooking `_setIntervalTime(true)`，不 reload 商品）。
	*/
	useEffect(() => {
		if (!dataSource.sales.isReady || !dataSource.sales.bookingTicket) return;
		startNowInterval(false);
		return () => {
			stopInterval();
		};
	}, [dataSource.sales.isReady, dataSource.sales.bookingTicket]);
	useEffect(() => {
		const getBodyScale = () => {
			const transform = window.getComputedStyle(document.body).transform;
			if (!transform || transform === "none") return 1;
			const matrix = transform.match(/matrix\(([^)]+)\)/);
			if (!matrix) return 1;
			return matrix[1].split(",").map((value) => parseFloat(value.trim()))[0] || 1;
		};
		const updateScale = () => {
			setScaleCompensation(getBodyScale());
		};
		updateScale();
		const observer = new MutationObserver(updateScale);
		observer.observe(document.body, {
			attributes: true,
			attributeFilter: ["style", "class"]
		});
		window.addEventListener("resize", updateScale);
		return () => {
			observer.disconnect();
			window.removeEventListener("resize", updateScale);
		};
	}, []);
	useEffect(() => {
		return () => {
			if (intervalRef.current) clearInterval(intervalRef.current);
		};
	}, []);
	const reloadProducts = useMemoizedFn(() => {
		dataSource.products.load(productLoadParams).catch((error) => {
			console.error(error);
		});
	});
	const applyDate = useMemoizedFn((date, shouldReloadProducts = false) => {
		setCurrentDate(date);
		if (!dataSource.sales.bookingTicket) return;
		bookingContext.setDate(date);
		if (shouldReloadProducts) reloadProducts();
	});
	const stopInterval = useMemoizedFn(() => {
		if (intervalRef.current) {
			clearInterval(intervalRef.current);
			intervalRef.current = null;
		}
		setIntervalSetTime(false);
	});
	/**
	* 开启「跟随当前时间」模式。
	* - 定时 tick 只同步 BookingContext（对齐 ticketBooking `_setDataChange`，不 reload 商品）
	* - 用户点 Today/Now 时传 shouldReloadProducts=true
	*
	* @example
	* startNowInterval(false); // mount 时
	* startNowInterval(true);  // 用户点「现在」
	*/
	const startNowInterval = useMemoizedFn((shouldReloadProducts = false) => {
		if (intervalRef.current) clearInterval(intervalRef.current);
		setIsDateChange(false);
		setIsTimeChange(false);
		setIntervalSetTime(true);
		applyDate(dayjs(), shouldReloadProducts);
		intervalRef.current = setInterval(() => {
			applyDate(dayjs(), false);
		}, 1e3 * 60);
	});
	const handlePreviousDay = useMemoizedFn(() => {
		const newDate = currentDate.subtract(1, "day");
		stopInterval();
		setIsDateChange(true);
		applyDate(newDate, true);
	});
	const handleNextDay = useMemoizedFn(() => {
		const newDate = currentDate.add(1, "day");
		stopInterval();
		setIsDateChange(true);
		applyDate(newDate, true);
	});
	const handleDateChange = useMemoizedFn((date) => {
		if (!date) return;
		stopInterval();
		setIsDateChange(true);
		applyDate(date, true);
	});
	const handleTimeChange = useMemoizedFn((timeString) => {
		const [hours, minutes] = timeString.split(":").map(Number);
		const newDate = currentDate.hour(hours).minute(minutes).second(0);
		setIsTimeChange(true);
		applyDate(newDate, true);
		if (timeString === dayjs().format("HH:mm")) startNowInterval(true);
		else stopInterval();
	});
	const handleCreateClick = useMemoizedFn(() => {
		dataSource.sales.createNew().then(() => {
			startNowInterval(false);
		}).catch((error) => {
			console.error(error);
		});
	});
	const hasExistingOrder = Boolean(orderId || ((_dataSource$sales$tem = dataSource.sales.tempOrder) === null || _dataSource$sales$tem === void 0 ? void 0 : _dataSource$sales$tem.order_id) || ((_dataSource$sales$sal = dataSource.sales.salesDetail) === null || _dataSource$sales$sal === void 0 || (_dataSource$sales$sal = _dataSource$sales$sal.header) === null || _dataSource$sales$sal === void 0 ? void 0 : _dataSource$sales$sal.order_id));
	const dateFormat = locale === "en" ? "dddd, DD MMM YYYY" : "YYYY年MM月DD日";
	const collapsedHeight = 40 / scaleCompensation;
	return useMemo(() => {
		const collapsedText = currentDate.isSame(dayjs(), "day") ? locales.getText("pisell2.big-sale.today") : currentDate.format(DISPLAY_DATE_FORMAT);
		if (variant === "phone") return /* @__PURE__ */ React.createElement(CompensatedPisellContainer, {
			renderType: "drawer",
			showHandlerBar: true,
			onHandlerBarClick: onMobileDrawerClose,
			props: {
				open: mobileDrawerOpen,
				onClose: onMobileDrawerClose,
				placement: "bottom",
				header: false,
				footer: false,
				closable: false,
				destroyOnClose: false,
				className: "pisell-big-sale-time-bar-drawer-phone",
				contentWrapperStyle: {
					maxWidth: "none",
					height: "auto"
				},
				styles: { body: { padding: 0 } }
			}
		}, /* @__PURE__ */ React.createElement("div", {
			className: "pisell-big-sale-time-bar-phone",
			style: { backgroundColor: isDateChange ? "#F79009" : void 0 }
		}, /* @__PURE__ */ React.createElement("div", { className: "pisell-big-sale-time-bar-phone__nav" }, /* @__PURE__ */ React.createElement(Button, {
			icon: /* @__PURE__ */ React.createElement(LeftOutlined, null),
			onClick: handlePreviousDay,
			size: "large"
		}), /* @__PURE__ */ React.createElement("div", { className: classNames("pisell-big-sale-time-bar-phone__field", { "pisell-big-sale-time-bar__picker--selected": isDateChange }) }, /* @__PURE__ */ React.createElement(DatePicker$1, {
			inputReadOnly: true,
			value: currentDate,
			format: locale === "en" ? "DD MMM YYYY" : "YYYY年MM月DD日",
			onChange: handleDateChange,
			size: "large",
			style: { width: "100%" }
		})), /* @__PURE__ */ React.createElement(Button, {
			icon: /* @__PURE__ */ React.createElement(RightOutlined, null),
			onClick: handleNextDay,
			size: "large"
		})), /* @__PURE__ */ React.createElement(Button, {
			block: true,
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, locales.getText("pisell2.big-sale.today")), /* @__PURE__ */ React.createElement("div", { className: classNames("pisell-big-sale-time-bar-phone__field", { "pisell-big-sale-time-bar__picker--selected": isTimeChange }) }, /* @__PURE__ */ React.createElement(SelectTime, {
			value: currentDate.format("HH:mm"),
			onChange: handleTimeChange,
			popoverProps: { style: { zoom: .8 } },
			timePickerProps: {},
			timeProps: {},
			slice: 5
		})), !hasExistingOrder && /* @__PURE__ */ React.createElement(Button, {
			block: true,
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, locales.getText("pisell2.big-sale.now")), hasExistingOrder && /* @__PURE__ */ React.createElement(Button, {
			block: true,
			onClick: () => {
				handleCreateClick();
				onMobileDrawerClose === null || onMobileDrawerClose === void 0 || onMobileDrawerClose();
			},
			size: "large",
			type: "primary"
		}, locales.getText("pisell2.big-sale.create-new"))));
		if (collapsed) return /* @__PURE__ */ React.createElement("div", {
			className: classNames("pisell-big-sale-time-bar", "pisell-big-sale-time-bar--collapsed", `pisell-big-sale-time-bar--${variant}`),
			style: {
				height: collapsedHeight,
				minHeight: collapsedHeight,
				maxHeight: collapsedHeight
			}
		}, /* @__PURE__ */ React.createElement("div", {
			className: "pisell-big-sale-time-bar__collapsed-content",
			style: { height: collapsedHeight }
		}, /* @__PURE__ */ React.createElement("span", {
			className: "pisell-big-sale-time-bar__collapsed-date",
			style: { lineHeight: `${collapsedHeight}px` }
		}, collapsedText), /* @__PURE__ */ React.createElement(Button, {
			type: "link",
			size: "small",
			className: "pisell-big-sale-time-bar__collapsed-expand",
			onClick: () => setCollapsed(false),
			style: { lineHeight: `${collapsedHeight}px` }
		}, /* @__PURE__ */ React.createElement("span", null, locales.getText("pisell2.big-sale.expand")), /* @__PURE__ */ React.createElement(Iconfont, { type: "pisell2-chevron-right-double" }))));
		return /* @__PURE__ */ React.createElement("div", {
			className: classNames("pisell-big-sale-time-bar", `pisell-big-sale-time-bar--${variant}`),
			style: { backgroundColor: isDateChange ? "#F79009" : void 0 }
		}, /* @__PURE__ */ React.createElement("div", { className: "pisell-big-sale-time-bar__scroll" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-big-sale-time-bar__scroll-content" }, /* @__PURE__ */ React.createElement(Button, {
			icon: /* @__PURE__ */ React.createElement(LeftOutlined, null),
			onClick: handlePreviousDay,
			size: "large"
		}), /* @__PURE__ */ React.createElement(Button, {
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, locales.getText("pisell2.big-sale.today")), /* @__PURE__ */ React.createElement("div", { className: classNames("pisell-big-sale-time-bar__date-picker", { "pisell-big-sale-time-bar__picker--selected": isDateChange }) }, /* @__PURE__ */ React.createElement(DatePicker$1, {
			inputReadOnly: true,
			value: currentDate,
			format: dateFormat,
			onChange: handleDateChange,
			size: "large",
			style: { width: "100%" }
		})), /* @__PURE__ */ React.createElement(Button, {
			icon: /* @__PURE__ */ React.createElement(RightOutlined, null),
			onClick: handleNextDay,
			size: "large"
		}), /* @__PURE__ */ React.createElement("div", { className: classNames("pisell-big-sale-time-bar__time-picker", { "pisell-big-sale-time-bar__picker--selected": isTimeChange }) }, /* @__PURE__ */ React.createElement(SelectTime, {
			value: currentDate.format("HH:mm"),
			onChange: handleTimeChange,
			popoverProps: { style: { zoom: .8 } },
			timePickerProps: {},
			timeProps: {},
			slice: 5
		})), !hasExistingOrder && /* @__PURE__ */ React.createElement(Button, {
			onClick: () => startNowInterval(true),
			size: "large",
			style: intervalSetTime ? {
				background: "#000",
				color: "#fff"
			} : void 0
		}, locales.getText("pisell2.big-sale.now")), hasExistingOrder && /* @__PURE__ */ React.createElement(Button, {
			onClick: handleCreateClick,
			size: "large",
			type: "primary"
		}, locales.getText("pisell2.big-sale.create-new")))), /* @__PURE__ */ React.createElement(Button, {
			type: "link",
			className: "pisell-big-sale-time-bar__collapse",
			onClick: () => setCollapsed(true)
		}, /* @__PURE__ */ React.createElement("span", null, locales.getText("pisell2.big-sale.collapse")), /* @__PURE__ */ React.createElement(Iconfont, { type: "pisell2-chevron-left-double" })));
	}, [
		collapsed,
		collapsedHeight,
		currentDate,
		dateFormat,
		handleCreateClick,
		handleDateChange,
		handleNextDay,
		handlePreviousDay,
		handleTimeChange,
		hasExistingOrder,
		intervalSetTime,
		isDateChange,
		isTimeChange,
		locale,
		mobileDrawerOpen,
		onMobileDrawerClose,
		startNowInterval,
		variant
	]);
};
BigSaleTimeBar.displayName = "BigSaleTimeBar";
var TimeBar_default = withResponsive(BigSaleTimeBar);
//#endregion
export { TimeBar_default as default };
