"use client";

import React, { createContext, useContext, useRef } from "react";
import "./styles/suneditor.min.css"; // Import Sun Editor's CSS File
import SunEditor from "suneditor-react";

const EditorContext = createContext();

/**
 * A generic input component with a label and a visible password toggle.
 * @type {React.FC<React.Attributes & {
 *   onChange?: React.ChangeEventHandler<HTMLTextAreaElement>;
 *   onKeyDown?: React.KeyboardEventHandler<HTMLTextAreaElement>;
 *   content: string;
 *   placeholder?: string;
 *   contentStyle?: string;
 *   callBackSave?: Function;
 * }>}
 */
const Editor = (props) => {
  const { setEditor } = useGetEditor();

  return (
    <SunEditor
      autoFocus={true}
      height="100%"
      width="100%"
      toggleFullScreen={true}
      setDefaultStyle={props.contentStyle}
      onImageUploadError={(err) => console.log(err)}
      onImageUpload={(file) => console.log({ file })}
      onChange={(content) =>
        props.onChange &&
        typeof props.onChange === "function" &&
        // execute
        props.onChange(content)
      }
      placeholder={props.placeholder || "Write something..."}
      setContents={props.content}
      onKeyDown={props.onKeyDown}
      setOptions={{
        imageUploadUrl: "/api/upload?type=mediapost",
        buttonList: [
          ["undo", "redo"],
          ["formatBlock"],
          [
            "bold",
            "underline",
            "italic",
            "strike",
            "subscript",
            "superscript",
            "fontColor",
          ],
          ["link", "table"],
          [
            "outdent",
            "indent",
            "align",
            "horizontalRule",
            "list",
            "lineHeight",
          ],
          ["fullScreen", "showBlocks", "codeView"],
        ],
        callBackSave: props.callBackSave,
      }}
      getSunEditorInstance={(suneditor) => setEditor(suneditor)}
    />
  );
};

export const EditorProvider = ({ children }) => {
  const editor = useRef(null);

  const setEditor = (editorInstance) => {
    editor.current = editorInstance;
  };

  return (
    <EditorContext.Provider value={{ editor, setEditor }}>
      {children}
    </EditorContext.Provider>
  );
};

export const useGetEditor = () => useContext(EditorContext);

export default Editor;
