/* global wp, tinymce */
import { useEffect, useRef } from '@wordpress/element';
import { Button, Modal } from '@wordpress/components';

const TinyMCEEditor = ({ id, value, onChange, onClose }) => {
  const container = useRef();

  useEffect(() => {
    if (!wp?.editor?.initialize) return;

    const textarea = document.createElement('textarea');
    textarea.id = id;
    textarea.value = value || '';
    container.current.appendChild(textarea);

    wp.editor.initialize(id, {
      tinymce: {
        wpautop: true,
        toolbar1:
          'formatselect bold italic underline bullist numlist blockquote alignleft aligncenter alignright link unlink | pastetext removeformat charmap outdent indent undo redo',
        setup: (editor) => {
          editor.on('change keyup', () => onChange(editor.getContent()));
        },
      },
      quicktags: true,
      mediaButtons: true,
    });

    return () => {
      if (wp.editor.remove) wp.editor.remove(id);
      if (container.current) container.current.innerHTML = '';
    };
  }, []);

  return (
    <Modal
      title="Edit Content"
      onRequestClose={onClose}
      className="leadgen-tinymce-modal"
    >
      <div ref={container}></div>
      <div style={{ marginTop: '1rem', textAlign: 'right' }}>
        <Button variant="primary" onClick={onClose}>
          Done
        </Button>
      </div>
    </Modal>
  );
};

export default TinyMCEEditor;
