"use client";

import React, { useEffect, useRef } from "react";
import { Editor } from "@tinymce/tinymce-react";

interface OptimizedEditorProps {
  initialData?: string;
  onChange?: (data: string) => void;
  height?: number;
  placeholder?: string;
  disabled?: boolean;
  readOnly?: any;
}

const OptimizedEditor: React.FC<OptimizedEditorProps> = ({
  initialData = "",
  onChange,
  height = 400,
  placeholder = "Start typing...",
  disabled = false,
  readOnly = false,
}) => {
  const editorRef = useRef<any>(null);

  const handleEditorChange = (content: string) => {
    if (onChange) {
      onChange(content);
    }
  };

  const handleInit = (evt: any, editor: any) => {
    editorRef.current = editor;
  };

  return (
    <Editor
      onInit={handleInit}
      initialValue={initialData}
      onEditorChange={handleEditorChange}
      disabled={disabled}
      init={{
        height,
        menubar: false,
        plugins: [
          "advlist",
          "autolink",
          "lists",
          "link",
          "image",
          "charmap",
          "preview",
          "anchor",
          "searchreplace",
          "visualblocks",
          "code",
          "fullscreen",
          "insertdatetime",
          "media",
          "table",
          "code",
          "help",
          "wordcount",
        ],
        toolbar:
          "undo redo | blocks | " +
          "bold italic forecolor | alignleft aligncenter " +
          "alignright alignjustify | bullist numlist outdent indent | " +
          "removeformat | table | code | help",
        content_style: `
          body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            font-size: 14px; 
            line-height: 1.6; 
            color: #333; 
          }
          .mce-content-body { 
            padding: 16px; 
            min-height: ${height - 32}px; 
          }
        `,
        placeholder,
        readonly: readOnly,
        branding: false,
        elementpath: false,
        resize: false,
        statusbar: false,
        // Performance optimizations
        cache_suffix: "?v=1.0",
        browser_spellcheck: false,
        gecko_spellcheck: false,
        // Auto-save feature
        auto_save: true,
        auto_save_interval: "30s",
        // Better mobile support
        mobile: {
          theme: "silver",
          plugins: ["lists", "autolink", "link", "image", "table"],
          toolbar: "bold italic | bullist numlist | link image",
        },
      }}
    />
  );
};

export default OptimizedEditor;
