import { useState, useCallback, useRef, useEffect, memo } from 'react' import { Button } from '@/components/ui/button' import { Download, X, Edit3, Save, X as XIcon, WrapText } from 'lucide-react' import type { FileInfo } from '@/types/files' import { API_BASE_URL } from '@/config' import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view' const API_BASE = API_BASE_URL const VIRTUALIZATION_THRESHOLD_BYTES = 8_000 interface FilePreviewProps { file: FileInfo hideHeader?: boolean isMobileModal?: boolean onCloseModal?: () => void onFileSaved?: () => void initialLineNumber?: number } export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) { const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview') const [editContent, setEditContent] = useState('') const [isSaving, setIsSaving] = useState(false) const [hasVirtualizedChanges, setHasVirtualizedChanges] = useState(false) const [highlightedLine, setHighlightedLine] = useState(initialLineNumber) const [lineWrap, setLineWrap] = useState(true) const virtualizedRef = useRef(null) const contentRef = useRef(null) const shouldVirtualize = file.size > VIRTUALIZATION_THRESHOLD_BYTES && !file.mimeType?.startsWith('image/') useEffect(() => { if (initialLineNumber && contentRef.current && !shouldVirtualize) { const lineHeight = 20 const scrollPosition = (initialLineNumber - 1) * lineHeight setHighlightedLine(initialLineNumber) setTimeout(() => { contentRef.current?.scrollTo({ top: scrollPosition, behavior: 'smooth' }) }, 100) setTimeout(() => { setHighlightedLine(undefined) }, 3000) } }, [initialLineNumber, shouldVirtualize, file.content]) const formatFileSize = (bytes: number) => { 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] } const formatDate = (date: Date) => { return new Date(date).toLocaleString() } const handleDownload = () => { const link = document.createElement('a') link.href = `${API_BASE}/api/files/${file.path}?download=true` link.download = file.name document.body.appendChild(link) link.click() document.body.removeChild(link) } const decodeBase64 = (base64: string): string => { try { const binaryString = atob(base64) const bytes = new Uint8Array(binaryString.length) for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i) } return new TextDecoder('utf-8').decode(bytes) } catch { throw new Error('Failed to decode base64 content') } } const handleEdit = () => { if (shouldVirtualize) { setViewMode('edit') const event = new CustomEvent('editModeChange', { detail: { isEditing: true } }) window.dispatchEvent(event) return } try { const content = file.content ? decodeBase64(file.content) : '' setEditContent(content) setViewMode('edit') const event = new CustomEvent('editModeChange', { detail: { isEditing: true } }) window.dispatchEvent(event) } catch (err) { console.error('Failed to load content for editing:', err) } } const handleSave = async () => { setIsSaving(true) try { const response = await fetch(`${API_BASE}/api/files/${file.path}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'file', content: editContent }), }) if (!response.ok) { throw new Error(`Save failed: ${response.statusText}`) } setViewMode('preview') const editEvent = new CustomEvent('editModeChange', { detail: { isEditing: false } }) window.dispatchEvent(editEvent) const event = new CustomEvent('fileSaved', { detail: { path: file.path, content: editContent } }) window.dispatchEvent(event) onFileSaved?.() } catch (err) { console.error('Failed to save file:', err) } finally { setIsSaving(false) } } const handleCancel = () => { setEditContent('') setViewMode('preview') setHasVirtualizedChanges(false) const event = new CustomEvent('editModeChange', { detail: { isEditing: false } }) window.dispatchEvent(event) } const handleVirtualizedSaveStateChange = useCallback((hasChanges: boolean) => { setHasVirtualizedChanges(hasChanges) }, []) const handleVirtualizedSave = useCallback(() => { setViewMode('preview') const editEvent = new CustomEvent('editModeChange', { detail: { isEditing: false } }) window.dispatchEvent(editEvent) const event = new CustomEvent('fileSaved', { detail: { path: file.path } }) window.dispatchEvent(event) onFileSaved?.() }, [file.path, onFileSaved]) const isTextFile = file.mimeType?.startsWith('text/') || ['application/json', 'application/xml', 'text/javascript', 'text/typescript'].includes(file.mimeType || '') const renderContent = () => { if (file.mimeType?.startsWith('image/')) { return (
{file.name}
) } if (shouldVirtualize && isTextFile) { return ( ) } if (!file.content) return null if (isTextFile) { if (viewMode === 'edit') { return (