/**
 * 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 { pkg } from "../../../../../settings.js";
import { TearsheetNarrow } from "../../../../Tearsheet/TearsheetNarrow.js";
import Columns from "./Columns.js";
import Actions from "./Actions.js";
import React, { useCallback, useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";

//#region src/components/Datagrid/Datagrid/addons/CustomizeColumns/CustomizeColumnsTearsheet.jsx
/**
* Copyright IBM Corp. 2022, 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const blockClass = `${pkg.prefix}--datagrid`;
const CustomizeColumnsTearsheet = ({ isOpen, setIsTearsheetOpen, launcherButtonRef, onSaveColumnPrefs, columnDefinitions, originalColumnDefinitions, customizeTearsheetHeadingLabel = "Customize columns", primaryButtonTextLabel = "Save", secondaryButtonTextLabel = "Cancel", instructionsLabel = "Select columns to display them. Click and drag the box to reorder the columns. These specifications will be saved and persist if you leave and return to the data table.", findColumnPlaceholderLabel = "Find column", resetToDefaultLabel = "Reset to default", assistiveTextInstructionsLabel = "Press space bar to toggle drag drop mode, use arrow keys to move selected elements.", assistiveTextDisabledInstructionsLabel = "Reordering columns are disabled because they are filtered currently.", selectAllLabel = "Column name" }) => {
	const [visibleColumnsCount, setVisibleColumnsCount] = useState("");
	const [totalColumns, setTotalColumns] = useState("");
	const [searchText, setSearchText] = useState("");
	const [columnObjects, setColumnObjects] = useState(columnDefinitions);
	const [isDirty, setIsDirty] = useState(false);
	const prevColumnDefinitions = useRef(void 0);
	const onRequestClose = () => {
		setColumnObjects(columnDefinitions);
		setIsTearsheetOpen(false);
	};
	const onRequestSubmit = () => {
		setIsTearsheetOpen(false);
		onSaveColumnPrefs(columnObjects.map((colDef) => ({
			id: colDef.id,
			isVisible: colDef.isVisible
		})));
	};
	const onCheckboxCheck = (col, value) => {
		const changedDefinitions = columnObjects.map((definition) => {
			if (Array.isArray(col)) return col.includes(definition) && definition.canFilter && !definition.disabled ? {
				...definition,
				isVisible: value
			} : definition;
			return col.id === definition.id ? {
				...definition,
				isVisible: value
			} : definition;
		});
		const selectedColumnsCount = changedDefinitions.filter((definition) => definition.isVisible && !["datagridSelection", "actions"].includes(definition.id)).length;
		setColumnObjects(changedDefinitions.map((definition) => {
			if (selectedColumnsCount > 0) return ["datagridSelection", "actions"].includes(definition.id) ? {
				...definition,
				isVisible: true
			} : definition;
			return ["datagridSelection", "actions"].includes(definition.id) ? {
				...definition,
				isVisible: false
			} : definition;
		}));
		setIsDirty(selectedColumnsCount !== 0);
	};
	const getVisibleColumnsCount = useCallback(() => {
		return columnObjects.filter((col) => col.isVisible).length;
	}, [columnObjects]);
	const string = searchText.trim().toLowerCase();
	useEffect(() => {
		if (!isOpen) return;
		if (prevColumnDefinitions.current !== columnDefinitions) setColumnObjects(columnDefinitions);
		const actionCount = columnObjects.filter((col) => col.id === "actions").length;
		const datagridSelectionCount = columnObjects.filter((col) => col.id === "datagridSelection").length;
		setVisibleColumnsCount(getVisibleColumnsCount() - actionCount - datagridSelectionCount < 0 ? 0 : getVisibleColumnsCount() - actionCount - datagridSelectionCount);
		setTotalColumns(columnObjects.length - actionCount - datagridSelectionCount);
		prevColumnDefinitions.current = columnDefinitions;
	}, [
		getVisibleColumnsCount,
		columnObjects,
		columnDefinitions
	]);
	return /* @__PURE__ */ React.createElement(TearsheetNarrow, {
		className: `${blockClass}__customize-columns-tearsheet`,
		open: isOpen,
		title: `${customizeTearsheetHeadingLabel} (${visibleColumnsCount}/${totalColumns})`,
		description: instructionsLabel,
		launcherButtonRef,
		actions: [{
			kind: "secondary",
			label: secondaryButtonTextLabel,
			onClick: onRequestClose
		}, {
			kind: "primary",
			label: primaryButtonTextLabel,
			onClick: onRequestSubmit,
			disabled: !isDirty
		}]
	}, /* @__PURE__ */ React.createElement(Actions, {
		columns: columnObjects,
		originalColumnDefinitions,
		searchText,
		setColumnsObject: (cols) => {
			setColumnObjects(cols);
			setIsDirty(true);
		},
		setSearchText,
		findColumnPlaceholderLabel,
		resetToDefaultLabel
	}), isOpen && /* @__PURE__ */ React.createElement(Columns, {
		assistiveTextInstructionsLabel,
		assistiveTextDisabledInstructionsLabel,
		getVisibleColumnsCount,
		columns: columnObjects,
		filterString: string,
		onSelectColumn: onCheckboxCheck,
		setColumnsObject: (cols) => {
			setColumnObjects(cols);
			setIsDirty(getVisibleColumnsCount() !== 0);
		},
		selectAllLabel,
		customizeTearsheetHeadingLabel
	}));
};
CustomizeColumnsTearsheet.propTypes = {
	assistiveTextDisabledInstructionsLabel: PropTypes.string,
	assistiveTextInstructionsLabel: PropTypes.string,
	columnDefinitions: PropTypes.array.isRequired,
	customizeTearsheetHeadingLabel: PropTypes.string,
	findColumnPlaceholderLabel: PropTypes.string,
	instructionsLabel: PropTypes.string,
	isOpen: PropTypes.bool.isRequired,
	onSaveColumnPrefs: PropTypes.func.isRequired,
	originalColumnDefinitions: PropTypes.array.isRequired,
	primaryButtonTextLabel: PropTypes.string,
	resetToDefaultLabel: PropTypes.string,
	secondaryButtonTextLabel: PropTypes.string,
	selectAllLabel: PropTypes.string,
	setIsTearsheetOpen: PropTypes.func.isRequired
};

//#endregion
export { CustomizeColumnsTearsheet as default };