'use client';

import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { detectTextDirection } from '@/lib/utils/text-direction';
import { sanitizeHtml } from '@/lib/utils/dom-sanitizer';

interface RichTextEditorProps {
  /** Initial HTML content */
  initialContent?: string;
  
  /** Callback when content changes */
  onChange?: (html: string) => void;
  
  /** Additional CSS class names */
  className?: string;
  
  /** Editor placeholder text */
  placeholder?: string;
  
  /** Whether the editor is read-only */
  readOnly?: boolean;
  
  /** Minimum height of the editor */
  minHeight?: string;
  
  /** Initial text direction */
  initialDirection?: 'ltr' | 'rtl';
}

/**
 * Unified rich text editor component with proper RTL support
 * Handles email composition with appropriate text direction detection
 */
const RichTextEditor = forwardRef<HTMLDivElement, RichTextEditorProps>(({
  initialContent = '',
  onChange,
  className = '',
  placeholder = 'Write your message...',
  readOnly = false,
  minHeight = '200px',
  initialDirection
}, ref) => {
  const internalEditorRef = useRef<HTMLDivElement>(null);
  const [direction, setDirection] = useState<'ltr' | 'rtl'>(
    initialDirection || detectTextDirection(initialContent)
  );
  
  // Forward the ref to parent components
  useImperativeHandle(ref, () => internalEditorRef.current as HTMLDivElement);
  
  // Initialize editor with clean content
  useEffect(() => {
    if (internalEditorRef.current) {
      // Clean the initial content
      const cleanContent = sanitizeHtml(initialContent);
      internalEditorRef.current.innerHTML = cleanContent;
      
      // Set initial direction
      internalEditorRef.current.setAttribute('dir', direction);
      
      // Focus editor if not read-only
      if (!readOnly) {
        setTimeout(() => {
          internalEditorRef.current?.focus();
        }, 100);
      }
    }
  }, [initialContent, direction, readOnly]);
  
  // Handle content changes and detect direction changes
  const handleInput = (e: React.FormEvent<HTMLDivElement>) => {
    if (onChange && e.currentTarget.innerHTML !== initialContent) {
      onChange(e.currentTarget.innerHTML);
    }
    
    // Re-detect direction on significant content changes
    // Only do this when the content length has changed significantly
    const newContent = e.currentTarget.innerText;
    if (newContent.length > 5 && newContent.length % 10 === 0) {
      const newDirection = detectTextDirection(newContent);
      if (newDirection !== direction) {
        setDirection(newDirection);
        e.currentTarget.setAttribute('dir', newDirection);
      }
    }
  };
  
  // Toggle direction manually
  const toggleDirection = () => {
    const newDirection = direction === 'ltr' ? 'rtl' : 'ltr';
    setDirection(newDirection);
    if (internalEditorRef.current) {
      internalEditorRef.current.setAttribute('dir', newDirection);
    }
  };
  
  return (
    <div className="rich-text-editor-container">
      {!readOnly && (
        <div className="editor-toolbar border-b p-1 flex items-center space-x-1">
          <button
            type="button"
            onClick={toggleDirection}
            className="px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded"
            title={`Switch to ${direction === 'ltr' ? 'right-to-left' : 'left-to-right'} text`}
          >
            {direction === 'ltr' ? 'LTR → RTL' : 'RTL → LTR'}
          </button>
        </div>
      )}
      
      <div
        ref={internalEditorRef}
        contentEditable={!readOnly}
        className={`rich-text-editor outline-none p-3 ${className}`}
        onInput={handleInput}
        dir={direction}
        style={{
          minHeight,
          cursor: readOnly ? 'default' : 'text',
        }}
        data-placeholder={placeholder}
        suppressContentEditableWarning
      />
      
      <style jsx>{`
        .rich-text-editor {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
          font-size: 14px;
          line-height: 1.6;
          overflow-wrap: break-word;
          word-break: break-word;
          white-space: pre-wrap;
        }
        
        .rich-text-editor:empty:before {
          content: attr(data-placeholder);
          color: #aaa;
          pointer-events: none;
        }
        
        .rich-text-editor[dir="rtl"] {
          text-align: right;
        }
        
        .rich-text-editor blockquote {
          margin: 10px 0;
          padding-left: 15px;
          border-left: 2px solid #ddd;
          color: #666;
        }
        
        .rich-text-editor[dir="rtl"] blockquote {
          padding-left: 0;
          padding-right: 15px;
          border-left: none;
          border-right: 2px solid #ddd;
        }
        
        .rich-text-editor img {
          max-width: 100%;
          height: auto;
        }
      `}</style>
    </div>
  );
});

RichTextEditor.displayName = 'RichTextEditor';

export default RichTextEditor; 