/**
 * 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 { getCellIdAsObject } from "./InlineEditContext/getCellIdAsObject.js";
import { handleMultipleKeys } from "./handleMultipleKeys.js";
//#region src/components/Datagrid/Datagrid/addons/InlineEdit/handleGridKeyPress.js
/**
* Copyright IBM Corp. 2022, 2025
*
* 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 handleGridKeyPress = ({ event, dispatch, state, instance, keysPressedList, usingMac, ref, carbonPrefix }) => {
	const { key } = event;
	const { gridActive, activeCellId, editId } = state;
	const focusedCell = document.querySelector(`#${instance.tableId} .${blockClass}__table-with-inline-edit [data-cell-id="${activeCellId}"]`);
	if (activeCellId === editId && key === "Tab") {
		if (focusedCell.getAttribute("data-inline-type") === "date") {
			dispatch({
				type: "EXIT_EDIT_MODE",
				payload: activeCellId
			});
			document.querySelector(`#${instance.tableId} .${blockClass}__table-with-inline-edit`).focus();
		}
		event.preventDefault();
		return;
	}
	if (activeCellId === editId && key === "Escape") {
		if (focusedCell.getAttribute("data-inline-type") === "date") {
			dispatch({
				type: "EXIT_EDIT_MODE",
				payload: activeCellId
			});
			event.preventDefault();
			document.querySelector(`#${instance.tableId} .${blockClass}__table-with-inline-edit`).focus();
			return;
		}
	}
	const dropdownIsActive = () => {
		if (ref?.current.querySelector(`
      #${instance.tableId} .${blockClass}__table-with-inline-edit [data-cell-id="${activeCellId}"] button[role='combobox']
    `)) {
			event.preventDefault();
			return true;
		}
		return false;
	};
	const datePickerIsActive = () => {
		if (document.querySelector(`.${carbonPrefix}--date-picker__input.flatpickr-input.active`) || document.activeElement.classList.contains(`flatpickr-day`)) return true;
		return false;
	};
	const isEditing = focusedCell.getAttribute("data-inline-type") !== "checkbox" && document.activeElement.id === activeCellId && document.activeElement.id === editId || dropdownIsActive() || datePickerIsActive();
	if (isEditing || !gridActive) return;
	if (key === "Meta" || key === "Control") return;
	if ([
		"End",
		"Home",
		"ArrowLeft",
		"ArrowUp",
		"ArrowRight",
		"ArrowDown"
	].indexOf(key) > -1 && !isEditing && keysPressedList.length < 2) event.preventDefault();
	const isDisabledCell = focusedCell.getAttribute("data-disabled") === "false" ? false : true;
	const isEditableCell = !event.target.classList.contains(`${blockClass}__inline-edit-button--non-edit`);
	const sharedUpdateParams = {
		oldId: activeCellId,
		instance
	};
	if (keysPressedList.length > 1) handleMultipleKeys({
		usingMac,
		keysPressedList,
		dispatch,
		activeCellId,
		instance
	});
	if (keysPressedList.length < 2) switch (key) {
		case "Tab":
			if (!editId) dispatch({
				type: "REMOVE_GRID_ACTIVE_FOCUS",
				payload: activeCellId
			});
			break;
		case "ArrowRight":
			dispatch({
				type: "UPDATE_ACTIVE_CELL_ID",
				payload: {
					direction: "right",
					...sharedUpdateParams
				}
			});
			break;
		case "ArrowLeft":
			dispatch({
				type: "UPDATE_ACTIVE_CELL_ID",
				payload: {
					direction: "left",
					...sharedUpdateParams
				}
			});
			break;
		case "ArrowUp":
			dispatch({
				type: "UPDATE_ACTIVE_CELL_ID",
				payload: {
					direction: "up",
					...sharedUpdateParams
				}
			});
			break;
		case "ArrowDown":
			dispatch({
				type: "UPDATE_ACTIVE_CELL_ID",
				payload: {
					direction: "down",
					...sharedUpdateParams
				}
			});
			break;
		case "Home": {
			const newActiveCellCoords = {
				...getCellIdAsObject(activeCellId),
				column: 0
			};
			const newActiveCellId = `column-${newActiveCellCoords.column}-row-${newActiveCellCoords.row}`;
			const scrollElement = document.querySelector(`#${instance.tableId} .${pkg.prefix}--datagrid__table-container`);
			scrollElement.scrollLeft = 0;
			dispatch({
				type: "UPDATE_ACTIVE_CELL_ID",
				payload: newActiveCellId
			});
			break;
		}
		case "End": {
			const activeCellObject = getCellIdAsObject(activeCellId);
			const totalVisibleColumns = instance.visibleColumns.filter((item) => item.id !== "spacer");
			const newActiveCellCoords = {
				...activeCellObject,
				column: totalVisibleColumns.length - 1
			};
			const newActiveCellId = `column-${newActiveCellCoords.column}-row-${newActiveCellCoords.row}`;
			const scrollElement = document.querySelector(`#${instance.tableId} .${pkg.prefix}--datagrid__table-container`);
			scrollElement.scrollLeft = scrollElement.scrollWidth;
			dispatch({
				type: "UPDATE_ACTIVE_CELL_ID",
				payload: newActiveCellId
			});
			break;
		}
		case " ":
		case "F2":
		case "Enter":
			if (isDisabledCell || !isEditableCell) return;
			if (!editId) {
				const focusedType = focusedCell.getAttribute("data-inline-type");
				if (focusedType === "selection") setTimeout(() => {
					focusedCell.querySelector("button")?.click();
				}, 1);
				if (focusedType === "checkbox") setTimeout(() => {
					const checkboxTrigger = focusedCell.querySelector("input");
					checkboxTrigger?.click();
					checkboxTrigger?.focus();
				}, 1);
				if (focusedType === "date") setTimeout(() => {
					const dateInputTrigger = focusedCell.querySelector("input");
					dateInputTrigger?.click();
					dateInputTrigger?.focus();
				}, 1);
				dispatch({
					type: "ENTER_EDIT_MODE",
					payload: {
						activeCellId,
						editId: activeCellId
					}
				});
			}
	}
};
//#endregion
export { handleGridKeyPress };
