import React, { useRef, useState, useCallback } from 'react';
import { Page } from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';
import { Highlight, Rect } from '../../types/pdfReader';

interface PDFPageProps {
  pageNumber: number;
  scale: number;
  highlights: Highlight[];
  selectedHighlightId: string | null;
  onHighlightClick: (highlight: Highlight, event: React.MouseEvent) => void;
  onAddHighlight: (highlight: Omit<Highlight, 'id'>) => void;
  readOnly?: boolean;
}

const mergeRects = (rects: DOMRect[], pageRect: DOMRect, scale: number): Rect[] => {
  if (rects.length === 0) return [];

  const groups: DOMRect[][] = [];
  let currentGroup: DOMRect[] = [rects[0]];
  const threshold = 5;

  for (let i = 1; i < rects.length; i++) {
    const currentRect = rects[i];
    const lastRectInGroup = currentGroup[currentGroup.length - 1];

    const currentCenterY = (currentRect.top + currentRect.bottom) / 2;
    const groupCenterY = (lastRectInGroup.top + lastRectInGroup.bottom) / 2;

    if (Math.abs(currentCenterY - groupCenterY) < threshold) {
      currentGroup.push(currentRect);
    } else {
      groups.push(currentGroup);
      currentGroup = [currentRect];
    }
  }

  if (currentGroup.length > 0) {
    groups.push(currentGroup);
  }

  const mergedPositions: Rect[] = groups.map((group) => {
    const minX = Math.min(...group.map(r => r.left));
    const minY = Math.min(...group.map(r => r.top));
    const maxX = Math.max(...group.map(r => r.right));
    const maxY = Math.max(...group.map(r => r.bottom));

    const x1 = minX - pageRect.left;
    const y1 = minY - pageRect.top;
    const x2 = maxX - pageRect.left;
    const y2 = maxY - pageRect.top;

    return {
      x1: Math.max(0, x1) / scale,
      y1: Math.max(0, y1) / scale,
      x2: x2 / scale,
      y2: y2 / scale,
      width: (x2 - Math.max(0, x1)) / scale,
      height: (y2 - Math.max(0, y1)) / scale
    };
  });

  return mergedPositions;
};

export const PDFPage: React.FC<PDFPageProps> = ({
  pageNumber,
  scale,
  highlights,
  selectedHighlightId,
  onHighlightClick,
  onAddHighlight,
  readOnly = false
}) => {
  const pageContainerRef = useRef<HTMLDivElement>(null);
  const pageRef = useRef<HTMLDivElement>(null);
  const [pageSize, setPageSize] = useState({ width: 0, height: 0 });

  const pageHighlights = highlights.filter(h => h.pageNumber === pageNumber);

  const handlePageLoadSuccess = useCallback((page: any) => {
    setPageSize({
      width: page.view[2],
      height: page.view[3]
    });
  }, []);

  const handleMouseUp = useCallback(() => {
    if (readOnly) return;

    const selection = window.getSelection();
    if (!selection || selection.toString().trim() === '') {
      return;
    }

    const range = selection.getRangeAt(0);
    
    const pageRect = pageRef.current?.getBoundingClientRect();
    if (!pageRect) return;

    const rects = range.getClientRects();
    if (rects.length === 0) {
      selection.removeAllRanges();
      return;
    }

    const positions = mergeRects(Array.from(rects), pageRect, scale);

    const newHighlight: Omit<Highlight, 'id'> = {
      type: 'text',
      pageNumber,
      positions,
      content: selection.toString(),
      color: '#ffeb3b'
    };

    onAddHighlight(newHighlight);
    selection.removeAllRanges();
  }, [readOnly, pageNumber, scale, onAddHighlight]);

  return (
    <div style={pageContainerStyle} ref={pageContainerRef}>
      <div
        ref={pageRef}
        onMouseUp={handleMouseUp}
        style={{ position: 'relative' }}
      >
        <Page
          pageNumber={pageNumber}
          scale={scale}
          renderTextLayer={true}
          renderAnnotationLayer={true}
          onLoadSuccess={handlePageLoadSuccess}
        />
        
        {pageHighlights.map((highlight) => {
          const isSelected = highlight.id === selectedHighlightId;
          return (
            <React.Fragment key={highlight.id}>
              {highlight.positions.map((position, index) => (
                <div
                  key={`${highlight.id}-${index}`}
                  onClick={(e) => {
                    e.stopPropagation();
                    onHighlightClick(highlight, e);
                  }}
                  style={{
                    ...highlightStyle,
                    backgroundColor: highlight.color + '60',
                    border: isSelected ? `2px solid ${highlight.color}` : 'none',
                    left: position.x1 * scale,
                    top: position.y1 * scale,
                    width: position.width * scale,
                    height: position.height * scale
                  }}
                />
              ))}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
};

const pageContainerStyle = {
  display: 'flex',
  justifyContent: 'center',
  marginBottom: '20px',
  padding: '10px'
} as const;

const highlightStyle = {
  position: 'absolute',
  pointerEvents: 'auto',
  cursor: 'pointer',
  borderRadius: '2px',
  transition: 'all 0.2s',
  zIndex: 10
} as const;
