<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import type { HTMLAttributes } from 'svelte/elements';
import type { Extension } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import { debounce } from 'lodash-es';

import CodeEditorWrapper from './code-editor-wrapper.svelte';
import type { Language } from './codemirror';
import * as CodeMirror from './codemirror';

const DEFAULT_DEBOUNCE_PERIOD_MS = 250;

interface Props extends HTMLAttributes<HTMLDivElement> {
  /** Accessible label of the editor element. */
  label: string;
  /** Initial content of the editor. Will re-render if the value changes and does not match the current document. */
  value: string;
  /** Set editor to read-only mode. */
  readonly?: boolean;
  /** Enable line wrapping. Defaults to true for JSON/JSON5, false for other languages. */
  lineWrapping?: boolean;
  /** Programming language for syntax highlighting and editing. */
  language?: Language;
  /**
   * Enable diff mode, comparing the current contents to `diffOriginal`.
   *
   * If `undefined` or omitted, the editor will not use diff mode.
   */
  diffOriginal?: string;
  /** Debounce change events. */
  debouncePeriodMS?: number;
  /** Error message element ID. */
  errorMessageID?: string;
  /** Whether the value is invalid. */
  isInvalid?: boolean;
  /** Extra CodeMirror extensions (e.g., LSP client). */
  extraExtensions?: Extension[];
  /** Only trigger onChange on blur instead of on every change. */
  fireOnBlurOnly?: boolean;
  /** Notify of changes. */
  onChange?: (contents: string) => unknown;
}

const {
  label,
  value,
  readonly = false,
  lineWrapping,
  language = 'json',
  diffOriginal,
  debouncePeriodMS = DEFAULT_DEBOUNCE_PERIOD_MS,
  errorMessageID,
  isInvalid,
  class: extraClasses = '',
  extraExtensions,
  fireOnBlurOnly = false,
  onChange,
}: Props = $props();

let isEditing = $state(false);

let currentValue = $state<string>('');
let previousInitialValue = $state<string>();
let currentDiffOriginal = $state<string>();

let editorParent = $state<HTMLElement>();
let editorView = $state<EditorView>();

const debouncedOnChange = $derived(
  onChange ? debounce(onChange, debouncePeriodMS) : undefined
);

const handleChange = (nextValue: string) => {
  currentValue = nextValue;
  if (!fireOnBlurOnly) {
    debouncedOnChange?.(nextValue);
  }
};

const handleFocus = () => {
  isEditing = true;
};

const handleBlur = () => {
  isEditing = false;

  if (fireOnBlurOnly) {
    onChange?.(currentValue);
  } else {
    debouncedOnChange?.flush();
  }
};

/**
 * Initialize the editor when the parent mounts or initial value changes.
 *
 * Implemented as a function to avoid running whenever `currentValue`
 * changes.
 */
const initializeEditor = (
  nextParent: HTMLElement | undefined,
  nextInitialValue: string,
  nextDiffOriginal: string | undefined
): EditorView | undefined => {
  // Skip if DOM element not on the page
  if (!nextParent) {
    return editorView;
  }

  const isMounted = nextParent === editorView?.dom.parentElement;
  const preferCurrentState =
    isEditing ||
    (nextInitialValue === currentValue &&
      nextDiffOriginal === currentDiffOriginal);

  if (isMounted && preferCurrentState) {
    return editorView;
  }

  currentValue = nextInitialValue;
  editorView?.destroy();

  const extensions = CodeMirror.createCodeExtensions({
    label,
    readonly,
    errorMessageID,
    isInvalid,
    diffOriginal,
    lineWrapping: lineWrapping ?? (language === 'json' || language === 'json5'),
    language,
    onFocus: handleFocus,
    onBlur: handleBlur,
    extraExtensions,
  });

  return new EditorView({
    extensions,
    parent: nextParent,
    doc: nextInitialValue,
    dispatchTransactions: CodeMirror.createDispatchTransactions(
      handleChange,
      language
    ),
  });
};

onMount(() => {
  currentValue = value;
  previousInitialValue = value;
  currentDiffOriginal = diffOriginal;

  if (editorParent) {
    editorView = initializeEditor(editorParent, value, diffOriginal);
  }
});

$effect(() => {
  if (editorView) {
    CodeMirror.setReadOnly(editorView, readonly);
    CodeMirror.setLabel(editorView, label);
    CodeMirror.setErrorMessageID(editorView, errorMessageID);
    CodeMirror.setIsInvalid(editorView, isInvalid);
  }
});

// Handle diff Original changes
$effect(() => {
  if (editorView && diffOriginal !== currentDiffOriginal) {
    if (diffOriginal === undefined) {
      // Re-initialize to remove the merge view extension. Capture the
      // caret position and focus first so switching out of diff mode
      // doesn't reset the user's cursor in the rebuilt editor view.
      const previousView = editorView;
      const hadFocus = previousView.hasFocus;
      const anchor = previousView.state.selection.main.anchor;
      const view = initializeEditor(editorParent, value, diffOriginal);
      if (view) {
        editorView = view;
        if (view !== previousView && hadFocus) {
          view.dispatch({
            selection: { anchor: Math.min(anchor, view.state.doc.length) },
          });
          view.focus();
        }
      }
    } else {
      CodeMirror.setDiffOriginal(editorView, diffOriginal);
    }
    currentDiffOriginal = diffOriginal;
  }
});

// Handle initial value changes (when externally controlled).
// Skipped while editing so an in-progress edit is never overwritten
// (e.g. by a normalized round-trip of what the user is typing). When a
// sync does happen, preserve the caret position and focus.
$effect(() => {
  if (editorView && !isEditing && value !== previousInitialValue) {
    previousInitialValue = value;
    const doc = editorView.state.doc.toString();
    if (doc !== value) {
      const hadFocus = editorView.hasFocus;
      const anchor = Math.min(
        editorView.state.selection.main.anchor,
        value.length
      );
      currentValue = value;
      editorView.dispatch({
        changes: { from: 0, to: doc.length, insert: value },
        annotations: CodeMirror.externalUpdate.of(true),
      });
      if (hadFocus) {
        editorView.dispatch({ selection: { anchor } });
        editorView.focus();
      }
    }
  }
});

onDestroy(() => {
  isEditing = false;
  debouncedOnChange?.flush();
  editorView?.destroy();
});
</script>

<CodeEditorWrapper
  bind:element={editorParent}
  class={extraClasses}
/>
