import { useEffect, useRef, useState } from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { TextAreaProps } from "@app/models/components";
import "./textArea-styles.scss";

const TextArea: React.FC<TextAreaProps> = ({
  field,
  onChange,
  onBlur,
  onFocus,
  isUpdated,
  setIsUpdated,
  isEditing,
  setIsEditing,
  isLoading,
  isDefaultDescription,
}) => {
  const editorRef = useRef<ReactQuill | null>(null);
  const [content, setContent] = useState(field.value);

  const modules = {
    toolbar: [
      ["bold", "italic", "underline", "strike"],
      ["blockquote"],
      ["link"],
      [{ list: "ordered" }, { list: "bullet" }, { list: "check" }],
      [{ size: ["small", false, "large", "huge"] }],
      [{ color: [] }, { background: [] }],
      [{ align: [] }],
    ],
  };

  const handleContentChange = (newContent: string) => {
    setContent(newContent);
    onChange?.(field.name, newContent);
  };

  useEffect(() => {
    if (isEditing && editorRef.current) {
      editorRef.current.getEditor().focus();
    }
  }, [isEditing, isUpdated]);

  useEffect(() => {
    setContent(field.value);
  }, [field.value]);

  return (
    <div>
      {isEditing && !isUpdated && !isLoading ? (
        <div>
          <ReactQuill
            ref={editorRef}
            value={isDefaultDescription ? "" : content}
            onChange={handleContentChange}
            onFocus={() => {
              onFocus?.();
            }}
            className="rich-text-editor"
            theme="snow"
            modules={modules}
          />
        </div>
      ) : (
        <div
          className={`${
            isLoading ? "textarea-field-loading" : "textarea-field"
          }`}
          onClick={() => {
            setIsEditing?.(true);
            setIsUpdated?.(false);
          }}
          dangerouslySetInnerHTML={{ __html: content }}
        />
      )}
    </div>
  );
};

export default TextArea;
