import { useEffect, useRef, useState } from 'react';
import * as monaco from 'monaco-editor';

export const useMonaco = ({
  defaultValue = '',
  language = 'javascript',
  readOnly = false,
  automaticLayout = true,
  quickSuggestions = false
}) => {
  const [editor, setEditor] = useState(null);
  const containerRef = useRef(null);
  const [value, setValue] = useState(defaultValue);

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

    const instance = monaco.editor.create(containerRef.current, {
      value: defaultValue,
      language,
      automaticLayout,
      quickSuggestions,
      readOnly,
      minimap: {
        enabled: false
      },
      scrollBeyondLastLine: false,
      theme: 'vs-dark'
    });

    setEditor(instance);

    instance.onDidChangeModelContent(() => {
      setValue(instance.getValue());
    });

    const resizeHandler = () => {
      // Monaco editor sometimes needs a manual resize trigger
      instance.layout({
        width: 0,
        height: 0
      });
      instance.layout();
    };

    window.addEventListener('resize', resizeHandler);

    return () => {
      window.removeEventListener('resize', resizeHandler);
      instance.dispose();
    };
  }, [defaultValue, language, automaticLayout, quickSuggestions, readOnly]);

  // Sync external value changes
  useEffect(() => {
    if (editor && defaultValue !== value) {
      editor.setValue(defaultValue);
    }
  }, [defaultValue, editor]);

  return {
    editor,
    containerRef,
    value
  };
};

export default useMonaco;
