/**
 * @file useFolderTreeHotkeys.ts - Registers keyboard shortcuts for the FolderTree component.
 */

import { useHotkeys } from 'react-hotkeys-hook';
import { assembleHotKeyString } from '../../utils/hotKeys.ts';
import { Key } from 'ts-key-enum';
import type { DocumentNode } from '../../components/Processing/DetailsFolderPanel/sections/FolderSection/FolderTree.tsx';
import * as UAParser from 'ua-parser-js';
import i18next from 'i18next';

/** Props required by {@link useFolderTreeHotkeys}. */
interface UseFolderTreeHotkeysProps {
  /** Ordered list of document nodes displayed in the folder tree */
  documentNodes: DocumentNode[];

  /** ID of the currently selected document */
  selectedDocumentId: number | undefined;

  /** When true, navigation hotkeys are suppressed to prevent switching mid-load */
  documentIsLoading: boolean;

  /** Callback to select a document node by reference */
  selectDocumentNode: (document: DocumentNode) => void;

  /** Detected operating system, used to adjust modifier keys for macOS */
  os: UAParser.IOS;
}

/**
 * Registers hotkeys used in the FolderTree component.
 */
export const useFolderTreeHotkeys = ({
  documentNodes,
  selectedDocumentId,
  documentIsLoading,
  selectDocumentNode,
  os,
}: UseFolderTreeHotkeysProps) => {
  const tKey = 'hooks.hotkeys.folder_tree';

  // Navigate to previous document hotkey
  useHotkeys(
    assembleHotKeyString(
      os.is('macOS') ? [Key.Control, Key.Meta] : [Key.Control],
      [Key.ArrowLeft]
    ),
    () => {
      const previousIndex =
        documentNodes.findIndex(
          (node) => node.documentId === selectedDocumentId
        ) - 1;
      if (previousIndex >= 0 && !documentIsLoading) {
        selectDocumentNode(documentNodes[previousIndex]);
      }
    },
    {
      preventDefault: true,
      description: `[nav]${i18next.t(tKey + '.navigate_previous_document')}`,
    }
  );

  // Navigate to next document hotkey
  useHotkeys(
    assembleHotKeyString(
      os.is('macOS') ? [Key.Control, Key.Meta] : [Key.Control],
      [Key.ArrowRight]
    ),
    () => {
      const nextIndex =
        documentNodes.findIndex(
          (node) => node.documentId === selectedDocumentId
        ) + 1;
      if (nextIndex <= documentNodes.length - 1 && !documentIsLoading) {
        selectDocumentNode(documentNodes[nextIndex]);
      }
    },
    {
      preventDefault: true,
      description: `[nav]${i18next.t(tKey + '.navigate_next_document')}`,
    }
  );
};
