import React, { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

const RichTextEditor = ({ disabled = false, error, touched, ...rest }) => {
  const quillRef = useRef(null);
  const { i18n } = useTranslation();
  const dir = i18n.dir();
  const modules = {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
      ['link'],
      [{ color: [] }, { background: [] }],
      [{ align: [] }],
      [{ direction: 'rtl' }],
      ['clean'],
    ],
  };

  useEffect(() => {
    if (dir === 'ltr') {
      quillRef.current.format('direction', 'ltr');
      quillRef.current.format('align', 'left');
    } else {
      quillRef.current.format('direction', 'rtl');
      quillRef.current.format('align', 'right');
    }
  }, [dir]);

  const formats = [
    'header',
    'bold',
    'italic',
    'underline',
    'strike',
    'blockquote',
    'list',
    'bullet',
    'indent',
    'link',
    'clean',
    'align',
    'direction',
    'code-block',
    'font',
    'size',
    'color',
    'background',
  ];

  const setEditorRef = (ref) => {
    if (ref) {
      quillRef.current = ref.getEditor();
    }
  };

  return (
    <div className="rich-text-editor">
      <ReactQuill
        ref={setEditorRef}
        modules={modules}
        formats={formats}
        {...rest}
        readOnly={disabled}
        className={disabled ? 'input-disabled' : ''}
        style={{ border: error && touched ? '2px solid rgb(239 68 68)' : '', borderRadius: '5px' }}
      />
    </div>
  );
};

export default RichTextEditor;
