/*
*  author: Yagnik Poshiya
*  organization: Webbrains Technologies Private Limited
*/
'use client';

import { useCallback, useMemo, useRef } from 'react';

import type { MarkdownTokenKind } from '@/lib/storage/markdown-highlight';
import { tokenizeForExtension } from '@/lib/storage/markdown-highlight';

/**
 * Every layer shares these metrics. The gutter, the highlight overlay and the
 * textarea are three separate boxes drawn on top of each other, so if their
 * font, size or line-height drift apart the line numbers stop pointing at the
 * right line.
 */
const LINE_METRICS = 'font-mono text-[13px] leading-6';

/**
 * Lines are never wrapped. One source line is one visual row, which is what
 * lets the gutter number them; wrapping would need the browser's line-box
 * count, which is not observable from here.
 */
const LINE_BOX = 'h-6 whitespace-pre';

const TOKEN_CLASS: Record<MarkdownTokenKind, string> = {
  plain: '',
  heading: 'font-semibold text-emerald-700 dark:text-emerald-300',
  fence: 'text-violet-600 dark:text-violet-300',
  code: 'text-amber-700 dark:text-amber-300',
  quote: 'italic text-neutral-500 dark:text-neutral-400',
  marker: 'text-sky-600 dark:text-sky-300',
  bold: 'font-semibold text-neutral-900 dark:text-neutral-50',
  italic: 'italic text-neutral-700 dark:text-neutral-300',
  linkText: 'text-blue-600 dark:text-blue-300',
  linkUrl: 'text-blue-500 underline dark:text-blue-400',
  hr: 'text-neutral-400 dark:text-neutral-500',
};

type StorageDocumentEditorProps = {
  value: string;
  onChange: (next: string) => void;
  /** Lowercase extension without dot. Only "md" is highlighted. */
  fileExtension: string;
  disabled?: boolean;
};

export function StorageDocumentEditor({
  value,
  onChange,
  fileExtension,
  disabled = false,
}: StorageDocumentEditorProps) {
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);
  const overlayRef = useRef<HTMLDivElement | null>(null);
  const gutterRef = useRef<HTMLDivElement | null>(null);

  const lines = useMemo(
    () => tokenizeForExtension(value, fileExtension),
    [value, fileExtension],
  );

  // The textarea is the only scrollable layer the user drives; the other two
  // follow it.
  const syncScroll = useCallback(() => {
    const el = textareaRef.current;
    if (!el) return;
    if (overlayRef.current) {
      overlayRef.current.scrollTop = el.scrollTop;
      overlayRef.current.scrollLeft = el.scrollLeft;
    }
    if (gutterRef.current) {
      gutterRef.current.scrollTop = el.scrollTop;
    }
  }, []);

  const handleKeyDown = useCallback(
    (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
      if (event.key !== 'Tab') return;
      // Without this, Tab leaves the editor — unhelpful in an indented file.
      event.preventDefault();
      const el = event.currentTarget;
      const { selectionStart, selectionEnd } = el;
      const next = `${value.slice(0, selectionStart)}  ${value.slice(selectionEnd)}`;
      onChange(next);
      requestAnimationFrame(() => {
        el.selectionStart = selectionStart + 2;
        el.selectionEnd = selectionStart + 2;
      });
    },
    [onChange, value],
  );

  return (
    <div className="flex min-h-0 flex-1 overflow-hidden rounded-lg border border-neutral-300 bg-white dark:border-neutral-700 dark:bg-neutral-950">
      <div
        ref={gutterRef}
        aria-hidden
        className={`${LINE_METRICS} select-none overflow-hidden border-r border-neutral-200 bg-neutral-50 py-3 text-right text-neutral-400 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-600`}
        style={{ minWidth: '3.25rem' }}
      >
        {lines.map((_line, index) => (
          <div key={index} className={`${LINE_BOX} px-3`}>
            {index + 1}
          </div>
        ))}
      </div>

      <div className="relative min-w-0 flex-1">
        <div
          ref={overlayRef}
          aria-hidden
          className={`${LINE_METRICS} pointer-events-none absolute inset-0 overflow-hidden p-3 text-neutral-800 dark:text-neutral-200`}
        >
          {lines.map((line, index) => (
            <div key={index} className={LINE_BOX}>
              {line.tokens.map((token, tokenIndex) => (
                <span key={tokenIndex} className={TOKEN_CLASS[token.kind]}>
                  {token.text}
                </span>
              ))}
            </div>
          ))}
        </div>

        <textarea
          ref={textareaRef}
          value={value}
          onChange={(event) => onChange(event.target.value)}
          onScroll={syncScroll}
          onKeyDown={handleKeyDown}
          disabled={disabled}
          spellCheck={false}
          autoComplete="off"
          autoCorrect="off"
          autoCapitalize="off"
          wrap="off"
          aria-label="File contents"
          // Transparent text so the highlighted overlay shows through, but a
          // real caret and a real selection so it still behaves as a textarea.
          className={`${LINE_METRICS} absolute inset-0 h-full w-full resize-none overflow-auto bg-transparent p-3 text-transparent caret-neutral-900 outline-none selection:bg-sky-200/60 disabled:cursor-not-allowed dark:caret-neutral-100 dark:selection:bg-sky-500/30`}
        />
      </div>
    </div>
  );
}
