import React, { useEffect } from 'react'
import FroalaEditor from 'react-froala-wysiwyg'

import 'froala-editor/js/languages/zh_cn'

import 'froala-editor/css/froala_style.min.css'
import 'froala-editor/css/froala_editor.pkgd.min.css'
//image
import 'froala-editor/js/plugins/image.min.js'
import 'froala-editor/css/plugins/image.min.css'
//image_tui
import 'froala-editor/js/third_party/image_tui.min.js'
import 'froala-editor/css/third_party/image_tui.min.css'
//file
import 'froala-editor/js/plugins/file.min.js'
import 'froala-editor/css/plugins/file.min.css'
//code_view
import 'froala-editor/js/plugins/code_view.min.js'
//lists
import 'froala-editor/js/plugins/lists.min.js'
//font_family
import 'froala-editor/js/plugins/font_family.min.js'
//font_size
import 'froala-editor/js/plugins/font_size.min.js'
//quote
import 'froala-editor/js/plugins/quote.min.js'
//inline_class
import 'froala-editor/js/plugins/inline_class.min.js'
//inline_style
import 'froala-editor/js/plugins/inline_style.min.js'
//line_height
import 'froala-editor/js/plugins/line_height.min.js'
//paragraph_format
import 'froala-editor/js/plugins/paragraph_format.min.js'
//paragraph_style
import 'froala-editor/js/plugins/paragraph_style.min.js'
//colors
import 'froala-editor/js/plugins/colors.min.js'
import 'froala-editor/css/plugins/colors.min.css'
//align
import 'froala-editor/js/plugins/align.min.js'
//emoticons
import 'froala-editor/js/plugins/emoticons.min.js'
import 'froala-editor/css/plugins/emoticons.min.css'
//special_characters
import 'froala-editor/js/plugins/special_characters.min.js'
import 'froala-editor/css/plugins/special_characters.min.css'
//link
import 'froala-editor/js/plugins/link.min.js'
// video
import 'froala-editor/js/plugins/video.min.js'
import 'froala-editor/css/plugins/video.min.css'
//table
import 'froala-editor/js/plugins/table.min.js'
import 'froala-editor/css/plugins/table.min.css'

import { htmlAllowedTags, htmlAllowedAttrs } from 'utils/froalaExtraOptions'

type FroalaWrapperProps = {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  handleUpstream?: (value: any) => void
  value?: string
  onChange?: (value: string) => void
  configType?: 'article' | 'note' | 'column'
}

const FroalaWrapper: React.FC<FroalaWrapperProps> = ({
  value,
  onChange,
  handleUpstream,
  configType = 'column'
}: FroalaWrapperProps) => {
  const config = {
    column: {
      key: '3AC6eC4F5G4A3D3A2B3B-16pfwg1gukaC7xiakldI1qA-16yiG5G4E3H3A1C8A6D4A3D3==',
      language: 'zh_cn',
      placeholderText: '请输入正文',
      heightMin: 460,
      fileMaxSize: 1024 * 1024 * 20,
      imageUpload: true,
      imageUploadMethod: 'POST',
      imageUploadParam: 'file',
      requestHeaders: {
        Authorization: `${localStorage.getItem('smtoken')}`
      },
      imageUploadURL: `${process.env.REACT_APP_API_NEW}/resource/image/upload`,
      imageEditButtonss: [
        'imageReplace',
        'imageAlign',
        'imageCaption',
        'imageRemove',
        '|',
        'imageLink',
        'linkOpen',
        'linkEdit',
        'linkRemove',
        '-',
        'imageDisplay',
        'imageStyle',
        'imageAlt',
        'imageSize'
      ],
      // iconsTemplate: 'font_awesome_5',
      toolbarSticky: true,
      quickInsertButtons: [],
      quickInsertTags: [],
      charCounterCount: false,
      paragraphFormatSelection: true,
      fontFamilySelection: true,
      fontSizeSelection: true,
      toolbarStickyOffset: 10,
      attribution: false,
      toolbarButtons: ['bold', 'italic', 'underline', 'textColor', 'align', 'insertHR', 'undo', 'redo', 'insertImage'],
      events: {
        'image.uploaded': (res: string) => {
          const json = JSON.parse(res)
          if (json.Success) {
            editorInstance.selection.restore()
            const uploadingImages = editorInstance.image.get('uploading')
            if (uploadingImages.length > 0) {
              editorInstance.image.remove(uploadingImages)
            }
            editorInstance.html.insert(
              `<img
                src=${json.Data.ResourceUrl}
                alt="图片"
              />`,
              false
            )
            onChange && onChange(editorInstance.html.get())
          }
        },
        blur: () => {
          editorInstance.selection.save()
        },
        focus: () => {
          editorInstance.selection.restore()
        }
      }
    },
    note: {
      key: '3AC6eC4F5G4A3D3A2B3B-16pfwg1gukaC7xiakldI1qA-16yiG5G4E3H3A1C8A6D4A3D3==',
      language: 'zh_cn',
      placeholderText: '笔记编辑',
      toolbarSticky: false,
      quickInsertButtons: [],
      quickInsertTags: [],
      charCounterCount: false,
      paragraphFormatSelection: true,
      fontFamilySelection: true,
      fontSizeSelection: true,
      attribution: false,
      toolbarButtons: [
        'bold',
        'italic',
        'underline',
        'fontSize',
        'textColor',
        'formatOL',
        'formatUL',
        'fontAwesome',
        'specialCharacters',
        'insertHR',
        'selectAll',
        'clearFormatting',
        'html',
        'undo',
        'redo',
        'insertImage'
      ],
      imageUpload: true,
      imageUploadMethod: 'POST',
      imageUploadParam: 'file',
      imageUploadURL: `${document.location.origin}/service/vmp_api_upload/api/img/uuid`,
      imageEditButtonss: [
        'imageReplace',
        'imageAlign',
        'imageCaption',
        'imageRemove',
        '|',
        'imageLink',
        'linkOpen',
        'linkEdit',
        'linkRemove',
        '-',
        'imageDisplay',
        'imageStyle',
        'imageAlt',
        'imageSize'
      ],
      events: {
        blur: () => {
          editorInstance.selection.save()
        },
        focus: () => {
          editorInstance.selection.restore()
        }
      },
      ...htmlAllowedTags,
      ...htmlAllowedAttrs
    },
    article: {
      key: '3AC6eC4F5G4A3D3A2B3B-16pfwg1gukaC7xiakldI1qA-16yiG5G4E3H3A1C8A6D4A3D3==',
      // zIndex: 99999,
      language: 'zh_cn',
      placeholderText: '文章正文编辑',
      heightMin: 200,
      fileMaxSize: 1024 * 1024 * 20,
      imageUpload: true,
      imageUploadMethod: 'POST',
      imageUploadParam: 'file',
      imageUploadURL: `${document.location.origin}/service/vmp_api_upload/api/img/uuid`,
      imageEditButtonss: [
        'imageReplace',
        'imageAlign',
        'imageCaption',
        'imageRemove',
        '|',
        'imageLink',
        'linkOpen',
        'linkEdit',
        'linkRemove',
        '-',
        'imageDisplay',
        'imageStyle',
        'imageAlt',
        'imageSize'
      ],
      videoUpload: true,
      videoUploadMethod: 'POST',
      videoUploadParams: { oss_path: 'qac/video' },
      // videoUploadURL: `${document.location.origin}/service/vmp_api_upload/api/upload`,
      videoUploadURL: `https://release.internal.hzinsights.com/service/vmp_api_upload/api/upload`,
      // 默认宽度 值为数值类型 单位为px 设为0时，不设置任何宽度
      videoDefaultWidth: 0,
      // 视频大小
      videoMaxSize: 1024 * 1024 * 200,
      // 选中视频弹窗按钮
      videoEditButtons: ['videoReplace', 'videoRemove', 'videoDisplay', 'videoAlign', 'videoSize'], // autoPlay导致视频报错
      // 插入视频弹窗按钮
      // 通过 URL 或任何来源的嵌入代码轻松插入视频，并自动解析 Youtube、Vimeo、Yahoo 和 DailyMotion 视频链接
      videoInsertButtons: ['videoUpload', 'videoEmbed', 'videoByURL'],
      // 视频供应商
      videoAllowedProviders: ['.*'],
      //iconsTemplate: 'font_awesome_5',
      toolbarSticky: true,
      quickInsertButtons: [],
      quickInsertTags: [],
      charCounterCount: false,
      paragraphFormatSelection: true,
      fontFamilySelection: true,
      fontSizeSelection: true,
      toolbarStickyOffset: 10,
      attribution: false,
      fileUploadURL: `${document.location.origin}/service/vmp_api_upload/api/upload`,
      fileUploadParams: {
        oss_path: 'article/pdf'
      },
      fileUploadMethod: 'POST',
      toolbarButtons: [
        'bold',
        'italic',
        'underline',
        'strikeThrough',
        'subscript',
        'superscript',
        'fontFamily',
        'fontSize',
        'textColor',
        'inlineClass',
        'inlineStyle',
        'paragraphStyle',
        'lineHeight',
        '|',
        'paragraphFormat',
        'align',
        'formatOL',
        'formatUL',
        'outdent',
        'indent',
        'quote',
        '|',
        'emoticons',
        'fontAwesome',
        'specialCharacters',
        'insertHR',
        'selectAll',
        'clearFormatting',
        '|',
        'html',
        '|',
        'undo',
        'redo',
        'insertFile',
        'insertImage',
        'insertLink',
        'insertVideo',
        'insertTable',
        'getPDF'
      ],
      events: {
        blur: () => {
          editorInstance.selection.save()
        },
        focus: () => {
          editorInstance.selection.restore()
        },
        'video.linkError': (link: any) => {
          editorInstance.html.insert(
            `<span class="fr-video fr-deletable fr-fvc fr-dvb fr-draggable" contenteditable="false" draggable="true"><iframe width="100%" height="400px" src="${link}" frameborder="0" allowfullscreen="" class="fr-draggable"></iframe></span>`,
            false
          )
        }
      },
      ...htmlAllowedTags,
      ...htmlAllowedAttrs
    }
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any

  let editorInstance: any

  const [editorModel, setEditorState] = React.useState(value)

  useEffect(() => {
    setEditorState(value)
  }, [value])

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleChange = (editorState: any) => {
    setEditorState(editorState)
    if (onChange) {
      onChange(editorState)
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleInit = (initControls: any) => {
    initControls.initialize()
    editorInstance = initControls.getEditor()
    if (handleUpstream) {
      handleUpstream(editorInstance)
    }
  }
  return (
    <FroalaEditor
      tag={'textarea'}
      config={config[configType]}
      model={editorModel}
      onManualControllerReady={handleInit}
      onModelChange={handleChange}
    />
  )
}

export default FroalaWrapper
