import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import editBookingModal_default from "../../../../components/booking/editBookingModal/index.js";
import { displayRoomTitleFromRow } from "../../floorRoomCard/floorRoomCardUtils.js";
import { appendBookingCountSuffix } from "../../floorRoomCard/views/RoomCardTooltipTimeLayout.js";
import { buildReservationTicketBookingCreateModeConfigForRow } from "../../utils/reservationTicketBookingHostParams.js";
import { BD_MODAL_MASK, DETAIL_TAB_ITEMS, I18N_BD, PREFIX, stopUiClick, t } from "./bookingDetailModalConstants.js";
import { BookingDetailUnit } from "./BookingDetailUnit.js";
import { useResourceBookingItem } from "./bookingDetailResourceBookingItem.js";
import { useBookingDetailActions } from "./useBookingDetailActions.js";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { locales } from "@pisell/utils";
import { PisellModal } from "@pisell/materials";
import "./ReservationBookingDetailModal.less";
//#region src/plus/pisellReservation/components/bookingDetailModal/ReservationBookingDetailModal.tsx
/**
* 平面图只读点击：预约详情弹窗。
* 内容由宿主 sales.getResourceBookingItem 返回的三段子列表驱动；
* 每条 booking 渲染为「RoomCard + 操作栏 + 商品」一个完整单元。
*/
function ReservationBookingDetailModal(props) {
	var _engineContext$appHel;
	const { open, onClose, onActionSuccess, raw, tableRow, sceneElementName, reservationBiz, associatedMenuListIds, reservationRuleProduct, floorDayBookingList, currentTime, followWallClock } = props;
	const [activeTab, setActiveTab] = useState("current-occupied");
	const engineContext = useEngineContext();
	const appHelperUtils = engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils;
	const { resourceBookingItem, resourceBookingItemLoading, activeTabBookings } = useResourceBookingItem(activeTab, {
		open,
		raw,
		tableRow,
		floorDayBookingList,
		currentTime,
		followWallClock,
		pisellos: appHelperUtils === null || appHelperUtils === void 0 ? void 0 : appHelperUtils.pisellos
	});
	/**
	* 各 Tab 当前数量：与 `useResourceBookingItem.activeTabBookings` 同源选段，
	* 用于在 Tab 名后追加 `(N)`。`resourceBookingItem == null`（首次加载未回）
	* 时不计算计数，避免在 Tab 标签上闪过 `(0)`。
	*/
	const tabCounts = useMemo(() => {
		if (resourceBookingItem == null) return null;
		return {
			"current-occupied": resourceBookingItem.bookings.length,
			ended: resourceBookingItem.completedBookings.length,
			unpaid: resourceBookingItem.unpaidBookings.length
		};
	}, [resourceBookingItem]);
	const { editBookingModalRef, isCancellingOrder, isCompletingBooking, handleResourceChangeConfirmed, handleActionCellClick } = useBookingDetailActions({
		raw,
		tableRow,
		reservationBiz,
		associatedMenuListIds,
		onActionSuccess,
		appHelperUtils
	});
	useEffect(() => {
		setActiveTab("current-occupied");
	}, [
		raw === null || raw === void 0 ? void 0 : raw.id,
		raw === null || raw === void 0 ? void 0 : raw.booking_uid,
		raw === null || raw === void 0 ? void 0 : raw.booking_id
	]);
	const detailModalTitle = useMemo(() => {
		var _tableRow$code;
		if (tableRow == null) return locales.getText(`${I18N_BD}.modal-title`);
		const roomTitle = displayRoomTitleFromRow(tableRow, sceneElementName != null && String(sceneElementName).trim() !== "" ? String(sceneElementName).trim() : void 0).trim();
		const code = (_tableRow$code = tableRow.code) === null || _tableRow$code === void 0 ? void 0 : _tableRow$code.trim();
		/**
		* 标题尾部按 `(N/M)` 拼当前资源订单计数，与平面图大卡 header / 小卡 tooltip
		* 同源；helper 接口为通用 `BookingCountSource`，`PisellReservationTableRow`
		* 的 `bookingCount` / `completeBookingCount` 字段结构化命中即可。
		* `bookingCount` 缺失或为 0 时不渲染计数，标题与之前完全一致。
		*/
		return appendBookingCountSuffix(roomTitle || code || locales.getText("pisell-reservation.room-kind-bound"), tableRow);
	}, [tableRow, sceneElementName]);
	const canShow = Boolean(open && raw != null);
	const handleHeaderCloseClick = useCallback((e) => {
		stopUiClick(e);
		onClose(e);
	}, [onClose]);
	const handleHeaderNewOrderClick = useCallback((e) => {
		var _appHelperUtils$actio2;
		stopUiClick(e);
		const createModeConfig = buildReservationTicketBookingCreateModeConfigForRow({
			reservationBiz,
			associated_menu_list_ids: associatedMenuListIds,
			reservationRuleProduct,
			row: tableRow !== null && tableRow !== void 0 ? tableRow : null
		});
		if (!createModeConfig) return;
		if (typeof reservationBiz === "string" && reservationBiz.trim() === "dine_in") {
			var _appHelperUtils$actio;
			appHelperUtils === null || appHelperUtils === void 0 || (_appHelperUtils$actio = appHelperUtils.action) === null || _appHelperUtils$actio === void 0 || _appHelperUtils$actio.call(appHelperUtils, {
				type: "pisell1.handleOpenCachedEditBooking",
				data: { createModeConfig: _objectSpread2({ initialModalState: createModeConfig.initialModalState }, createModeConfig.associated_menu_list_ids ? { associated_menu_list_ids: createModeConfig.associated_menu_list_ids } : {}) },
				callback: () => {}
			});
			return;
		}
		appHelperUtils === null || appHelperUtils === void 0 || (_appHelperUtils$actio2 = appHelperUtils.action) === null || _appHelperUtils$actio2 === void 0 || _appHelperUtils$actio2.call(appHelperUtils, {
			type: "pisell1.handleOpenEditBooking",
			data: { createModeConfig },
			callback: () => {}
		});
	}, [
		appHelperUtils,
		reservationBiz,
		associatedMenuListIds,
		reservationRuleProduct,
		tableRow
	]);
	const detailModalHeader = useMemo(() => /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__header` }, /* @__PURE__ */ React.createElement("button", {
		type: "button",
		className: `${PREFIX}__header-action ${PREFIX}__header-action--left`,
		onClick: handleHeaderCloseClick
	}, t("header-close")), /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__header-title` }, detailModalTitle), /* @__PURE__ */ React.createElement("button", {
		type: "button",
		className: `${PREFIX}__header-action ${PREFIX}__header-action--right`,
		onClick: handleHeaderNewOrderClick
	}, t("header-new-order"))), [
		detailModalTitle,
		handleHeaderCloseClick,
		handleHeaderNewOrderClick
	]);
	const getApp = appHelperUtils === null || appHelperUtils === void 0 ? void 0 : appHelperUtils.getApp;
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PisellModal, {
		platform: "pc",
		open: canShow,
		onCancel: onClose,
		maskProps: BD_MODAL_MASK,
		focusTriggerAfterClose: false,
		title: detailModalHeader,
		closable: false,
		footer: null,
		destroyOnClose: true,
		width: 560,
		wrapClassName: `${PREFIX}-wrap`,
		zIndex: 900
	}, raw ? /* @__PURE__ */ React.createElement("div", { className: PREFIX }, /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__body` }, /* @__PURE__ */ React.createElement("div", {
		className: `${PREFIX}__tabs`,
		role: "tablist",
		"aria-label": t("tabs-aria")
	}, DETAIL_TAB_ITEMS.map(({ key, labelKey }) => {
		const active = activeTab === key;
		const count = tabCounts === null || tabCounts === void 0 ? void 0 : tabCounts[key];
		return /* @__PURE__ */ React.createElement("button", {
			key,
			type: "button",
			role: "tab",
			"aria-selected": active,
			className: `${PREFIX}__tab${active ? ` ${PREFIX}__tab--active` : ""}`,
			onClick: (e) => {
				stopUiClick(e);
				setActiveTab(key);
			}
		}, t(labelKey), count != null ? /* @__PURE__ */ React.createElement("span", { className: `${PREFIX}__tab-count` }, " ", "(", count, ")") : null);
	})), /* @__PURE__ */ React.createElement("div", {
		className: `${PREFIX}__bookings-list`,
		role: "tabpanel",
		"aria-label": t(`tab-${activeTab}`)
	}, activeTabBookings.length === 0 ? !resourceBookingItemLoading ? /* @__PURE__ */ React.createElement("div", { className: `${PREFIX}__bookings-empty` }, t("empty-tab-bookings")) : null : activeTabBookings.map((bookingRaw, idx) => {
		var _ref, _ref2, _bookingRaw$id;
		const unitKey = String((_ref = (_ref2 = (_bookingRaw$id = bookingRaw.id) !== null && _bookingRaw$id !== void 0 ? _bookingRaw$id : bookingRaw.booking_uid) !== null && _ref2 !== void 0 ? _ref2 : bookingRaw.booking_id) !== null && _ref !== void 0 ? _ref : idx);
		return /* @__PURE__ */ React.createElement(BookingDetailUnit, {
			key: unitKey,
			bookingRaw,
			tableRow,
			isCancellingOrder,
			isCompletingBooking,
			getApp,
			onActionCellClick: handleActionCellClick
		});
	})))) : null), /* @__PURE__ */ React.createElement(editBookingModal_default, {
		ref: editBookingModalRef,
		open: false,
		onCancel: () => {},
		onOk: handleResourceChangeConfirmed
	}));
}
//#endregion
export { ReservationBookingDetailModal };
