import React, { useEffect, useMemo } from "react";
import PropTypes from "prop-types";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import { BalloonEditor, ClassicEditor, InlineEditor } from "ckeditor5";
import "ckeditor5/ckeditor5.css";

const EDITOR_TYPES = {
  classic: ClassicEditor,
  inline: InlineEditor,
  balloon: BalloonEditor,
};

const COLOR_LIST_BODY_CLASS = "ckstudio-colors-list";

let colorListMounts = 0;

const useColorListLayout = (enabled) => {
  useEffect(() => {
    if (!enabled) return undefined;

    colorListMounts += 1;
    document.body.classList.add(COLOR_LIST_BODY_CLASS);

    return () => {
      colorListMounts -= 1;
      if (colorListMounts === 0) document.body.classList.remove(COLOR_LIST_BODY_CLASS);
    };
  }, [enabled]);
};

const CKEReact = ({ preset, value, disabled, onChange, onEditorReady, onWordCountUpdate }) => {
  useColorListLayout(preset.colorLayout === "list");

  const editorConfig = useMemo(() => {
    if (!onWordCountUpdate) return preset.editorConfig;

    return {
      ...preset.editorConfig,
      wordCount: {
        ...preset.editorConfig.wordCount,
        onUpdate: onWordCountUpdate,
      },
    };
  }, [preset, onWordCountUpdate]);

  const handleChange = (event, editor) => onChange(editor.getData());

  const handleReady = (editor) => onEditorReady?.(editor);

  return (
    <CKEditor
      editor={EDITOR_TYPES[preset.editorType] ?? ClassicEditor}
      config={editorConfig}
      data={value}
      disabled={disabled}
      onChange={handleChange}
      onReady={handleReady}
    />
  );
};

CKEReact.propTypes = {
  preset: PropTypes.shape({
    name: PropTypes.string.isRequired,
    editorConfig: PropTypes.object.isRequired,
  }).isRequired,
  value: PropTypes.string,
  disabled: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  onEditorReady: PropTypes.func,
  onWordCountUpdate: PropTypes.func,
};

export default CKEReact;
