import { Editor } from '@tinymce/tinymce-react';
import { message } from 'antd';
import React, { useCallback, useState } from 'react';
import type { Editor as TinyMCEEditor } from 'tinymce';
import { uploadImage } from '@/services/infra/media';
export interface RichEditorProps {
  value?: string;
  onChange?: (content: string) => void;
  height?: number;
  placeholder?: string;
  disabled?: boolean;
  uploadConfig?: {
    action: string;
    headers?: Record<string, string>;
    maxSize?: number;
    acceptTypes?: string[];
    data?: Record<string, any>;
  };
  showWordCount?: boolean;
  maxWords?: number;
}

console.log(VITE_BASE_URL);
const RichEditor: React.FC<RichEditorProps> = ({
  value = '',
  onChange,
  // height = 400,
  // placeholder = "请输入内容...",
  disabled = false,
  // showWordCount = true,
  // maxWords,
  uploadConfig = {
    maxSize: 5,
    acceptTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
  },
}) => {
  const [uploading, setUploading] = useState<boolean>(false);
  const uploadFile = useCallback(
    async (file: File): Promise<string> => {
      return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append('file', file);
        try {
          uploadImage(formData).then((res) => {
            if (res) {
              resolve(res);
            } else {
              reject(new Error('上传失败：未返回有效的URL'));
            }
          });
        } catch (error) {
          reject(error);
        }
      });
    },
    [uploadConfig],
  );
  const handleImageUpload = useCallback(
    (blobInfo: any, _: (percent: number) => void): Promise<string> => {
      return new Promise((resolve, reject) => {
        try {
          setUploading(true);
          const file = blobInfo.blob();
          uploadFile(file).then((url) => {
            resolve(url);
          });

          message.success('图片上传成功');
        } catch (error) {
          reject(error);
          message.error(typeof error === 'string' ? error : '上传失败');
        } finally {
          setUploading(false);
        }
      });
    },
    [uploadFile],
  );

  const handleCustomUpload = useCallback(
    (editor: TinyMCEEditor) => {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = uploadConfig.acceptTypes?.join(',') || 'image/*';
      input.multiple = true;

      const handleFileChange = async (event: Event) => {
        const target = event.target as HTMLInputElement;
        const files = Array.from(target.files || []);

        if (files.length === 0) return;

        setUploading(true);

        try {
          for (const file of files) {
            const isValidType = uploadConfig.acceptTypes?.includes(file.type);
            if (!isValidType) {
              message.error(`文件 ${file.name} 类型不支持`);
              continue;
            }

            const isValidSize =
              file.size / 1024 / 1024 < (uploadConfig.maxSize || 5);
            if (!isValidSize) {
              message.error(
                `文件 ${file.name} 大小超过 ${uploadConfig.maxSize || 5}MB`,
              );
              continue;
            }

            try {
              const url = await uploadFile(file);
              const imgHtml = `<img src="${url}" alt="${file.name}" style="max-width: 100%; height: auto;" />`;
              editor.insertContent(imgHtml);
              message.success(`${file.name} 上传成功`);
            } catch (error) {
              message.error(`${file.name} 上传失败: ${error}`);
            }
          }
        } finally {
          setUploading(false);
        }
      };

      input.addEventListener('change', handleFileChange);
      input.click();
    },
    [uploadConfig, uploadFile],
  );

  const handleEditorChange = (content: string) => {
    onChange?.(content);
  };
  return (
    <Editor
      // apiKey="xt51qhzvj8q9mxzxytigtp0nu94v4rz7dska2dbqeilkxo99"
      value={value}
      onEditorChange={handleEditorChange}
      api-key="no-api-key"
      licenseKey="gpl"
      tinymceScriptSrc="/tinymce/tinymce.min.js"
      init={{
        plugins: [
          // Core editing features
          'anchor',
          'autolink',
          'charmap',
          'codesample',
          'emoticons',
          'link',
          'lists',
          'media',
          'searchreplace',
          'table',
          'visualblocks',
          'wordcount',
          // Your account includes a free trial of TinyMCE premium features
          // Try the most popular premium features until Oct 8, 2025:
          // "checklist",
          // "mediaembed",
          // "casechange",
          // "formatpainter",
          // "pageembed",
          // "a11ychecker",
          // "tinymcespellchecker",
          // "permanentpen",
          // "powerpaste",
          // "advtable",
          // "advcode",
          // "advtemplate",
          // "ai",
          // "uploadcare",
          // "mentions",
          // "tinycomments",
          // "tableofcontents",
          // "footnotes",
          // "mergetags",
          // "autocorrect",
          // "typography",
          // "inlinecss",
          // "markdown",
          // "importword",
          // "exportword",
          // "exportpdf",
        ],

        menubar: false,
        toolbar:
          'undo redo | blocks | bold italic forecolor ' +
          'alignleft aligncenter | ' +
          'alignright alignjustify | bullist numlist outdent indent customupload | ' +
          'removeformat ',
        tinycomments_mode: 'embedded',
        tinycomments_author: 'Author name',
        toolbar_mode: 'wrap' as const, // 改为 wrap 模式，全部展开
        // toolbar_mode: "sliding",
        mergetags_list: [
          { value: 'First.Name', title: 'First Name' },
          { value: 'Email', title: 'Email' },
        ],
        ai_request: (
          _: any,
          respondWith: { string: (arg0: () => Promise<never>) => any },
        ) =>
          respondWith.string(() =>
            Promise.reject('See docs to implement AI Assistant'),
          ),
        language: 'zh_CN',
        // 其他配置
        table_class_list: [
          { title: '无样式', value: '' },
          { title: '简单表格', value: 'simple-table' },
          { title: '条纹表格', value: 'striped-table' },
          { title: '边框表格', value: 'bordered-table' },
        ],
        convert_urls: false,
        remove_script_host: false,
        uploadcare_public_key: '0ad3671d77f59c5756dd',
        setup: (editor: TinyMCEEditor) => {
          // 注册自定义上传按钮
          editor.ui.registry.addButton('customupload', {
            text: uploading ? '上传中...' : '上传',
            icon: 'upload',
            tooltip: '上传图片（支持多选）',
            enabled: !disabled && !uploading,
            onAction: () => {
              handleCustomUpload(editor);
            },
          });
        },
        // 图片上传配置
        images_upload_handler: handleImageUpload,
        // 性能配置
        browser_spellcheck: true,
        contextmenu: 'link image table',
        promotion: false,
        branding: false, // 去除品牌标识
      }}

      // onBlur={() =>onChange()}
    />
  );
};

export default React.memo(RichEditor);
