import { createEditor } from '@kevisual/codemirror';
import { Chain } from '@kevisual/codemirror/utils';
import { useEffect, useRef } from 'react';
import { CacheWorkspace } from '@kevisual/cache';

export const chain = new Chain();
type TextEditorProps = {
  content: string;
  chain?: Chain;
  onChange?: (content: string) => void;
};
export const TextEditor = ({ content, chain, onChange }: TextEditorProps) => {
  const editorElRef = useRef<HTMLDivElement>(null);
  const editorRef = useRef<ReturnType<typeof createEditor>>(null);
  useEffect(() => {
    initEditor();
    return () => {
      if (editorRef.current) {
        chain?.destroy?.();
      }
    };
  }, []);
  useEffect(() => {
    if (editorRef.current) {
      chain?.setContent?.(content);
    }
  }, [content]);
  const initEditor = async () => {
    if (!editorElRef.current) return;
    const cache = new CacheWorkspace();
    const editor = createEditor(editorElRef.current, {
      type: 'html',
      onChange: (value) => {
        cache.set('editor-content-home', value);
        onChange?.(value);
      },
    });

    const value = await cache.get('editor-content-home');
    const cmScroller = editorElRef.current.querySelector('.cm-scroller');
    if (cmScroller) {
      cmScroller.classList.add('scrollbar');
    }
    chain?.setEditor?.(editor);
    editorRef.current = editor;
    if (value) {
      chain?.setContent?.(value);
    }
  };
  return <div className='h-full overflow-hidden' ref={editorElRef}></div>;
};
