import React, { useEffect } from "react";
import Editor from "react-simple-code-editor";
import { highlightCode, loadLanguage } from "../utils/language";

interface CodeEditorProps {
  value: string;
  onChange: (value: string) => void;
  language: string;
  readOnly?: boolean;
}

export const CodeEditor: React.FC<CodeEditorProps> = ({
  value,
  onChange,
  language,
  readOnly = false,
}) => {
  useEffect(() => {
    const highlight = async () => {
      await loadLanguage(language);
    };
    void highlight();
  }, [language]);

  const hightlightWithLineNumbers = (input: string) =>
    input
      .split("\n")
      .map(
        (line, i) =>
          `<div class="editor-line"><span class="editor-line-number">${
            i + 1
          }</span><span class="editor-line-content">${highlightCode(
            line || " ",
            language
          )}</span></div>`
      )
      .join("");

  return (
    <div className="code-editor">
      <Editor
        value={value}
        onValueChange={onChange}
        highlight={hightlightWithLineNumbers}
        padding={0}
        className="editor-textarea"
        textareaClassName="editor-textarea-input"
        readOnly={readOnly}
        style={{
          fontFamily: '"Fira Code", "Monaco", "Courier New", monospace',
          fontSize: 14,
        }}
      />
    </div>
  );
};
