"use client"

import React, { useEffect, useRef } from "react"
import { CKEditor } from "@ckeditor/ckeditor5-react"
import {
  ClassicEditor,
  Essentials,
  Underline,
  Bold,
  Heading,
  Indent,
  IndentBlock,
  Italic,
  Link,
  List,
  MediaEmbed,
  Paragraph,
  Table,
  Undo,
  Font,
  FontColor,
  FontSize,
  FontBackgroundColor,
  BlockQuote,
  SimpleUploadAdapter,
  ImageUpload,
  Image,
  AutoImage,
  ImageCaption,
  ImageResize,
  ImageStyle,
  ImageToolbar,
  ImageInsert,
  LinkImage,
  CodeBlock,
  SourceEditing,
  Strikethrough,
  Alignment,
  TodoList,
} from "ckeditor5"
import { UploadAdapter, FileLoader } from "@ckeditor/ckeditor5-upload/src/filerepository"
import "ckeditor5/ckeditor5.css"
import { useUploadImage } from "@/hook/useMedia"

type Props = {
  disabled?: boolean
  value?: any
  onChange?: (value: any) => void
  onBlur?: (e: any) => void
  onFocus?: (e: any) => void
}

export default function CustomEditor({ disabled, value, onChange, onBlur, onFocus }: Props) {
  const uploadImage = useUploadImage()
  const editorRef = useRef(null)

  const handleEditorChange = (_: any, editor: any) => {
    const data = editor.getData()
    onChange && onChange(data)
  }

  const handleEditorBlur = (e: any) => {
    onBlur && onBlur(e)
  }

  const handleEditorFocus = (e: any) => {
    onFocus && onFocus(e)
  }

  function uploadAdapter(loader: FileLoader): UploadAdapter {
    return {
      upload: () => {
        return loader.file.then(
          (file) =>
            new Promise((resolve, reject) => {
              if (file) {
                uploadImage
                  .mutateAsync({ image: file })
                  .then((res: any) => {
                    console.log("res", res?.data?.data.url)
                    if (res?.data?.success) {
                      resolve({
                        default: res?.data.data.url,
                      })
                    } else {
                      reject(res?.data?.msg)
                    }
                  })
                  .catch(() => {
                    reject("Error uploading image.")
                  })
              } else {
                reject("Error uploading image.")
              }
            }),
        )
      },
      abort: () => {
        console.log("Upload canceled")
      },
    }
  }

  return (
    <CKEditor
      ref={editorRef}
      editor={ClassicEditor}
      // disabled={disabled}
      // data={value}
      config={{
        licenseKey: "GPL",
        initialData: value || "",
        plugins: [
          Underline,
          Bold,
          Essentials,
          Heading,
          Indent,
          IndentBlock,
          Italic,
          Link,
          List,
          MediaEmbed,
          Paragraph,
          Table,
          Undo,
          Font,
          FontColor,
          FontSize,
          FontBackgroundColor,
          BlockQuote,
          SimpleUploadAdapter,
          ImageUpload,
          Image,
          AutoImage,
          ImageCaption,
          ImageResize,
          ImageStyle,
          ImageToolbar,
          ImageInsert,
          LinkImage,
          CodeBlock,
          SourceEditing,
          Strikethrough,
          Alignment,
          TodoList,
        ],
        toolbar: [
          "undo",
          "redo",
          "|",
          "heading",
          "|",
          "bold",
          "italic",
          "underline",
          "strikethrough",
          "|",
          "fontColor",
          "fontBackgroundColor",
          "fontSize",
          "fontFamily",
          "|",
          "insertImage",
          "mediaEmbed",
          "insertTable",
          "link",
          "|",
          "alignment",
          "bulletedList",
          "numberedList",
          "todoList",
          "indent",
          "outdent",
          "blockQuote",
          "|",
          "codeBlock",
          "sourceEditing",
        ],
        fontSize: {
          options: [9, 11, 12, 13, "default", 15, 16, 17, 18, 19, 20, 25, 30],
          supportAllValues: true,
        },
        image: {
          toolbar: ["toggleImageCaption", "imageTextAlternative", "ckboxImageEdit", "linkImage"],
          upload: {
            types: ["jpeg", "png", "gif", "bmp", "webp", "tiff"],
          },
        },
      }}
      onReady={(editor) => {
        // Set the editor's read-only state when it's ready
        // editor.isReadOnly = disabled || false
        if (disabled) {
          editor.enableReadOnlyMode(`id-${Date.now()}-${Math.random().toString(36)}`)
        } else {
          editor.disableReadOnlyMode(`id-${Date.now()}-${Math.random().toString(36)}`)
        }
        editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {
          return uploadAdapter(loader)
        }
      }}
      onChange={handleEditorChange}
      onBlur={handleEditorBlur}
      onFocus={handleEditorFocus}
    />
  )
}
