'use client';

import React, { useEffect, useRef, useState } from 'react';
import 'quill/dist/quill.snow.css';
import { sanitizeHtml } from '@/lib/utils/email-formatter';

interface RichEmailEditorProps {
  initialContent: string;
  onChange: (content: string) => void;
  placeholder?: string;
  minHeight?: string;
  maxHeight?: string;
}

const RichEmailEditor: React.FC<RichEmailEditorProps> = ({
  initialContent,
  onChange,
  placeholder = 'Write your message here...',
  minHeight = '200px',
  maxHeight = 'calc(100vh - 400px)',
}) => {
  const editorRef = useRef<HTMLDivElement>(null);
  const toolbarRef = useRef<HTMLDivElement>(null);
  const quillRef = useRef<any>(null);
  const [isReady, setIsReady] = useState(false);

  // Initialize Quill editor when component mounts
  useEffect(() => {
    // Import Quill dynamically (client-side only)
    const initializeQuill = async () => {
      if (!editorRef.current || !toolbarRef.current) return;
      
      const Quill = (await import('quill')).default;
      
      // Define custom formats/modules with table support
      const emailToolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'indent': '-1'}, { 'indent': '+1' }],
        [{ 'align': [] }],
        ['link'],
        ['clean'],
      ];

      // Create new Quill instance with the DOM element and custom toolbar
      const editorElement = editorRef.current;
      quillRef.current = new Quill(editorElement, {
        modules: {
          toolbar: {
            container: toolbarRef.current,
            handlers: {
              // Add any custom toolbar handlers here
            }
          },
        },
        placeholder: placeholder,
        theme: 'snow',
      });

      // Set initial content (sanitized)
      if (initialContent) {
        // Properly handle table content in the sanitized HTML
        const cleanContent = sanitizeHtml(initialContent);
        // Use clipboard API to ensure tables and complex HTML are rendered correctly
        quillRef.current.clipboard.dangerouslyPasteHTML(cleanContent);
      }

      // Add change listener
      quillRef.current.on('text-change', () => {
        const html = quillRef.current.root.innerHTML;
        onChange(html);
      });

      // Improve editor layout
      const editorContainer = editorElement.closest('.ql-container');
      if (editorContainer) {
        editorContainer.classList.add('email-editor-container');
      }

      setIsReady(true);
    };

    initializeQuill().catch(err => {
      console.error('Failed to initialize Quill editor:', err);
    });

    // Clean up on unmount
    return () => {
      if (quillRef.current) {
        // Clean up any event listeners or resources
        quillRef.current.off('text-change');
      }
    };
  }, []);

  // Update content from props if changed externally
  useEffect(() => {
    if (quillRef.current && isReady) {
      const currentContent = quillRef.current.root.innerHTML;
      // Only update if content changed to avoid editor position reset
      if (initialContent !== currentContent) {
        // Preserve cursor position if possible
        const selection = quillRef.current.getSelection();
        quillRef.current.clipboard.dangerouslyPasteHTML(sanitizeHtml(initialContent));
        if (selection) {
          quillRef.current.setSelection(selection);
        }
      }
    }
  }, [initialContent, isReady]);

  return (
    <div className="rich-email-editor-wrapper">
      {/* Custom toolbar container */}
      <div ref={toolbarRef} className="ql-toolbar ql-snow">
        <span className="ql-formats">
          <button className="ql-bold"></button>
          <button className="ql-italic"></button>
          <button className="ql-underline"></button>
          <button className="ql-strike"></button>
        </span>
        <span className="ql-formats">
          <select className="ql-color"></select>
          <select className="ql-background"></select>
        </span>
        <span className="ql-formats">
          <button className="ql-list" value="ordered"></button>
          <button className="ql-list" value="bullet"></button>
        </span>
        <span className="ql-formats">
          <button className="ql-indent" value="-1"></button>
          <button className="ql-indent" value="+1"></button>
        </span>
        <span className="ql-formats">
          <select className="ql-align"></select>
        </span>
        <span className="ql-formats">
          <button className="ql-link"></button>
        </span>
        <span className="ql-formats">
          <button className="ql-clean"></button>
        </span>
      </div>
      
      {/* Editor container with improved scrolling */}
      <div className="rich-email-editor-container">
        <div 
          ref={editorRef} 
          className="quill-editor"
        />
        
        {/* Loading indicator */}
        {!isReady && (
          <div className="flex items-center justify-center py-8">
            <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
          </div>
        )}
      </div>
      
      {/* Custom styles for email context */}
      <style jsx>{`
        .rich-email-editor-wrapper {
          display: flex;
          flex-direction: column;
          width: 100%;
          height: 100%;
          overflow: hidden;
          border-radius: 6px;
          flex: 1;
        }
        
        .rich-email-editor-container {
          display: flex;
          flex-direction: column;
          width: 100%;
          height: 100%;
          overflow: auto;
          flex: 1;
          position: relative;
        }
        
        .quill-editor {
          width: 100%;
          min-height: ${minHeight};
          max-height: ${maxHeight};
          overflow-y: auto;
          overflow-x: hidden;
        }
        
        /* Hide the editor until it's ready */
        .quill-editor ${!isReady ? '{ display: none; }' : ''}
        
        /* Hide duplicate toolbar */
        :global(.ql-toolbar.ql-snow + .ql-toolbar.ql-snow) {
          display: none !important;
        }
        
        :global(.ql-container) {
          border: none !important;
          height: auto !important;
          min-height: ${minHeight};
          max-height: none !important;
          overflow: visible;
        }
        
        :global(.ql-editor) {
          padding: 12px;
          min-height: ${minHeight};
          overflow-y: auto !important;
        }
        
        /* Fix table rendering */
        :global(.ql-editor table) {
          width: 100%;
          border-collapse: collapse;
        }
        
        :global(.ql-editor td),
        :global(.ql-editor th) {
          border: 1px solid #ccc;
          padding: 4px 8px;
          min-width: 40px;
        }
      `}</style>
    </div>
  );
};

export default RichEmailEditor; 