// src/components/PDFViewer.tsx
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';

// Import CSS for react-pdf
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';
import { 
    UploadIcon, 
    ChevronLeft, 
    ChevronRight, 
    FileText, 
    Eye, 
    Clock,
    ZoomIn,
    ZoomOut,
    RotateCw,
    Download,
    Image as ImageIcon
} from 'lucide-react';
import { format } from 'date-fns';
import { Message } from '@/components/ChatInterface';

// Configure worker with better error handling
const configureWorker = () => {
    try {
        // Try CDN first for better reliability
        pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.mjs`;
        console.log('Using CDN .mjs worker, version:', pdfjs.version);
    } catch (error) {
        console.warn('CDN worker failed, trying local worker');
        pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.mjs';
    }
};

// Configure worker on module load
configureWorker();

interface ProcessedPage {
    pageNumber: number;
    processedAt: string;
    ocrResult?: string;
}

interface DocPdfProps {
    setExtractedData: ({}) => void;
}

type FileType = 'pdf' | 'image' | null;

const DocPdf: React.FC<DocPdfProps> = ({setExtractedData}) => {
    const [messages, setMessages] = useState<Message[]>([]);
    const [fileUrl, setFileUrl] = useState<string | null>(null);
    const [fileType, setFileType] = useState<FileType>(null);
    const [pageNumber, setPageNumber] = useState<number>(1);
    const [totalPages, setTotalPages] = useState<number | null>(null);
    const [processedPages, setProcessedPages] = useState<ProcessedPage[]>([]);
    const [isProcessing, setIsProcessing] = useState<boolean>(false);
    const [currentFileName, setCurrentFileName] = useState<string>('');
    const [scale, setScale] = useState<number>(1.2);
    const [rotation, setRotation] = useState<number>(0);
    const [isDocumentLoading, setIsDocumentLoading] = useState<boolean>(false);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [dialogueText, setDialogueText] = useState<Message[]>([]);

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        const url = URL.createObjectURL(file);
        setFileUrl(url);
        setCurrentFileName(file.name);
        
        // Determine file type
        if (file.type === 'application/pdf') {
            setFileType('pdf');
            setIsDocumentLoading(true);
            
            const form = new FormData();
            form.append('file', file); // Changed from 'filename' to 'file' to match backend
            console.log('filename', file.name);
            
            try {
                const response = await fetch('http://localhost:4402/upload_document', {
                    method: 'POST',
                    body: form,
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const json_result = await response.json();
                console.log("OCR result:", json_result.content);

                if (json_result.result) {
                    console.log("Document processed at:", json_result.result);
                    console.log("Parsed content:", json_result.content);
                    setExtractedData(json_result.content);
                }
                
            } catch (error) {
                console.error('Error uploading document:', error);
                
            }

        } else if (file.type.startsWith('image/')) {
            setFileType('image');
            setTotalPages(1);
            // Process image immediately
            try {
                await processCurrentPage(file);
            } catch (error) {
                console.error('Error processing image:', error);
                // Handle image processing error
            }
        }
    };

    const processCurrentPage = async (file?: File) => {
        if (!file && !fileUrl) return;
        
        setIsProcessing(true);
        
        try {
            let fileToProcess: File;
            
            if (file) {
                fileToProcess = file;
            } else {
                // For PDF, we need to convert current page to image
                // This is a simplified approach - in production, you might want to use PDF.js to render the page to canvas
                const response = await fetch(fileUrl!);
                const blob = await response.blob();
                fileToProcess = new File([blob], currentFileName);
            }

            const form = new FormData();
            // form.append('file', fileToProcess);
            form.append('page_number', pageNumber.toString());

            // const response = await fetch('http://192.168.42.22:4402/get_page', {
            //     method: 'POST',
            //     body: form,
            // });
            // const json_result = await response.json();
            // console.log("OCR result:", json_result);

            // Add to processed pages
            const newProcessedPage: ProcessedPage = {
                pageNumber,
                processedAt: format(new Date(), 'dd/MM/yyyy HH:mm:ss'),
                ocrResult: "" //json_result.content
            };
            
            setProcessedPages(prev => {
                const filtered = prev.filter(p => p.pageNumber !== pageNumber);
                return [...filtered, newProcessedPage].sort((a, b) => a.pageNumber - b.pageNumber);
            });

            // setTimeout(() => {
            //     const botMessage: Message = { sender: 'Bot', text: `${pdfResult.ocr_json}` };
            //     setMessages(prev => [...prev, botMessage]);
            //     setDialogueText(messages);
            // }, 500);
        } catch (error) {
            console.error('Error processing file:', error);
        } finally {
            setIsProcessing(false);
        }
    };

    const onDocumentLoadSuccess = useCallback(({ numPages }: { numPages: number }) => {
        setTotalPages(numPages);
        setIsDocumentLoading(false);
        console.log('PDF loaded with', numPages, 'pages');
    }, []);

    const onDocumentLoadError = useCallback((error: Error) => {
        console.error('Error loading PDF:', error);
        setIsDocumentLoading(false);
    }, []);

    const handlePageChange = async (newPageNumber: number) => {
        if (newPageNumber >= 1 && (totalPages === null || newPageNumber <= totalPages)) {
            setPageNumber(newPageNumber);
            const form = new FormData();
            form.append('new_page_number', newPageNumber.toString());
            try {
                const response = await fetch('http://localhost:4402/get_page', {
                    method: 'POST',
                    body: form,
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const json_result = await response.json();
                console.log("page result:", json_result.content);

                if (json_result.result) {
                    console.log("Document processed at:", json_result.result);
                    console.log("Parsed page content:", json_result.content);
                    setExtractedData(json_result.content);
                }
                
            } catch (error) {
                console.error('Error uploading document:', error);
                
            }
        }
    };

    const goToNextPage = () => {
        handlePageChange(pageNumber + 1);
    };

    const goToPreviousPage = () => {
        handlePageChange(pageNumber - 1);
    };

    const handleZoomIn = () => {
        setScale(prev => Math.min(prev + 0.2, 3));
    };

    const handleZoomOut = () => {
        setScale(prev => Math.max(prev - 0.2, 0.5));
    };

    // const handleRotate = () => {
    //     setRotation(prev => (prev + 90) % 360);
    // };

    const isPageProcessed = (page: number) => {
        return processedPages.some(p => p.pageNumber === page);
    };

    const getProcessedPageInfo = (page: number) => {
        return processedPages.find(p => p.pageNumber === page);
    };

    useEffect(() => {
        if (pageNumber) {
            console.log('page_number', pageNumber.toString());
        }
    }, [pageNumber]);

    return (
        <div className="flex min-h-screen bg-gray-50">
            <div className="flex-1 ml-2 mr-2 p-4 flex w-full justify-center">
                <div className="w-full max-w-none h-[95%] flex flex-col space-y-6">
                    
                    {/* Header with File Info and Upload */}
                    <div className="bg-white rounded-lg shadow-sm border p-4">
                        <div className="flex items-center justify-between mb-4">
                            <div className="flex items-center space-x-4">
                                <div className="flex items-center space-x-2">
                                    {fileType === 'pdf' ? (
                                        <FileText className="w-5 h-5 text-red-600" />
                                    ) : fileType === 'image' ? (
                                        <ImageIcon className="w-5 h-5 text-blue-600" />
                                    ) : (
                                        <FileText className="w-5 h-5 text-gray-600" />
                                    )}
                                    <span className="font-medium text-gray-800">
                                        {currentFileName || 'No file selected'}
                                    </span>
                                    {fileType && (
                                        <span className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded-full uppercase">
                                            {fileType}
                                        </span>
                                    )}
                                </div>
                                {totalPages && (
                                    <span className="text-sm text-gray-500">
                                        ({totalPages} pages total)
                                    </span>
                                )}
                            </div>
                            
                            <label className="inline-flex items-center justify-center px-4 py-2 bg-blue-950 hover:bg-blue-900 text-white rounded-md cursor-pointer space-x-2 transition-colors">
                                <UploadIcon className="w-4 h-4" />
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept=".pdf,image/*"
                                    onChange={handleFileChange}
                                    className="hidden"
                                />
                            </label>
                        </div>

                        {/* Navigation and Controls */}
                        <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-4">
                                <button
                                    onClick={goToPreviousPage}
                                    disabled={pageNumber <= 1}
                                    className="flex items-center space-x-1 px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed rounded-md transition-colors"
                                >
                                    <ChevronLeft className="w-4 h-4" />
                                </button>

                                <div className="flex items-center space-x-3">
                                    <label className="text-sm font-medium text-gray-700">
                                        Page:
                                    </label>
                                    <input
                                        type="number"
                                        min="1"
                                        max={totalPages || undefined}
                                        value={pageNumber}
                                        onChange={(e) => handlePageChange(parseInt(e.target.value) || 1)}
                                        className="w-20 px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    />
                                    {totalPages && (
                                        <span className="text-sm text-gray-500">
                                            of {totalPages}
                                        </span>
                                    )}
                                </div>

                                <button
                                    onClick={goToNextPage}
                                    disabled={totalPages !== null && pageNumber >= totalPages}
                                    className="flex items-center space-x-1 px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed rounded-md transition-colors"
                                >
                                    <ChevronRight className="w-4 h-4" />
                                </button>
                            </div>

                            {/* Viewer Controls */}
                            {fileUrl && (
                                <div className="flex items-center space-x-2">
                                    <button
                                        onClick={handleZoomOut}
                                        className="p-2 text-gray-600 hover:bg-gray-100 rounded-md transition-colors"
                                        title="Zoom Out"
                                    >
                                        <ZoomOut className="w-4 h-4" />
                                    </button>
                                    <span className="text-sm text-gray-600 min-w-12 text-center">
                                        {Math.round(scale * 100)}%
                                    </span>
                                    <button
                                        onClick={handleZoomIn}
                                        className="p-2 text-gray-600 hover:bg-gray-100 rounded-md transition-colors"
                                        title="Zoom In"
                                    >
                                        <ZoomIn className="w-4 h-4" />
                                    </button>
                                    {/* <button
                                        onClick={handleRotate}
                                        className="p-2 text-gray-600 hover:bg-gray-100 rounded-md transition-colors"
                                        title="Rotate"
                                    >
                                        <RotateCw className="w-4 h-4" />
                                    </button> */}
                                    <button
                                        onClick={() => processCurrentPage()}
                                        disabled={isProcessing}
                                        className="px-3 py-2 text-sm bg-green-600 hover:bg-green-700 disabled:opacity-50 text-white rounded-md transition-colors"
                                    >
                                        {isProcessing ? 'Processing...' : 'Process Page'}
                                    </button>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Document Viewer */}
                    {fileUrl && (
                        <div className="border-2 border-gray-300 rounded-lg bg-white flex-1 overflow-auto">
                            <div className="flex items-center justify-between p-4 border-b">
                                <h3 className="text-lg font-medium text-gray-800">
                                    {fileType === 'pdf' ? `PDF Page ${pageNumber}` : 'Image Preview'}
                                </h3>
                                {isPageProcessed(pageNumber) && (
                                    <span className="px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full">
                                        ✓ Processed
                                    </span>
                                )}
                            </div>
                            
                            <div className="p-4 flex justify-center">
                                {fileType === 'pdf' ? (
                                    <div className="pdf-container">
                                        <Document
                                            file={fileUrl}
                                            onLoadSuccess={onDocumentLoadSuccess}
                                            onLoadError={onDocumentLoadError}
                                            loading={
                                                <div className="flex items-center justify-center p-8">
                                                    <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
                                                    <span className="ml-3">Loading PDF...</span>
                                                </div>
                                            }
                                        >
                                            <Page
                                                pageNumber={pageNumber}
                                                scale={scale}
                                                rotate={rotation}
                                                loading={
                                                    <div className="flex items-center justify-center p-8">
                                                        <div className="w-6 h-6 border-2 border-gray-400 border-t-transparent rounded-full animate-spin"></div>
                                                        <span className="ml-2">Loading page...</span>
                                                    </div>
                                                }
                                                className="shadow-lg"
                                            />
                                        </Document>
                                    </div>
                                ) : fileType === 'image' ? (
                                    <img
                                        src={fileUrl}
                                        alt={`${currentFileName} preview`}
                                        className="max-w-full h-auto object-contain shadow-lg rounded"
                                        style={{ 
                                            transform: `scale(${scale}) rotate(${rotation}deg)`,
                                            transition: 'transform 0.2s ease'
                                        }}
                                    />
                                ) : null}
                            </div>
                        </div>
                    )}

                    {/* Welcome Message */}
                    {!fileUrl && (
                        <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center bg-white">
                            <FileText className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                            <h3 className="text-lg font-medium text-gray-800 mb-2">
                                Upload a PDF or Image File
                            </h3>
                            <p className="text-gray-600 mb-4">
                                Select a PDF document or image file to start viewing and processing pages.
                            </p>
                            <label className="inline-flex items-center justify-center px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-md cursor-pointer space-x-2 transition-colors">
                                <UploadIcon className="w-5 h-5" />
                                <span>Choose File</span>
                                <input
                                    type="file"
                                    accept=".pdf,image/*"
                                    onChange={handleFileChange}
                                    className="hidden"
                                />
                            </label>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default DocPdf;