import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { useEffect, useState, useRef } from 'react';
import { $getRoot, $isParagraphNode } from 'lexical';
import { useFileStore } from '../../stores/fileStore';
import { Comment01Icon } from 'hugeicons-react';

export default function LineNumbers() {
  const [editor] = useLexicalComposerContext();
  const { activeFileId, files, setComment } = useFileStore();
  const activeFile = files.find(f => f.id === activeFileId);
  const [lines, setLines] = useState<{ id: string, top: number, height: number, index: number }[]>([]);
  const [activeCommentLine, setActiveCommentLine] = useState<string | null>(null);
  const [expandedComments, setExpandedComments] = useState<Set<string>>(new Set());
  const [commentText, setCommentText] = useState('');
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const updateLineNumbers = () => {
      editor.getEditorState().read(() => {
        const root = $getRoot();
        const children = root.getChildren();
        const newLines: any[] = [];
        
        const containerElement = containerRef.current;
        if (!containerElement) return;
        
        const containerRect = containerElement.getBoundingClientRect();
        
        let globalIndex = 1;
        children.forEach((node) => {
          if ($isParagraphNode(node)) {
            const elm = editor.getElementByKey(node.getKey());
            if (elm) {
              const rect = elm.getBoundingClientRect();
              
              const textContent = node.getTextContent();
              const explicitLines = textContent.split('\n').length;
              const computedLineHeight = 22.5; // 15px * 1.5

              for (let i = 0; i < explicitLines; i++) {
                 const lineId = `${node.getKey()}${i > 0 ? '-' + i : ''}`;
                 newLines.push({
                   id: lineId,
                   rootId: node.getKey(),
                   top: (rect.top - containerRect.top) + (i * computedLineHeight),
                   height: computedLineHeight,
                   index: globalIndex++,
                 });
              }
            }
          }
        });
        setLines(newLines);
      });
    };

    const unregister = editor.registerUpdateListener(() => {
      // Small delay to ensure DOM has reflowed
      setTimeout(updateLineNumbers, 0);
    });
    
    // Initial and periodic syncs
    updateLineNumbers();
    const interval = setInterval(updateLineNumbers, 1000); 

    window.addEventListener('resize', updateLineNumbers);

    return () => {
      unregister();
      clearInterval(interval);
      window.removeEventListener('resize', updateLineNumbers);
    };
  }, [editor]);

  return (
    <div 
      ref={containerRef}
      className="line-numbers-container" 
      style={{ 
        position: 'relative', 
        width: 45, 
        minHeight: '100%', 
        borderRight: '1px solid rgba(0,0,0,0.05)',
        marginRight: 0,
        backgroundColor: 'transparent',
        userSelect: 'none',
        pointerEvents: 'none'
      }}
    >
      {lines.map(line => (
        <div 
          key={line.id} 
          className="line-number-item"
          style={{ 
            position: 'absolute', 
            top: line.top, 
            width: '100%', 
            textAlign: 'right', 
            paddingRight: 12,
            color: 'var(--text-secondary)',
            fontSize: '15px',
            opacity: 0.3,
            fontFamily: 'var(--font-ibm-plex)',
            lineHeight: '1.5',
            pointerEvents: 'auto',
            cursor: 'pointer',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'flex-end'
          }}
          onClick={(e) => {
            e.stopPropagation();
            setActiveCommentLine(line.id);
            setCommentText(activeFile?.comments?.[line.id] || '');
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
             {activeFile?.comments?.[line.id] && (
               <button 
                 onClick={(e) => {
                   e.stopPropagation();
                   setExpandedComments(prev => {
                     const next = new Set(prev);
                     if (next.has(line.id)) next.delete(line.id);
                     else next.add(line.id);
                     return next;
                   });
                 }}
                 style={{ 
                   opacity: expandedComments.has(line.id) ? 1 : 0.4, 
                   color: expandedComments.has(line.id) ? 'var(--accent-color)' : 'inherit',
                   display: 'flex', alignItems: 'center'
                 }}
                 title={expandedComments.has(line.id) ? "Minimize comment" : "Expand comment"}
               >
                 <Comment01Icon size={12} />
               </button>
             )}
             {line.index}
          </div>
          
          {/* Top-part comment UI */}
          {activeCommentLine === line.id && (
            <div 
              onClick={e => e.stopPropagation()}
              style={{
                position: 'fixed', left: 60, zIndex: 100,
                background: 'var(--bg-panel)', border: '1px solid var(--border-color)',
                borderRadius: '6px', padding: '12px', width: 220,
                boxShadow: '0 10px 25px rgba(0,0,0,0.1)'
              }}
            >
               <textarea 
                 autoFocus
                 value={commentText}
                 onChange={e => setCommentText(e.target.value)}
                 placeholder="Line comment..."
                 style={{ width: '100%', height: 60, fontSize: '11px', border: 'none', outline: 'none', background: 'transparent', resize: 'none' }}
               />
               <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px', marginTop: '8px' }}>
                  <button onClick={() => setActiveCommentLine(null)} style={{ fontSize: '10px', opacity: 0.5 }}>Cancel</button>
                  <button 
                    onClick={() => {
                        if (activeFileId) setComment(activeFileId, line.id, commentText);
                        setActiveCommentLine(null);
                    }}
                    style={{ fontSize: '10px', fontWeight: 600, color: 'var(--accent-color)' }}
                  >Save</button>
               </div>
            </div>
          )}

          {activeFile?.comments?.[line.id] && activeCommentLine !== line.id && expandedComments.has(line.id) && (
             <div 
                className="comment-bubble"
                onClick={(e) => {
                  e.stopPropagation();
                  setExpandedComments(prev => {
                    const next = new Set(prev);
                    next.delete(line.id);
                    return next;
                  });
                }}
                title="Click to minimize"
                style={{ 
                  marginTop: 4, 
                  textAlign: 'left', 
                  wordBreak: 'break-word', 
                  userSelect: 'text',
                  cursor: 'pointer',
                  animation: 'fadeInSlide 0.2s ease forwards'
                }}
             >
                {activeFile.comments[line.id]}
             </div>
          )}
        </div>
      ))}
    </div>
  );
}
