'use client';
import React, { useEffect, useRef, useState } from 'react';
import type { Editor as ToastEditor } from '@toast-ui/react-editor';
import '@toast-ui/editor/dist/toastui-editor.css';
import { isSSR } from '@/utils/is';

interface EditorSectionProps {
  initialContent?: string;
  visible: boolean;
  onChange?: (content: string) => void;
}

// 创建一个 Viewer 组件用于服务端渲染
const EditorViewer: React.FC<{ content: string }> = ({ content }) => {
  const viewerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isSSR && viewerRef.current) {
      // 在客户端激活时，动态加载 Viewer 并渲染内容
      import('@toast-ui/editor/dist/toastui-editor-viewer').then((module) => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const { Viewer } = module;
        new Viewer({
          el: viewerRef.current!,
          initialValue: content || ''
        });
      }).catch((error) => {
        console.error('Failed to load Toast UI Viewer:', error);
      });
    }
  }, [content]);

  // 服务端直接渲染 HTML 内容
  return <div ref={viewerRef} dangerouslySetInnerHTML={{ __html: content || '' }} />;
};

export default function EditorSection({ initialContent, visible, onChange }: EditorSectionProps) {
  const [isClient, setIsClient] = useState(false);
  const [currentContent, setCurrentContent] = useState(initialContent || '');
  const editorRef = useRef<any>(null);
  const editorInstanceRef = useRef<ToastEditor | null>(null);

  useEffect(() => {
    if (!isSSR) {
      setIsClient(true);

      // 动态导入编辑器组件
      import('@toast-ui/react-editor').then((module) => {
        editorRef.current = module.Editor;
      }).catch((error) => {
        console.error('Failed to load Toast UI Editor:', error);
      });
    }
    
    // 更新当前内容当初始内容变化时
    setCurrentContent(initialContent || '');
  }, [initialContent, visible]);

  // 在服务端或组件未加载完成时，使用 Viewer 模式显示内容
  if (!isClient || !editorRef.current || !visible) {
    return (
      <div className="mt-8">
        <EditorViewer content={currentContent || ''} />
      </div>
    );
  }

  const DynamicEditor = editorRef.current;

  return (
    <div className="mt-8">
      <DynamicEditor
        key={visible ? 'editor-visible' : 'editor-hidden'} // 强制重新创建组件
        initialValue={currentContent}
        initialEditType="markdown"
        onChange={() => {
          // 获取编辑器实例并读取内容
          const editorInstance = editorRef.current?.getInstance?.();
          if (editorInstance && onChange) {
            const content = editorInstance.getMarkdown();
            setCurrentContent(content);
            onChange(content);
          }
        }}
      />
    </div>
  );
}