/**
 * @file UnsavedChangesModal.tsx - Modal that appears when the user tries to switch to a different FolderTree node (folder or document) while the current node has unsaved changes.
 * Dynamically describes what changed (folder fields, template fields, or document content) and what will be selected (folder, another document).
 * Offers cancel and discard changes options. Enter key triggers the discard action.
 */

import { useProcessingUI } from '../../../contexts/ProcessingUIContext.tsx';
import { useEffect } from 'react';
import { Key } from 'ts-key-enum';
import type { FolderNode } from '../DetailsFolderPanel/sections/FolderSection/FolderTree.tsx';
import { Button, Modal } from 'react-bootstrap';
import { Trans, useTranslation } from 'react-i18next';

/**
 * Unsaved Changes modal that may appear when attempting to select a different FolderTree node while the current node has unsaved field or document content changes.
 */
export const UnsavedChangesModal = () => {
  const {
    unsavedChangesModalShown,
    hideUnsavedChangesModal,
    discardChanges,
    newNodeAfterChangesDiscarded,
    selectedNode,
    selectedNodeFieldsHaveChanged,
  } = useProcessingUI();

  // Register Enter key listener when modal is visible to allow quick discard confirmation
  useEffect(() => {
    if (!unsavedChangesModalShown) {
      return;
    }

    // Enter key triggers discard confirmation
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === Key.Enter) {
        event.preventDefault();
        discardChanges();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [unsavedChangesModalShown]);

  const { t } = useTranslation(undefined, {
    keyPrefix: 'components.processing.modals.unsaved_changes',
  });

  if (!selectedNode || !newNodeAfterChangesDiscarded) {
    return null;
  }

  // Dynamically determine the change description and navigation target for the modal message
  let whatChanged: string;
  let willBeSelected: string;
  if (
    (selectedNode as FolderNode).folderId !== undefined &&
    selectedNodeFieldsHaveChanged
  ) {
    whatChanged = t('variables.what_changed.folder_fields');
    willBeSelected = t('variables.will_be_selected.a_document');
  } else {
    if (selectedNodeFieldsHaveChanged) {
      whatChanged = t('variables.what_changed.template_fields');
    } else {
      whatChanged = t('variables.what_changed.document_content');
    }

    if ((newNodeAfterChangesDiscarded as FolderNode).folderId !== undefined) {
      willBeSelected = t('variables.will_be_selected.folder');
    } else {
      willBeSelected = t('variables.will_be_selected.another_document');
    }
  }

  return (
    <Modal
      centered
      show={unsavedChangesModalShown}
      onHide={hideUnsavedChangesModal}
    >
      <Modal.Header closeButton>
        <Modal.Title>{t('modal.header.title')}</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <p>
          {t('modal.body.paragraph_text', {
            what_changed: whatChanged,
            will_be_selected: willBeSelected,
          })}
        </p>
        <p className={'mb-0'}>
          {t('modal.body.instructions_text')}{' '}
          <span className={'text-danger'}>
            <Trans t={t} i18nKey={'modal.body.warning_text'} />
          </span>
        </p>
      </Modal.Body>
      <Modal.Footer>
        <Button variant={'secondary'} onClick={hideUnsavedChangesModal}>
          {t('modal.footer.buttons.cancel.button_text')}
        </Button>
        <Button variant={'danger'} onClick={discardChanges}>
          {t('modal.footer.buttons.discard_changes.button_text')}
        </Button>
      </Modal.Footer>
    </Modal>
  );
};
