import React, { useState, useRef, useEffect } from "react";
import { __ } from "@wordpress/i18n";
import { HelpCircle } from "lucide-react";

/**
 * Add Note Form Component
 *
 * Form for adding new subscription notes with TinyMCE editor.
 *
 * @param {Object} props Component props
 * @param {Function} props.onAdd Handler for adding notes
 * @param {boolean} props.loading Loading state
 */
const AddNoteForm = ({ onAdd, loading }) => {
  const [content, setContent] = useState("");
  const [type, setType] = useState("private");
  const editorRef = useRef(null);
  const editorIdRef = useRef(`subscription-note-editor-${Date.now()}`);
  const editorId = editorIdRef.current;
  const [editorReady, setEditorReady] = useState(false);

  /**
   * Initialize TinyMCE editor
   */
  useEffect(() => {
    // Check if TinyMCE is available (loaded by WordPress)
    if (typeof window.tinymce !== "undefined") {
      // Small delay to ensure DOM is ready
      const timer = setTimeout(() => {
        initTinyMCE();
      }, 100);

      return () => {
        clearTimeout(timer);
        destroyTinyMCE();
      };
    }
  }, []);

  const initTinyMCE = () => {
    if (window.tinymce.get(editorId)) {
      return;
    }

    window.tinymce.init({
      selector: `#${editorId}`,
      menubar: false,
      statusbar: false,
      toolbar: "bold italic underline | link | bullist numlist",
      plugins: "lists link",
      height: 120,
      content_style: `
                body {
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                    font-size: 13px;
                    line-height: 1.5;
                    padding: 8px;
                    margin: 0;
                }
                p { margin: 0 0 8px 0; }
                p:last-child { margin-bottom: 0; }
                a { color: #2271b1; }
            `,
      setup: (editor) => {
        editorRef.current = editor;

        editor.on("init", () => {
          setEditorReady(true);
        });

        editor.on("change keyup", () => {
          setContent(editor.getContent());
        });
      },
    });
  };

  const destroyTinyMCE = () => {
    if (editorRef.current) {
      try {
        window.tinymce.remove(`#${editorId}`);
      } catch (e) {
        // Ignore errors during cleanup
      }
      editorRef.current = null;
    }
  };

  /**
   * Handle form submission
   */
  const handleSubmit = async (e) => {
    e.preventDefault();

    const editorContent = editorRef.current
      ? editorRef.current.getContent()
      : content;

    if (!editorContent || !editorContent.trim()) {
      return;
    }

    const success = await onAdd({ content: editorContent, type });

    if (success) {
      // Clear editor
      if (editorRef.current) {
        editorRef.current.setContent("");
      }
      setContent("");
    }
  };

  /**
   * Handle textarea change (fallback when TinyMCE not available)
   */
  const handleTextareaChange = (e) => {
    setContent(e.target.value);
  };

  return (
    <form className="arraysubs-add-note-form" onSubmit={handleSubmit}>
      <div className="arraysubs-add-note-form__header">
        <label className="arraysubs-add-note-form__label" htmlFor={editorId}>
          {__("Add note", "arraysubs")}
        </label>
        <span
          className="arraysubs-add-note-form__help"
          title={__(
            "You can use basic formatting (bold, italic, links) and URLs will be automatically linked.",
            "arraysubs",
          )}
        >
          <HelpCircle size={14} />
        </span>
      </div>

      <div className="arraysubs-add-note-form__editor-wrapper">
        <textarea
          id={editorId}
          className="arraysubs-add-note-form__editor"
          value={content}
          onChange={handleTextareaChange}
          placeholder={__("Enter note content...", "arraysubs")}
          rows={4}
        />
      </div>

      <div className="arraysubs-add-note-form__actions">
        <select
          className="arraysubs-add-note-form__type"
          value={type}
          onChange={(e) => setType(e.target.value)}
        >
          <option value="private">{__("Private note", "arraysubs")}</option>
          <option value="customer">
            {__("Note to customer", "arraysubs")}
          </option>
        </select>

        <button
          type="submit"
          className="button button-primary"
          disabled={loading || (!editorReady && !content.trim())}
        >
          {loading ? __("Adding...", "arraysubs") : __("Add", "arraysubs")}
        </button>
      </div>
    </form>
  );
};

export default AddNoteForm;
