"use client";

import * as React from "react";
import CodeMirror from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { python } from "@codemirror/lang-python";
import { oneDark } from "@codemirror/theme-one-dark";
import { useTheme } from "next-themes";
import { cn } from "@/lib/utils";

/**
 * Code editor for the coding lab.
 *
 * Uses CodeMirror 6 (the `@codemirror/*` packages already in the tree). The
 * language extension is derived from the project's stored `language` column, so
 * Python projects get Python highlighting without a second component.
 *
 * `onChange` is debounced by the parent when it matters; here we forward every
 * change so the editor stays responsive.
 */
export function CodeEditor({
  value,
  onChange,
  language,
  readOnly = false,
  minHeight = "20rem",
  className,
  ariaLabel,
}: {
  value: string;
  onChange: (next: string) => void;
  language: "JAVASCRIPT" | "PYTHON" | "ROBOT";
  readOnly?: boolean;
  minHeight?: string;
  className?: string;
  ariaLabel?: string;
}) {
  const { resolvedTheme } = useTheme();
  const [mounted, setMounted] = React.useState(false);

  // next-themes resolves on the client; avoid a hydration mismatch on the theme.
  React.useEffect(() => setMounted(true), []);

  const extensions = React.useMemo(() => {
    if (language === "PYTHON") return [python()];
    // The ROBOT pseudo-language shares JavaScript's tokenizer closely enough
    // for readable highlighting (keywords, numbers, braces, comments).
    return [javascript({ jsx: false, typescript: false })];
  }, [language]);

  const isDark = mounted && resolvedTheme === "dark";

  return (
    <div
      className={cn(
        "overflow-hidden rounded-lg border border-line",
        readOnly && "opacity-90",
        className
      )}
    >
      <CodeMirror
        value={value}
        height={minHeight}
        theme={isDark ? oneDark : "light"}
        extensions={extensions}
        editable={!readOnly}
        readOnly={readOnly}
        basicSetup={{
          lineNumbers: true,
          highlightActiveLine: !readOnly,
          highlightActiveLineGutter: !readOnly,
          foldGutter: true,
          bracketMatching: true,
          closeBrackets: true,
          autocompletion: true,
          indentOnInput: true,
          tabSize: 2,
        }}
        onChange={onChange}
        aria-label={ariaLabel}
        className="text-sm [&_.cm-editor]:outline-none [&_.cm-scroller]:font-mono"
      />
    </div>
  );
}
