"use client";

import { useRef, useEffect } from "react";
import { EditorView, lineNumbers, highlightActiveLine } from "@codemirror/view";
import { EditorState } from "@codemirror/state";
import { foldGutter } from "@codemirror/language";
import { javascript } from "@codemirror/lang-javascript";
import { json } from "@codemirror/lang-json";

// ── Custom theme — neutral Notion-style palette ─────────────────

const rpTheme = EditorView.theme(
  {
    "&": {
      backgroundColor: "#1e1e1e",
      color: "#e8e8e8",
      fontSize: "var(--text-xs)",
      height: "100%",
    },
    ".cm-scroller": {
      overflow: "auto",
      fontFamily: "var(--font-mono), ui-monospace, monospace",
    },
    ".cm-content": {
      fontFamily: "var(--font-mono), ui-monospace, monospace",
      caretColor: "#2383e2",
    },
    ".cm-cursor, .cm-dropCursor": {
      borderLeftColor: "#2383e2",
    },
    "&.cm-focused .cm-selectionBackground, .cm-selectionBackground": {
      backgroundColor: "rgba(35, 131, 226, 0.15)",
    },
    ".cm-gutters": {
      backgroundColor: "#191919",
      color: "#888888",
      border: "none",
      borderRight: "1px solid #333333",
    },
    ".cm-activeLineGutter": {
      backgroundColor: "#252525",
      color: "#e8e8e8",
    },
    ".cm-activeLine": {
      backgroundColor: "rgba(37, 37, 37, 0.5)",
    },
    ".cm-foldGutter": {
      color: "#888888",
    },
    ".cm-lineNumbers .cm-gutterElement": {
      padding: "0 8px 0 16px",
      minWidth: "3em",
    },
    ".cm-editor": {
      height: "100%",
    },
  },
  { dark: true },
);

// ── Language resolver ────────────────────────────────────────────

function getLanguageExtension(language: string) {
  switch (language) {
    case "java":
      // Java uses similar syntax to JS for basic highlighting
      return javascript();
    case "javascript":
      return javascript();
    case "typescript":
      return javascript({ typescript: true });
    case "json":
      return json();
    default:
      return [];
  }
}

// ── Component ────────────────────────────────────────────────────

interface CodeEditorProps {
  content: string;
  language: string;
  focusLine?: number;
}

export function CodeEditor({ content, language, focusLine }: CodeEditorProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const viewRef = useRef<EditorView | null>(null);

  useEffect(() => {
    if (!containerRef.current) return;

    viewRef.current?.destroy();

    const state = EditorState.create({
      doc: content,
      extensions: [
        lineNumbers(),
        foldGutter(),
        highlightActiveLine(),
        EditorState.readOnly.of(true),
        EditorView.editable.of(false),
        rpTheme,
        getLanguageExtension(language),
        EditorView.lineWrapping,
      ],
    });

    viewRef.current = new EditorView({
      state,
      parent: containerRef.current,
    });

    return () => {
      viewRef.current?.destroy();
      viewRef.current = null;
    };
  }, [content, language]);

  useEffect(() => {
    const view = viewRef.current;
    if (!view || !focusLine || focusLine < 1) {
      return;
    }

    const safeLine = Math.min(focusLine, view.state.doc.lines);
    const line = view.state.doc.line(safeLine);
    view.dispatch({
      selection: { anchor: line.from },
      effects: EditorView.scrollIntoView(line.from, { y: "center" }),
    });
    view.focus();
  }, [focusLine, content]);

  return <div ref={containerRef} className="h-full overflow-hidden cm-wrapper" />;
}
