import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { Document, pdfjs } from 'react-pdf';
import { AnnotationData, Highlight, Comment, Rect } from '../../types/pdfReader';
import { Toolbar } from './Toolbar';
import { ColorPicker } from './ColorPicker';
import { CommentPopup } from './CommentPopup';
import { PDFPage } from './PDFPage';
import {
  createAnnotationData,
  addHighlight,
  removeHighlight,
  addComment,
  removeComment,
  exportAnnotations,
  importAnnotations
} from '../../utils/annotationUtils';
import { useSpeechSynthesis } from '../../hooks/useSpeechSynthesis';

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@4.8.69/build/pdf.worker.min.mjs`;

const migrateInitialAnnotations = (data: any): AnnotationData => {
  if (!data) return createAnnotationData();
  
  const migratedHighlights: Highlight[] = data.highlights?.map((h: any) => {
    if ('positions' in h) {
      return h as Highlight;
    }
    if ('position' in h) {
      return {
        ...h,
        positions: [h.position as Rect]
      };
    }
    return h;
  }) || [];

  return {
    ...data,
    highlights: migratedHighlights,
    version: '2.0.0'
  };
};

interface AdvancedPDFReaderProps {
  file: File | string;
  initialAnnotations?: AnnotationData;
  onAnnotationsChange?: (data: AnnotationData) => void;
  readOnly?: boolean;
  className?: string;
}

export const AdvancedPDFReader: React.FC<AdvancedPDFReaderProps> = ({
  file,
  initialAnnotations,
  onAnnotationsChange,
  readOnly = false,
  className = ''
}) => {
  const [numPages, setNumPages] = useState<number>(0);
  const [scale, setScale] = useState(1);
  const [annotations, setAnnotations] = useState<AnnotationData>(() => 
    migrateInitialAnnotations(initialAnnotations)
  );
  const [selectedColor, setSelectedColor] = useState('#ffeb3b');
  const [selectedHighlight, setSelectedHighlight] = useState<Highlight | null>(null);
  const [commentPopupPosition, setCommentPopupPosition] = useState({ x: 0, y: 0 });
  const [showCommentPopup, setShowCommentPopup] = useState(false);
  
  const { speak, isSpeaking } = useSpeechSynthesis();

  useEffect(() => {
    if (initialAnnotations) {
      setAnnotations(migrateInitialAnnotations(initialAnnotations));
    }
  }, [initialAnnotations]);

  useEffect(() => {
    if (onAnnotationsChange) {
      onAnnotationsChange(annotations);
    }
  }, [annotations, onAnnotationsChange]);

  const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
    setNumPages(numPages);
  };

  const handleZoomIn = useCallback(() => {
    setScale(prev => Math.min(prev + 0.25, 3));
  }, []);

  const handleZoomOut = useCallback(() => {
    setScale(prev => Math.max(prev - 0.25, 0.5));
  }, []);

  const handleZoomReset = useCallback(() => {
    setScale(1);
  }, []);

  const handleAddHighlight = useCallback((highlight: Omit<Highlight, 'id'>) => {
    if (readOnly) return;

    const highlightWithColor = {
      ...highlight,
      color: selectedColor
    };

    setAnnotations(prev => addHighlight(prev, highlightWithColor));
  }, [readOnly, selectedColor]);

  const handleHighlightClick = useCallback((highlight: Highlight, e: React.MouseEvent) => {
    setSelectedHighlight(highlight);
    setCommentPopupPosition({ x: e.clientX, y: e.clientY });
    setShowCommentPopup(true);
  }, []);

  const handleAddComment = useCallback((text: string) => {
    if (!selectedHighlight) return;

    setAnnotations(prev => addComment(prev, selectedHighlight.id, text));
  }, [selectedHighlight]);

  const handleDeleteComment = useCallback((commentId: string) => {
    setAnnotations(prev => removeComment(prev, commentId));
  }, []);

  const handleDeleteHighlight = useCallback(() => {
    if (!selectedHighlight) return;

    setAnnotations(prev => removeHighlight(prev, selectedHighlight.id));
    setShowCommentPopup(false);
    setSelectedHighlight(null);
  }, [selectedHighlight]);

  const handleExport = useCallback(() => {
    exportAnnotations(annotations);
  }, [annotations]);

  const handleImport = useCallback(async (file: File) => {
    try {
      const data = await importAnnotations(file);
      setAnnotations(data);
    } catch (err) {
      console.error('Failed to import annotations:', err);
      alert('导入批注失败，请检查文件格式');
    }
  }, []);

  const handleSpeak = useCallback(() => {
    if (selectedHighlight?.content) {
      speak(selectedHighlight.content);
    }
  }, [selectedHighlight, speak]);

  const getHighlightComments = useCallback((highlightId: string): Comment[] => {
    return annotations.comments.filter(c => c.highlightId === highlightId);
  }, [annotations.comments]);

  return (
    <div style={containerStyle} className={className}>
      {/* 工具栏已隐藏 — 仅保留阅读区域 */}

      {/* 颜色选择器已隐藏 */}

      <div style={contentStyle}>
        <Document
          file={file}
          onLoadSuccess={onDocumentLoadSuccess}
          loading={<div style={loadingStyle}>加载中...</div>}
          error={<div style={errorStyle}>加载 PDF 失败</div>}
        >
          {Array.from(new Array(numPages), (_, index) => (
            <PDFPage
              key={`page_${index + 1}`}
              pageNumber={index + 1}
              scale={scale}
              highlights={annotations.highlights}
              selectedHighlightId={selectedHighlight?.id || null}
              onHighlightClick={handleHighlightClick}
              onAddHighlight={handleAddHighlight}
              readOnly={readOnly}
            />
          ))}
        </Document>
      </div>

      {showCommentPopup && selectedHighlight && (
        <>
          <CommentPopup
            highlightId={selectedHighlight.id}
            comments={getHighlightComments(selectedHighlight.id)}
            position={commentPopupPosition}
            onAddComment={handleAddComment}
            onDeleteComment={handleDeleteComment}
            onClose={() => {
              setShowCommentPopup(false);
              setSelectedHighlight(null);
            }}
          />
          
          <div style={actionButtonsStyle}>
            {selectedHighlight.content && (
              <button
                onClick={handleSpeak}
                style={actionButtonStyle}
              >
                {isSpeaking ? '停止朗读' : '朗读'}
              </button>
            )}
            <button
              onClick={handleDeleteHighlight}
              style={{ ...actionButtonStyle, backgroundColor: '#f44336' }}
            >
              删除高亮
            </button>
          </div>
        </>
      )}
    </div>
  );
};

const containerStyle = {
  display: 'flex',
  flexDirection: 'column' as const,
  height: '100%',
  backgroundColor: '#e0e0e0',
  overflow: 'hidden'
} as const;

const colorPickerContainerStyle = {
  display: 'flex',
  alignItems: 'center',
  padding: '10px 20px',
  backgroundColor: '#f5f5f5',
  borderBottom: '1px solid #ddd'
} as const;

const colorPickerLabelStyle = {
  fontSize: '14px',
  color: '#666',
  marginRight: '10px'
} as const;

const contentStyle = {
  flex: 1,
  overflowY: 'auto' as const,
  padding: '20px'
} as const;

const loadingStyle = {
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  padding: '40px',
  fontSize: '16px'
} as const;

const errorStyle = {
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  padding: '40px',
  fontSize: '16px',
  color: '#f44336'
} as const;

const actionButtonsStyle = {
  position: 'fixed' as const,
  bottom: '20px',
  left: '50%',
  transform: 'translateX(-50%)',
  display: 'flex',
  gap: '10px',
  zIndex: 1001
} as const;

const actionButtonStyle = {
  padding: '10px 20px',
  backgroundColor: '#2196f3',
  color: 'white',
  border: 'none',
  borderRadius: '4px',
  cursor: 'pointer',
  fontSize: '14px',
  boxShadow: '0 2px 8px rgba(0,0,0,0.2)'
} as const;
