/**
 * Copyright IBM Corp. 2020, 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { InlineEditContext } from "../InlineEdit/InlineEditContext/InlineEditContext.js";
import CustomizeColumnsTearsheet from "./CustomizeColumnsTearsheet.js";
import React, { useContext, useEffect } from "react";
import PropTypes from "prop-types";

//#region src/components/Datagrid/Datagrid/addons/CustomizeColumns/TearsheetWrapper.jsx
const TearsheetWrapper = ({ instance, launcherButtonRef }) => {
	const { onSaveColumnPrefs, isTearsheetOpen, setIsTearsheetOpen, labels, ...rest } = instance.customizeColumnsProps;
	const { state } = useContext(InlineEditContext);
	const { featureFlags } = state || {};
	useEffect(() => {
		if (featureFlags && !featureFlags?.["enable-datagrid-useCustomizeColumns"]) console.error(`Datagrid useCustomizeColumns extension has not been enabled via feature flag.`);
	}, [featureFlags]);
	return /* @__PURE__ */ React.createElement(CustomizeColumnsTearsheet, {
		...rest,
		...labels,
		isOpen: isTearsheetOpen,
		setIsTearsheetOpen,
		launcherButtonRef,
		columnDefinitions: instance.allColumns,
		originalColumnDefinitions: instance.columns,
		onSaveColumnPrefs: (updatedColDefs) => {
			setTimeout(() => {
				const hiddenIds = updatedColDefs.filter((colDef) => !colDef.isVisible).map((colDef) => colDef.id);
				instance.setHiddenColumns(hiddenIds);
				if (typeof instance.setColumnOrder === "function") instance.setColumnOrder(updatedColDefs.map((colDef) => colDef.id));
				else console.warn("Column order can not be updated. Did you forget to add 'useColumnOrder' in 'useDatagrid'");
			}, 0);
			if (typeof onSaveColumnPrefs === "function") onSaveColumnPrefs(updatedColDefs);
		}
	});
};
TearsheetWrapper.propTypes = { instance: PropTypes.object.isRequired };

//#endregion
export { TearsheetWrapper as default };