"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RFPDocumentUpload = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_2 = require("@chakra-ui/react");
const icons_1 = require("@chakra-ui/icons");
const RFPDocumentUpload = ({ onDocumentsProcessed, onAnalysisComplete, maxFileSize = 10, acceptedFormats = ['pdf', 'doc', 'docx'], className }) => {
    const [documents, setDocuments] = (0, react_1.useState)([]);
    const [urlInput, setUrlInput] = (0, react_1.useState)('');
    const [googleDriveInput, setGoogleDriveInput] = (0, react_1.useState)('');
    const [textInput, setTextInput] = (0, react_1.useState)('');
    const [isProcessing, setIsProcessing] = (0, react_1.useState)(false);
    const [dragOver, setDragOver] = (0, react_1.useState)(false);
    const toast = (0, react_2.useToast)();
    const addDocument = (0, react_1.useCallback)((document) => {
        setDocuments(prev => [...prev, document]);
    }, []);
    const updateDocument = (0, react_1.useCallback)((id, updates) => {
        setDocuments(prev => prev.map(doc => doc.id === id ? { ...doc, ...updates } : doc));
    }, []);
    const removeDocument = (0, react_1.useCallback)((id) => {
        setDocuments(prev => prev.filter(doc => doc.id !== id));
    }, []);
    const handleFileUpload = (0, react_1.useCallback)((files) => {
        if (!files)
            return;
        Array.from(files).forEach(file => {
            // Validate file size
            if (file.size > maxFileSize * 1024 * 1024) {
                toast({
                    title: 'File too large',
                    description: `${file.name} exceeds ${maxFileSize}MB limit`,
                    status: 'error',
                    duration: 5000,
                    isClosable: true
                });
                return;
            }
            // Validate file type
            const fileExtension = file.name.split('.').pop()?.toLowerCase();
            if (!fileExtension || !acceptedFormats.includes(fileExtension)) {
                toast({
                    title: 'Unsupported file type',
                    description: `${file.name} is not a supported format`,
                    status: 'error',
                    duration: 5000,
                    isClosable: true
                });
                return;
            }
            const document = {
                id: `file-${Date.now()}-${Math.random()}`,
                type: fileExtension,
                name: file.name,
                size: file.size,
                file,
                status: 'pending',
                progress: 0
            };
            addDocument(document);
            processDocument(document);
        });
    }, [maxFileSize, acceptedFormats, addDocument, toast]);
    const handleUrlSubmit = (0, react_1.useCallback)(() => {
        if (!urlInput.trim())
            return;
        const document = {
            id: `url-${Date.now()}`,
            type: 'url',
            name: urlInput,
            url: urlInput,
            status: 'pending',
            progress: 0
        };
        addDocument(document);
        processDocument(document);
        setUrlInput('');
    }, [urlInput, addDocument]);
    const handleGoogleDriveSubmit = (0, react_1.useCallback)(() => {
        if (!googleDriveInput.trim())
            return;
        const document = {
            id: `gdrive-${Date.now()}`,
            type: 'google-drive',
            name: googleDriveInput,
            url: googleDriveInput,
            status: 'pending',
            progress: 0
        };
        addDocument(document);
        processDocument(document);
        setGoogleDriveInput('');
    }, [googleDriveInput, addDocument]);
    const handleTextSubmit = (0, react_1.useCallback)(() => {
        if (!textInput.trim())
            return;
        const document = {
            id: `text-${Date.now()}`,
            type: 'text',
            name: 'Pasted Text Content',
            status: 'pending',
            progress: 0
        };
        addDocument(document);
        processDocument(document);
        setTextInput('');
    }, [textInput, addDocument]);
    const processDocument = async (document) => {
        try {
            updateDocument(document.id, { status: 'uploading', progress: 20 });
            // Simulate document processing with progress updates
            await new Promise(resolve => setTimeout(resolve, 1000));
            updateDocument(document.id, { status: 'processing', progress: 50 });
            await new Promise(resolve => setTimeout(resolve, 2000));
            updateDocument(document.id, { progress: 80 });
            await new Promise(resolve => setTimeout(resolve, 1000));
            // Mock extracted data
            const extractedData = {
                pageCount: Math.floor(Math.random() * 50) + 10,
                wordCount: Math.floor(Math.random() * 10000) + 5000,
                confidence: 0.8 + Math.random() * 0.2,
                requirements: [
                    'Technical Approach Section Required',
                    'Past Performance References (minimum 3)',
                    'FedRAMP Compliance Documentation',
                    'Security Clearance Requirements',
                    'Cost Proposal with Labor Categories'
                ],
                deadline: new Date(Date.now() + Math.random() * 90 * 24 * 60 * 60 * 1000),
                estimatedValue: Math.floor(Math.random() * 5000000) + 1000000
            };
            updateDocument(document.id, {
                status: 'completed',
                progress: 100,
                extractedData
            });
            toast({
                title: 'Document processed',
                description: `${document.name} has been successfully analyzed`,
                status: 'success',
                duration: 3000,
                isClosable: true
            });
        }
        catch (error) {
            updateDocument(document.id, {
                status: 'error',
                error: 'Failed to process document'
            });
            toast({
                title: 'Processing failed',
                description: `Failed to process ${document.name}`,
                status: 'error',
                duration: 5000,
                isClosable: true
            });
        }
    };
    const processAllDocuments = async () => {
        if (documents.length === 0) {
            toast({
                title: 'No documents',
                description: 'Please upload at least one document',
                status: 'warning',
                duration: 3000,
                isClosable: true
            });
            return;
        }
        setIsProcessing(true);
        try {
            // Simulate competitive analysis
            await new Promise(resolve => setTimeout(resolve, 3000));
            const analysisResults = {
                marketIntelligence: {
                    competitorCount: 15,
                    averageWinRate: 0.28,
                    marketSize: 150000000
                },
                recommendations: [
                    'Emphasize AI/ML expertise in technical approach',
                    'Highlight FedRAMP compliance experience',
                    'Include 3+ relevant past performance examples',
                    'Position pricing competitively at market rate'
                ],
                riskFactors: [
                    'High competition in this market segment',
                    'Tight deadline may limit proposal quality',
                    'Technical requirements are complex'
                ]
            };
            onAnalysisComplete?.(analysisResults);
            onDocumentsProcessed?.(documents);
            toast({
                title: 'Analysis complete',
                description: 'All documents have been processed and analyzed',
                status: 'success',
                duration: 5000,
                isClosable: true
            });
        }
        catch (error) {
            toast({
                title: 'Analysis failed',
                description: 'Failed to complete competitive analysis',
                status: 'error',
                duration: 5000,
                isClosable: true
            });
        }
        finally {
            setIsProcessing(false);
        }
    };
    const handleDragOver = (e) => {
        e.preventDefault();
        setDragOver(true);
    };
    const handleDragLeave = (e) => {
        e.preventDefault();
        setDragOver(false);
    };
    const handleDrop = (e) => {
        e.preventDefault();
        setDragOver(false);
        handleFileUpload(e.dataTransfer.files);
    };
    const getStatusIcon = (status) => {
        switch (status) {
            case 'completed': return (0, jsx_runtime_1.jsx)(icons_1.CheckIcon, { color: "green.500" });
            case 'error': return (0, jsx_runtime_1.jsx)(icons_1.WarningIcon, { color: "red.500" });
            case 'processing':
            case 'uploading': return (0, jsx_runtime_1.jsx)(react_2.Spinner, { size: "sm" });
            default: return (0, jsx_runtime_1.jsx)(icons_1.AttachmentIcon, {});
        }
    };
    const formatFileSize = (bytes) => {
        if (bytes === 0)
            return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };
    return ((0, jsx_runtime_1.jsx)(react_2.Box, { className: className, p: 6, children: (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 6, align: "stretch", children: [(0, jsx_runtime_1.jsx)(react_2.Heading, { size: "lg", children: "RFP Document Upload & Analysis" }), (0, jsx_runtime_1.jsxs)(react_2.SimpleGrid, { columns: { base: 1, lg: 2 }, spacing: 6, children: [(0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", children: "File Upload" }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsx)(react_2.VStack, { spacing: 4, children: (0, jsx_runtime_1.jsxs)(react_2.Box, { border: "2px dashed", borderColor: dragOver ? "blue.300" : "gray.300", borderRadius: "md", p: 8, textAlign: "center", bg: dragOver ? "blue.50" : "gray.50", cursor: "pointer", transition: "all 0.2s", onDragOver: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, onClick: () => document.getElementById('file-input')?.click(), children: [(0, jsx_runtime_1.jsx)(icons_1.UploadIcon, { boxSize: 8, color: "gray.400", mb: 2 }), (0, jsx_runtime_1.jsx)(react_2.Text, { fontWeight: "medium", mb: 1, children: "Drop files here or click to browse" }), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "sm", color: "gray.600", children: ["Supports PDF, DOC, DOCX up to ", maxFileSize, "MB"] }), (0, jsx_runtime_1.jsx)("input", { id: "file-input", type: "file", multiple: true, accept: acceptedFormats.map(f => `.${f}`).join(','), style: { display: 'none' }, onChange: (e) => handleFileUpload(e.target.files) })] }) }) })] }), (0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsx)(react_2.Heading, { size: "md", children: "Other Sources" }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { fontSize: "sm", children: "Document URL" }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(react_2.Input, { placeholder: "https://example.com/rfp-document.pdf", value: urlInput, onChange: (e) => setUrlInput(e.target.value), size: "sm" }), (0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", onClick: handleUrlSubmit, isDisabled: !urlInput.trim(), children: "Add" })] })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { fontSize: "sm", children: "Google Drive Link" }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(react_2.Input, { placeholder: "https://drive.google.com/...", value: googleDriveInput, onChange: (e) => setGoogleDriveInput(e.target.value), size: "sm" }), (0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", onClick: handleGoogleDriveSubmit, isDisabled: !googleDriveInput.trim(), children: "Add" })] })] }), (0, jsx_runtime_1.jsxs)(react_2.FormControl, { children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { fontSize: "sm", children: "Paste Text Content" }), (0, jsx_runtime_1.jsx)(react_2.Textarea, { placeholder: "Paste RFP text content here...", value: textInput, onChange: (e) => setTextInput(e.target.value), size: "sm", rows: 3 }), (0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", onClick: handleTextSubmit, isDisabled: !textInput.trim(), mt: 2, width: "full", children: "Add Text Content" })] })] }) })] })] }), documents.length > 0 && ((0, jsx_runtime_1.jsxs)(react_2.Card, { children: [(0, jsx_runtime_1.jsx)(react_2.CardHeader, { children: (0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", children: [(0, jsx_runtime_1.jsxs)(react_2.Heading, { size: "md", children: ["Uploaded Documents (", documents.length, ")"] }), (0, jsx_runtime_1.jsx)(react_2.Button, { colorScheme: "blue", onClick: processAllDocuments, isLoading: isProcessing, loadingText: "Analyzing...", isDisabled: documents.some(doc => doc.status === 'uploading' || doc.status === 'processing'), children: "Start AI Analysis" })] }) }), (0, jsx_runtime_1.jsx)(react_2.CardBody, { children: (0, jsx_runtime_1.jsx)(react_2.VStack, { spacing: 3, align: "stretch", children: documents.map((doc) => ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, border: "1px", borderColor: "gray.200", borderRadius: "md", children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", mb: 2, children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [getStatusIcon(doc.status), (0, jsx_runtime_1.jsxs)(react_2.VStack, { align: "start", spacing: 0, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontWeight: "medium", fontSize: "sm", children: doc.name }), doc.size && ((0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "xs", color: "gray.600", children: [formatFileSize(doc.size), " \u2022 ", doc.type.toUpperCase()] }))] })] }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: doc.status === 'completed' ? 'green' :
                                                                doc.status === 'error' ? 'red' :
                                                                    doc.status === 'processing' || doc.status === 'uploading' ? 'blue' :
                                                                        'gray', children: doc.status.replace('-', ' ').toUpperCase() }), doc.url && ((0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: "Open external link", children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Open link", icon: (0, jsx_runtime_1.jsx)(icons_1.ExternalLinkIcon, {}), size: "sm", variant: "ghost", onClick: () => window.open(doc.url, '_blank') }) })), (0, jsx_runtime_1.jsx)(react_2.IconButton, { "aria-label": "Remove document", icon: (0, jsx_runtime_1.jsx)(icons_1.DeleteIcon, {}), size: "sm", variant: "ghost", colorScheme: "red", onClick: () => removeDocument(doc.id) })] })] }), (doc.status === 'uploading' || doc.status === 'processing') && ((0, jsx_runtime_1.jsx)(react_2.Progress, { value: doc.progress, size: "sm", colorScheme: "blue" })), doc.status === 'error' && doc.error && ((0, jsx_runtime_1.jsxs)(react_2.Alert, { status: "error", size: "sm", children: [(0, jsx_runtime_1.jsx)(react_2.AlertIcon, {}), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { fontSize: "sm", children: doc.error })] })), doc.status === 'completed' && doc.extractedData && ((0, jsx_runtime_1.jsxs)(react_2.Box, { mt: 3, p: 3, bg: "green.50", borderRadius: "md", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", fontWeight: "medium", mb: 2, children: "Extracted Information:" }), (0, jsx_runtime_1.jsxs)(react_2.SimpleGrid, { columns: { base: 1, md: 3 }, spacing: 2, children: [(0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "xs", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Pages:" }), " ", doc.extractedData.pageCount] }), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "xs", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Words:" }), " ", doc.extractedData.wordCount.toLocaleString()] }), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "xs", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Confidence:" }), " ", (doc.extractedData.confidence * 100).toFixed(0), "%"] })] }), doc.extractedData.requirements.length > 0 && ((0, jsx_runtime_1.jsxs)(react_2.Box, { mt: 2, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "xs", fontWeight: "medium", children: "Key Requirements:" }), (0, jsx_runtime_1.jsx)(react_2.List, { spacing: 1, fontSize: "xs", children: doc.extractedData.requirements.slice(0, 3).map((req, idx) => ((0, jsx_runtime_1.jsxs)(react_2.ListItem, { children: [(0, jsx_runtime_1.jsx)(react_2.ListIcon, { as: icons_1.CheckIcon, color: "green.500" }), req] }, idx))) })] }))] }))] }, doc.id))) }) })] })), documents.length === 0 && ((0, jsx_runtime_1.jsxs)(react_2.Alert, { status: "info", children: [(0, jsx_runtime_1.jsx)(react_2.AlertIcon, {}), (0, jsx_runtime_1.jsxs)(react_2.Box, { children: [(0, jsx_runtime_1.jsx)(react_2.AlertTitle, { children: "Get Started" }), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { children: "Upload RFP solicitation documents to begin AI-powered analysis and content generation. The system will extract requirements, analyze competitors, and help generate winning responses." })] })] }))] }) }));
};
exports.RFPDocumentUpload = RFPDocumentUpload;
exports.default = exports.RFPDocumentUpload;
//# sourceMappingURL=RFPDocumentUpload.js.map