import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { withMode } from "../../dataSourceForm/utils.js";
import RecordListWrapperReadPretty from "./ReadPretty.js";
import Tabs from "../Tabs/Tabs.js";
import DataSourceSubForm from "../../dataSourceSubForm/index.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
//#region src/components/dataSourceComponents/fields/RecordListWrapper/WithMode.tsx
/**
* @title RecordListWrapper 编辑器
* @description
*   上部为插槽区域（topSlot），通过 cloneElement 注入 options/value/onChange，默认展示 Tabs 导航。
*   下部委托给 DataSourceSubForm 渲染当前 activeKey 对应的子表单。
*   切换 tab 时通过 key={activeKey} 强制重新挂载 DataSourceSubForm，实现值自动同步。
*
*   值结构: { [optionValue]: { field1: v1, field2: v2 } }
*/
const RecordListWrapperBase = (props) => {
	const { value, onChange, options = [], children, xRecordSchema, topSlot, slot, renderMode, __designMode, defaultValue } = props;
	const isMounted = useRef(false);
	const dataSourceSubFormRef = useRef(null);
	/** value 是 Map: { optionValue: { field1: v1 } } */
	const safeValue = useMemo(() => {
		if (value && typeof value === "object" && !Array.isArray(value)) return value;
		return {};
	}, [value]);
	/**
	* 当前选中的 option key
	* 优先级：defaultActiveKey > options[0].value
	*/
	const [activeKey, setActiveKey] = useState(() => {
		var _options$;
		if (defaultValue != null) return String(defaultValue);
		return String(((_options$ = options[0]) === null || _options$ === void 0 ? void 0 : _options$.value) || "");
	});
	/** defaultValue 变化时同步更新 activeKey */
	useEffect(() => {
		if (defaultValue != null) setActiveKey(String(defaultValue));
	}, [defaultValue]);
	/** options 变化时校正 activeKey（仅在无 defaultValue 且当前 key 不合法时回退） */
	useEffect(() => {
		if (options.length && !options.find((o) => String(o.value) === activeKey)) {
			var _options$2;
			setActiveKey(defaultValue != null ? String(defaultValue) : String(((_options$2 = options[0]) === null || _options$2 === void 0 ? void 0 : _options$2.value) || ""));
		}
	}, [options]);
	/**
	* 初始化所有 option 的值：
	* 以字段 schema 中的 uiSchema.default 作为每个 option 的默认值模板，
	* 已有值（safeValue）优先覆盖，确保已填写的数据不丢失。
	* 仅执行一次（由 isMounted 守卫），避免重复触发 onChange。
	*/
	useEffect(() => {
		if (isMounted.current) return;
		if ((options === null || options === void 0 ? void 0 : options.length) > 0 && dataSourceSubFormRef.current) {
			var _dataSourceSubFormRef, _dataSourceSubFormRef2, _dataSourceSubFormRef3;
			const defaultValues = (_dataSourceSubFormRef = (_dataSourceSubFormRef2 = (_dataSourceSubFormRef3 = dataSourceSubFormRef.current).getFieldsValue) === null || _dataSourceSubFormRef2 === void 0 ? void 0 : _dataSourceSubFormRef2.call(_dataSourceSubFormRef3)) !== null && _dataSourceSubFormRef !== void 0 ? _dataSourceSubFormRef : {};
			const completeValue = options.reduce((acc, option) => {
				if (option.value === null || option.value === void 0) return acc;
				acc[String(option.value)] = _objectSpread2(_objectSpread2({}, defaultValues), safeValue[String(option.value)] || {});
				return acc;
			}, {});
			onChange === null || onChange === void 0 || onChange(completeValue);
			isMounted.current = true;
		}
	}, [options, safeValue]);
	const renderTopSlot = () => {
		const slotElement = topSlot || slot;
		if (slotElement && React.isValidElement(slotElement)) return React.cloneElement(slotElement, {
			options,
			value: activeKey,
			onChange: setActiveKey
		});
		const tabOptions = options.map((o) => {
			var _o$label;
			return _objectSpread2(_objectSpread2({}, o), {}, { label: (_o$label = o.label) !== null && _o$label !== void 0 ? _o$label : String(o.value) });
		});
		if (!options.length) return /* @__PURE__ */ React.createElement("div", { style: {
			color: "#999",
			fontSize: 16
		} }, "暂无选项，请配置数据源。");
		return /* @__PURE__ */ React.createElement(Tabs, {
			options: tabOptions,
			value: activeKey,
			onChange: (key) => setActiveKey(String(key)),
			disabled: renderMode === "disabled"
		});
	};
	const renderBottom = () => {
		return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(DataSourceSubForm, {
			activeKey,
			value: safeValue[activeKey],
			onChange: (recordValue) => onChange === null || onChange === void 0 ? void 0 : onChange(_objectSpread2(_objectSpread2({}, safeValue || {}), {}, { [activeKey]: recordValue || {} })),
			xRecordSchema,
			renderMode,
			__designMode
		}, children), /* @__PURE__ */ React.createElement("div", { style: {
			width: "100%",
			height: 0,
			visibility: "hidden",
			overflow: "hidden"
		} }, /* @__PURE__ */ React.createElement(DataSourceSubForm, {
			key: "record-list-wrapper-default-value-form",
			ref: dataSourceSubFormRef,
			xRecordSchema,
			renderMode,
			__designMode
		}, children)));
	};
	return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { style: { marginBottom: 12 } }, renderTopSlot()), renderBottom());
};
const RecordListWrapperWithMode = withMode(RecordListWrapperBase, RecordListWrapperReadPretty);
//#endregion
export { RecordListWrapperWithMode as default };
