import { getCurrentLocale } from "../../utils/locale.js";
import { getText } from "../../locales/index.js";
import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { PISELL_MOBILE_DATE_RANGE_PICKER_FILTER_POPUP_CLASS } from "./types.js";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import classNames from "classnames";
import dayjs from "dayjs";
import { CalendarPicker, ConfigProvider } from "antd-mobile";
import Calendar from "@pisell/icon/es/Calendar";
import antdMobileZhCN from "antd-mobile/es/locales/zh-CN";
import antdMobileZhTW from "antd-mobile/es/locales/zh-TW";
import antdMobileZhHK from "antd-mobile/es/locales/zh-HK";
import antdMobileEnUS from "antd-mobile/es/locales/en-US";
import antdMobileJaJP from "antd-mobile/es/locales/ja-JP";
import antdMobilePtBR from "antd-mobile/es/locales/pt-BR";
import "antd-mobile/es/global/global.css";
import "./PisellMobileDateRangePicker.less";
//#region src/components/pisellMobileDateRangePicker/PisellMobileDateRangePicker.tsx
/**
* 项目语言 → antd-mobile 内置 locale 包映射。
* 对齐 packages/materials/src/locales/index.ts 的 langMap。
* 未匹配时回落 en-US。
*/
const ANTD_MOBILE_LOCALE_MAP = {
	"zh-CN": antdMobileZhCN,
	"zh-TW": antdMobileZhTW,
	"zh-HK": antdMobileZhHK,
	"en-US": antdMobileEnUS,
	en: antdMobileEnUS,
	original: antdMobileEnUS,
	ja: antdMobileJaJP,
	pt: antdMobilePtBR
};
/** 高于 antd Popover 默认 1030，避免嵌套在齿轮/Filter 弹层下被遮挡 */
const FILTER_POPUP_Z_INDEX = 1100;
/**
* 默认日期范围：当前月起往前 1 年。
* - antd-mobile `CalendarPickerView` 默认窗口仅「打开月 +6 个月」，业务上预约/筛选场景
*   常需要至少能往前查 1 年。
* - 该组件 `renderBody` 是「一次性把 min..max 之间所有月份都渲染」，无虚拟滚动；
*   ±1 年（约 13 个月）DOM 量在 ≈400 cells，开销可接受。
* - 业务方仍可用 `min` / `max` props 显式覆盖。
*/
function getDefaultMin() {
	return dayjs().subtract(1, "year").startOf("month").toDate();
}
function getDefaultMax() {
	return dayjs().endOf("month").toDate();
}
/** 与 FilterItem `toRangePickerValue` 一致：兼容 form 中的 dayjs[] / string[] / Date[] */
function toDayjsRange(val) {
	if (val == null) return null;
	if (!Array.isArray(val) || val.length < 2) return null;
	const start = val[0] ? dayjs.isDayjs(val[0]) ? val[0] : dayjs(val[0]) : null;
	const end = val[1] ? dayjs.isDayjs(val[1]) ? val[1] : dayjs(val[1]) : null;
	if (!(start === null || start === void 0 ? void 0 : start.isValid()) || !(end === null || end === void 0 ? void 0 : end.isValid())) return null;
	return [start, end];
}
function toDateRange(val) {
	const normalized = toDayjsRange(val);
	if (!normalized) return null;
	return [normalized[0].toDate(), normalized[1].toDate()];
}
function formatRangeLabel(range, format, placeholder) {
	if (!range) return placeholder;
	return `${range[0].format(format)} - ${range[1].format(format)}`;
}
function resolveFilterGetContainer() {
	if (typeof document === "undefined") return null;
	return document.body;
}
/**
* antd-mobile CalendarPicker（range）薄封装：受控 value/onChange 与 RecordBoard 快筛 dayjs[] 对齐。
*/
const PisellMobileDateRangePicker = ({ value, onChange, format = "DD/MM/YYYY", placeholder, className, style, title, confirmText, allowClear = true, min, max, variant = "toolbar", getContainer, popupClassName, popupStyle, onOpen, onClose }) => {
	var _ANTD_MOBILE_LOCALE_M, _popupStyle$zIndex;
	const [visible, setVisible] = useState(false);
	const dayjsRange = useMemo(() => toDayjsRange(value), [value]);
	const pickerValue = useMemo(() => toDateRange(value), [value]);
	/**
	* 弹层「内部受控」缓冲：
	* - antd-mobile `CalendarPickerView` 内部 `usePropsValue` 每次渲染都执行
	*   `if (value !== undefined) stateRef.current = value`，因此一旦透传非空 `value`，
	*   单格点选触发的 `setDateRange + onChange` 不写回外层 form 时，下一次重渲染会立刻把
	*   内部累计选择覆盖回 prop 原值，表现为「点格子完全无反应」。
	* - 解决：始终把 `value` 接到本地 `innerValue`，并把 `onChange` 写回 `innerValue`，
	*   形成真正的「弹层内部受控」。打开弹层时再用外部 form 值同步一次初值。
	*   `onConfirm` 时把 `innerValue` 写回外部 form。
	*/
	const [innerValue, setInnerValue] = useState(pickerValue);
	useEffect(() => {
		if (visible) setInnerValue(pickerValue);
	}, [visible]);
	const resolvedPlaceholder = placeholder !== null && placeholder !== void 0 ? placeholder : getText("pisell-mobile-date-range-picker-placeholder");
	const resolvedTitle = title !== null && title !== void 0 ? title : getText("pisell-mobile-date-range-picker-title");
	const resolvedConfirmText = confirmText !== null && confirmText !== void 0 ? confirmText : getText("pisell-mobile-date-range-picker-confirm");
	const antMobileLocale = (_ANTD_MOBILE_LOCALE_M = ANTD_MOBILE_LOCALE_MAP[getCurrentLocale()]) !== null && _ANTD_MOBILE_LOCALE_M !== void 0 ? _ANTD_MOBILE_LOCALE_M : antdMobileEnUS;
	const isFilterVariant = variant === "filter";
	const openPicker = useCallback(() => {
		setVisible(true);
		onOpen === null || onOpen === void 0 || onOpen();
	}, [onOpen]);
	const closePicker = useCallback(() => {
		setVisible(false);
		onClose === null || onClose === void 0 || onClose();
	}, [onClose]);
	const handleConfirm = useCallback((next) => {
		if (!next) {
			onChange === null || onChange === void 0 || onChange(void 0);
			closePicker();
			return;
		}
		onChange === null || onChange === void 0 || onChange([dayjs(next[0]).startOf("day"), dayjs(next[1]).startOf("day")]);
		closePicker();
	}, [onChange, closePicker]);
	const resolvedGetContainer = getContainer !== null && getContainer !== void 0 ? getContainer : isFilterVariant ? resolveFilterGetContainer : void 0;
	const resolvedPopupClassName = classNames(isFilterVariant ? PISELL_MOBILE_DATE_RANGE_PICKER_FILTER_POPUP_CLASS : null, popupClassName);
	const resolvedPopupStyle = isFilterVariant ? _objectSpread2(_objectSpread2({}, popupStyle), {}, { zIndex: (_popupStyle$zIndex = popupStyle === null || popupStyle === void 0 ? void 0 : popupStyle.zIndex) !== null && _popupStyle$zIndex !== void 0 ? _popupStyle$zIndex : FILTER_POPUP_Z_INDEX }) : popupStyle;
	return /* @__PURE__ */ React.createElement("div", {
		className: classNames("pisell-mobile-date-range-picker", { "pisell-mobile-date-range-picker--filter": isFilterVariant }, className),
		style
	}, /* @__PURE__ */ React.createElement("button", {
		type: "button",
		className: classNames("pisell-mobile-date-range-picker__trigger", { "pisell-mobile-date-range-picker__trigger--placeholder": !dayjsRange }),
		onClick: openPicker
	}, /* @__PURE__ */ React.createElement("span", { className: "pisell-mobile-date-range-picker__trigger-text" }, formatRangeLabel(dayjsRange, format, resolvedPlaceholder)), isFilterVariant ? /* @__PURE__ */ React.createElement(Calendar, {
		className: "pisell-mobile-date-range-picker__trigger-icon",
		"aria-hidden": true
	}) : null), /* @__PURE__ */ React.createElement(ConfigProvider, { locale: antMobileLocale }, /* @__PURE__ */ React.createElement(CalendarPicker, {
		visible,
		selectionMode: "range",
		value: innerValue !== null && innerValue !== void 0 ? innerValue : void 0,
		onChange: (v) => setInnerValue(v),
		onClose: closePicker,
		onMaskClick: closePicker,
		closeOnMaskClick: true,
		onConfirm: handleConfirm,
		title: resolvedTitle,
		confirmText: resolvedConfirmText,
		allowClear,
		min: min !== null && min !== void 0 ? min : getDefaultMin(),
		max: max !== null && max !== void 0 ? max : getDefaultMax(),
		getContainer: resolvedGetContainer,
		popupClassName: resolvedPopupClassName || void 0,
		popupStyle: resolvedPopupStyle
	})));
};
//#endregion
export { PisellMobileDateRangePicker };
