'use client';

import { useRef, useEffect, useState } from 'react';

interface RichTextareaProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  minHeight?: string;
  rows?: number;
}

export default function RichTextarea({ 
  value, 
  onChange, 
  placeholder = "Enter text...", 
  disabled = false,
  className = "",
  minHeight = "120px",
  rows = 6
}: RichTextareaProps) {
  const editorRef = useRef<HTMLDivElement>(null);
  const [showLinkModal, setShowLinkModal] = useState(false);
  const [linkUrl, setLinkUrl] = useState('');
  const [fontSize, setFontSize] = useState('14');
  const [activeFormats, setActiveFormats] = useState({
    bold: false,
    italic: false,
    underline: false,
    strikeThrough: false,
    justifyLeft: false,
    justifyCenter: false,
    justifyRight: false,
    justifyFull: false,
    insertUnorderedList: false,
    insertOrderedList: false
  });

  useEffect(() => {
    if (editorRef.current && editorRef.current.innerHTML !== value) {
      editorRef.current.innerHTML = value;
    }
  }, [value]);

  useEffect(() => {
    const handleSelectionChange = () => {
      updateActiveFormats();
    };

    // Initial format check when component mounts
    setTimeout(() => {
      if (editorRef.current) {
        editorRef.current.focus();
        updateActiveFormats();
      }
    }, 100);

    document.addEventListener('selectionchange', handleSelectionChange);
    return () => {
      document.removeEventListener('selectionchange', handleSelectionChange);
    };
  }, []);

  const handleInput = () => {
    if (editorRef.current) {
      const content = editorRef.current.innerHTML;
      onChange(content);
      updateActiveFormats();
    }
  };

  const updateActiveFormats = () => {
    if (!editorRef.current) return;
    
    try {
      const justifyLeft = document.queryCommandState('justifyLeft');
      const justifyCenter = document.queryCommandState('justifyCenter');
      const justifyRight = document.queryCommandState('justifyRight');
      const justifyFull = document.queryCommandState('justifyFull');
      
      // If no alignment is explicitly set, default to left alignment
      const isLeftAligned = justifyLeft || (!justifyCenter && !justifyRight && !justifyFull);
      
      setActiveFormats({
        bold: document.queryCommandState('bold'),
        italic: document.queryCommandState('italic'),
        underline: document.queryCommandState('underline'),
        strikeThrough: document.queryCommandState('strikeThrough'),
        justifyLeft: isLeftAligned,
        justifyCenter: justifyCenter,
        justifyRight: justifyRight,
        justifyFull: justifyFull,
        insertUnorderedList: document.queryCommandState('insertUnorderedList'),
        insertOrderedList: document.queryCommandState('insertOrderedList')
      });
    } catch (e) {
      // queryCommandState may not be supported in all browsers
      console.warn('queryCommandState not supported:', e);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (disabled) return;

    // Handle keyboard shortcuts
    if (e.ctrlKey || e.metaKey) {
      switch (e.key) {
        case 'b':
          e.preventDefault();
          document.execCommand('bold', false);
          break;
        case 'i':
          e.preventDefault();
          document.execCommand('italic', false);
          break;
        case 'u':
          e.preventDefault();
          document.execCommand('underline', false);
          break;
        case 'z':
          e.preventDefault();
          if (e.shiftKey) {
            document.execCommand('redo', false);
          } else {
            document.execCommand('undo', false);
          }
          break;
      }
    }

    // Handle Enter key for better list behavior
    if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
      const selection = window.getSelection();
      if (selection && selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        const container = range.commonAncestorContainer;
        
        // Check if we're in a list
        let listElement = container.nodeType === Node.TEXT_NODE ? container.parentElement : container as Element;
        while (listElement && listElement !== editorRef.current) {
          if (listElement.tagName === 'LI') {
            // Let default behavior handle list items
            return;
          }
          listElement = listElement.parentElement;
        }
      }
    }
  };

  const formatText = (command: string, value?: string) => {
    if (disabled) return;
    document.execCommand(command, false, value);
    if (editorRef.current) {
      editorRef.current.focus();
      handleInput();
      // Small delay to ensure DOM is updated before checking state
      setTimeout(updateActiveFormats, 10);
    }
  };

  const insertLink = () => {
    if (disabled) return;
    const selection = window.getSelection();
    if (selection && selection.toString()) {
      setShowLinkModal(true);
    } else {
      const url = prompt('Enter URL:');
      if (url) {
        const linkText = prompt('Enter link text:') || url;
        document.execCommand('insertHTML', false, `<a href="${url}" target="_blank">${linkText}</a>`);
        if (editorRef.current) {
          editorRef.current.focus();
          handleInput();
        }
      }
    }
  };

  const applyLink = () => {
    if (linkUrl) {
      document.execCommand('createLink', false, linkUrl);
      setShowLinkModal(false);
      setLinkUrl('');
      if (editorRef.current) {
        editorRef.current.focus();
        handleInput();
      }
    }
  };

  const changeFontSize = (size: string) => {
    if (disabled) return;
    setFontSize(size);
    document.execCommand('fontSize', false, '7');
    const fontElements = editorRef.current?.querySelectorAll('font[size="7"]');
    fontElements?.forEach(element => {
      element.removeAttribute('size');
      (element as HTMLElement).style.fontSize = size + 'px';
    });
    if (editorRef.current) {
      editorRef.current.focus();
      handleInput();
    }
  };

  const getPlainText = () => {
    if (editorRef.current) {
      return editorRef.current.textContent || '';
    }
    return '';
  };

  // Reusable styles
  const toolbarButtonStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '28px',
    height: '28px',
    border: '1px solid transparent',
    background: '#ffffff',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    fontWeight: '600',
    color: '#564B43',
    transition: 'all 0.2s ease',
    boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)'
  };

  const toolbarSelectStyle = {
    height: '28px',
    minHeight: '28px',
    border: '1px solid #E6E6E6',
    borderRadius: '4px',
    background: '#ffffff',
    fontSize: '12px',
    padding: '0 8px',
    color: '#564B43',
    cursor: 'pointer',
    minWidth: '85px',
    boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
    transition: 'all 0.2s ease'
  };

  const toolbarColorStyle = {
    width: '28px',
    height: '28px',
    minHeight: '28px',
    border: '1px solid #E6E6E6',
    borderRadius: '4px',
    cursor: 'pointer',
    background: '#ffffff',
    padding: 0,
    boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
    transition: 'all 0.2s ease',
    overflow: 'hidden'
  };

  const getButtonStyle = (isActive: boolean) => ({
    ...toolbarButtonStyle,
    background: isActive ? '#EF7310' : '#ffffff',
    color: isActive ? '#ffffff' : '#564B43',
    borderColor: isActive ? '#EF7310' : 'transparent',
    opacity: disabled ? 0.5 : 1,
    cursor: disabled ? 'not-allowed' : 'pointer'
  });

  const handleButtonHover = (e: React.MouseEvent<HTMLButtonElement>, isEnter: boolean, isActive: boolean) => {
    if (disabled) return;
    if (isEnter && !isActive) {
      e.currentTarget.style.background = '#EF7310';
      e.currentTarget.style.color = '#ffffff';
      e.currentTarget.style.borderColor = '#EF7310';
      e.currentTarget.style.transform = 'translateY(-1px)';
      e.currentTarget.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
    } else if (!isEnter && !isActive) {
      e.currentTarget.style.background = '#ffffff';
      e.currentTarget.style.color = '#564B43';
      e.currentTarget.style.borderColor = 'transparent';
      e.currentTarget.style.transform = 'translateY(0)';
      e.currentTarget.style.boxShadow = '0 1px 2px rgba(0, 0, 0, 0.05)';
    }
  };

  return (
    <>
      <style>{`
        .rich-textarea-wrapper:focus-within {
          border-color: #EF7310 !important;
          box-shadow: 0 0 0 0.2rem rgba(239, 115, 16, 0.25) !important;
        }
        .rich-editor[contenteditable]:empty:before {
          content: attr(data-placeholder);
          color: #999;
          opacity: 0.7;
          pointer-events: none;
        }
        .rich-editor p {
          margin: 0 0 12px 0;
        }
        .rich-editor p:last-child {
          margin-bottom: 0;
        }
        .rich-editor ul, .rich-editor ol {
          margin: 0 0 12px 0;
          padding-left: 24px;
        }
        .rich-editor li {
          margin-bottom: 4px;
        }
        .rich-editor strong {
          font-weight: 700;
        }
        .rich-editor em {
          font-style: italic;
        }
        .rich-editor u {
          text-decoration: underline;
        }
        .rich-editor s {
          text-decoration: line-through;
        }
        .rich-editor h1, .rich-editor h2, .rich-editor h3 {
          margin: 16px 0 8px 0;
          font-weight: bold;
        }
        .rich-editor h1 {
          font-size: 2em;
        }
        .rich-editor h2 {
          font-size: 1.5em;
        }
        .rich-editor h3 {
          font-size: 1.25em;
        }
        .rich-editor a {
          color: #EF7310;
          text-decoration: underline;
        }
        .rich-editor a:hover {
          text-decoration: none;
        }
      `}</style>
      <div 
        className={`rich-textarea-wrapper ${className}`}
        style={{
          border: '1px solid #E6E6E6',
          borderRadius: '6px',
          background: '#ffffff',
          overflow: 'hidden',
          transition: 'border-color 0.3s ease',
          padding: '0px'
        }}
      >
      {/* Toolbar */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        padding: '12px 16px',
        background: '#F8F9FA',
        borderBottom: '1px solid #E6E6E6',
        gap: '8px',
        flexWrap: 'wrap'
      }}>
        {/* Text Formatting */}
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('bold')}
          title="Bold (Ctrl+B)"
          disabled={disabled}
          style={getButtonStyle(activeFormats.bold)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.bold)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.bold)}
        >
          <strong>B</strong>
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('italic')}
          title="Italic (Ctrl+I)"
          disabled={disabled}
          style={getButtonStyle(activeFormats.italic)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.italic)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.italic)}
        >
          <em>I</em>
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('underline')}
          title="Underline (Ctrl+U)"
          disabled={disabled}
          style={getButtonStyle(activeFormats.underline)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.underline)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.underline)}
        >
          <u>U</u>
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('strikeThrough')}
          title="Strikethrough"
          disabled={disabled}
          style={getButtonStyle(activeFormats.strikeThrough)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.strikeThrough)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.strikeThrough)}
        >
          <s>S</s>
        </button>
        
        <div style={{
          width: '1px',
          height: '24px',
          background: '#E6E6E6',
          margin: '0 8px'
        }}></div>
        
        {/* Headings */}
        <select 
          onChange={(e) => formatText('formatBlock', e.target.value)}
          disabled={disabled}
          defaultValue=""
          style={{ 
            ...toolbarSelectStyle, 
            maxWidth: '90px',
            opacity: disabled ? 0.5 : 1,
            cursor: disabled ? 'not-allowed' : 'pointer'
          }}
        >
          <option value="">Format</option>
          <option value="h1">Heading 1</option>
          <option value="h2">Heading 2</option>
          <option value="h3">Heading 3</option>
          <option value="p">Paragraph</option>
        </select>
        
        {/* Font Size */}
        <select 
          onChange={(e) => changeFontSize(e.target.value)}
          disabled={disabled}
          value={fontSize}
          style={{ 
            ...toolbarSelectStyle, 
            maxWidth: '30px',
            opacity: disabled ? 0.5 : 1,
            cursor: disabled ? 'not-allowed' : 'pointer'
          }}
        >
          <option value="12">12px</option>
          <option value="14">14px</option>
          <option value="16">16px</option>
          <option value="18">18px</option>
          <option value="20">20px</option>
          <option value="24">24px</option>
        </select>
        
        <div style={{
          width: '1px',
          height: '24px',
          background: '#E6E6E6',
          margin: '0 8px'
        }}></div>
        
        {/* Text Colors */}
        <input
          type="color"
          onChange={(e) => formatText('foreColor', e.target.value)}
          title="Text Color"
          disabled={disabled}
          style={{
            ...toolbarColorStyle,
            opacity: disabled ? 0.5 : 1,
            cursor: disabled ? 'not-allowed' : 'pointer'
          }}
        />
        <input
          type="color"
          onChange={(e) => formatText('backColor', e.target.value)}
          title="Background Color"
          disabled={disabled}
          defaultValue="#ffffff"
          style={{
            ...toolbarColorStyle,
            opacity: disabled ? 0.5 : 1,
            cursor: disabled ? 'not-allowed' : 'pointer'
          }}
        />
        
        <div style={{
          width: '1px',
          height: '24px',
          background: '#E6E6E6',
          margin: '0 8px'
        }}></div>
        
        {/* Alignment */}
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('justifyLeft')}
          title="Align Left"
          disabled={disabled}
          style={getButtonStyle(activeFormats.justifyLeft)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.justifyLeft)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.justifyLeft)}
        >
          ⬅
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('justifyCenter')}
          title="Center"
          disabled={disabled}
          style={getButtonStyle(activeFormats.justifyCenter)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.justifyCenter)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.justifyCenter)}
        >
          ↔
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('justifyRight')}
          title="Align Right"
          disabled={disabled}
          style={getButtonStyle(activeFormats.justifyRight)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.justifyRight)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.justifyRight)}
        >
          ➡
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('justifyFull')}
          title="Justify"
          disabled={disabled}
          style={getButtonStyle(activeFormats.justifyFull)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.justifyFull)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.justifyFull)}
        >
          ⬌
        </button>
        
        <div style={{
          width: '1px',
          height: '24px',
          background: '#E6E6E6',
          margin: '0 8px'
        }}></div>
        
        {/* Lists */}
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('insertUnorderedList')}
          title="Bullet List"
          disabled={disabled}
          style={getButtonStyle(activeFormats.insertUnorderedList)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.insertUnorderedList)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.insertUnorderedList)}
        >
          •
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('insertOrderedList')}
          title="Numbered List"
          disabled={disabled}
          style={getButtonStyle(activeFormats.insertOrderedList)}
          onMouseEnter={(e) => handleButtonHover(e, true, activeFormats.insertOrderedList)}
          onMouseLeave={(e) => handleButtonHover(e, false, activeFormats.insertOrderedList)}
        >
          1.
        </button>
        
        <div style={{
          width: '1px',
          height: '24px',
          background: '#E6E6E6',
          margin: '0 8px'
        }}></div>
        
        {/* Link */}
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={insertLink}
          title="Insert Link"
          disabled={disabled}
          style={{ ...toolbarButtonStyle, opacity: disabled ? 0.5 : 1, cursor: disabled ? 'not-allowed' : 'pointer' }}
          onMouseEnter={(e) => handleButtonHover(e, true, false)}
          onMouseLeave={(e) => handleButtonHover(e, false, false)}
        >
          🔗
        </button>
        
        {/* Undo/Redo */}
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('undo')}
          title="Undo (Ctrl+Z)"
          disabled={disabled}
          style={{ ...toolbarButtonStyle, opacity: disabled ? 0.5 : 1, cursor: disabled ? 'not-allowed' : 'pointer' }}
          onMouseEnter={(e) => handleButtonHover(e, true, false)}
          onMouseLeave={(e) => handleButtonHover(e, false, false)}
        >
          ↶
        </button>
        <button 
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => formatText('redo')}
          title="Redo (Ctrl+Shift+Z)"
          disabled={disabled}
          style={{ ...toolbarButtonStyle, opacity: disabled ? 0.5 : 1, cursor: disabled ? 'not-allowed' : 'pointer' }}
          onMouseEnter={(e) => handleButtonHover(e, true, false)}
          onMouseLeave={(e) => handleButtonHover(e, false, false)}
        >
          ↷
        </button>
      </div>
      
      {/* Editor */}
      <div
        ref={editorRef}
        contentEditable={!disabled}
        className="rich-editor"
        style={{ 
          minHeight,
          padding: '12px',
          outline: 'none',
          fontSize: '16px',
          lineHeight: '1.6',
          color: '#564B43',
          fontFamily: '"Manrope", sans-serif',
          overflowY: 'auto',
          maxHeight: '400px'
        }}
        onInput={handleInput}
        onKeyDown={handleKeyDown}
        data-placeholder={placeholder}
        suppressContentEditableWarning={true}
      />
      
      {/* Hidden input for form compatibility */}
      <input
        type="hidden"
        value={getPlainText()}
        readOnly
      />
      
      {/* Link Modal */}
      {showLinkModal && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000
        }}>
          <div style={{
            background: '#ffffff',
            padding: '24px',
            borderRadius: '8px',
            boxShadow: '0 10px 30px rgba(0, 0, 0, 0.3)',
            minWidth: '320px',
            maxWidth: '400px'
          }}>
            <h3 style={{
              margin: '0 0 16px 0',
              fontSize: '18px',
              fontWeight: '600',
              color: '#564B43'
            }}>Insert Link</h3>
            <input
              type="url"
              value={linkUrl}
              onChange={(e) => setLinkUrl(e.target.value)}
              placeholder="Enter URL"
              style={{
                width: '100%',
                padding: '12px',
                border: '1px solid #E6E6E6',
                borderRadius: '6px',
                fontSize: '14px',
                marginBottom: '16px',
                outline: 'none'
              }}
              autoFocus
            />
            <div style={{
              display: 'flex',
              gap: '8px',
              justifyContent: 'flex-end'
            }}>
              <button 
                onClick={applyLink} 
                style={{
                  padding: '8px 16px',
                  border: 'none',
                  borderRadius: '4px',
                  fontSize: '14px',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  background: '#EF7310',
                  color: 'white'
                }}
              >
                Apply
              </button>
              <button 
                onClick={() => {setShowLinkModal(false); setLinkUrl('')}} 
                style={{
                  padding: '8px 16px',
                  border: 'none',
                  borderRadius: '4px',
                  fontSize: '14px',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  background: '#F1F5F9',
                  color: '#564B43'
                }}
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
      </div>
    </>
  );
}