import React, { useState, useRef, useCallback, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Progress } from '@/components/ui/progress'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; import { Checkbox } from '@/components/ui/checkbox'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Upload, FileArchive, AlertCircle, FileText, Trash2, FolderOpen, CheckSquare, Square, AlertTriangle } from 'lucide-react'; import { useProjects } from '@/hooks/useProjects'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { cn } from '@/lib/utils'; import JSZip from 'jszip'; interface ProjectInfo { id: string; name: string; path: string; files: string[]; isConflict: boolean; selected: boolean; } interface ProjectImportDialogProps { mode?: 'single' | 'bulk'; onImport: (data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] }, overwrite: boolean) => Promise; disabled?: boolean; className?: string; open?: boolean; onOpenChange?: (open: boolean) => void; } export function ProjectImportDialog({ mode = 'single', onImport, disabled = false, className, open, onOpenChange }: ProjectImportDialogProps) { // Use controlled state if props are provided, otherwise use internal state const [internalIsOpen, setInternalIsOpen] = useState(false); const isOpen = open !== undefined ? open : internalIsOpen; const setIsOpen = onOpenChange || setInternalIsOpen; const [selectedFile, setSelectedFile] = useState(null); const [generatedId, setGeneratedId] = useState(''); const [discoveredProjects, setDiscoveredProjects] = useState([]); const [isAnalyzing, setIsAnalyzing] = useState(false); const [isImporting, setIsImporting] = useState(false); const [importProgress, setImportProgress] = useState(0); const [error, setError] = useState(null); const [isDragOver, setIsDragOver] = useState(false); const [showOverwriteDialog, setShowOverwriteDialog] = useState(false); const [zipData, setZipData] = useState(null); const fileInputRef = useRef(null); const { data: existingProjects = [] } = useProjects(); const projectsManager = useProjectsManager(); // Analyze ZIP for bulk import const analyzeZipForProjects = useCallback(async (zip: JSZip): Promise => { const projects: ProjectInfo[] = []; const projectPaths = new Set(); // Find all potential project directories for (const [path] of Object.entries(zip.files)) { const pathParts = path.split('/').filter(part => part !== ''); // Skip files in root directory - we're looking for project directories if (pathParts.length < 2) continue; // Check if this looks like a project indicator file if (isProjectIndicator(path)) { let projectPath: string; // If structure is projects/project-name/file, extract project-name if (pathParts[0] === 'projects' && pathParts.length >= 3) { projectPath = `projects/${pathParts[1]}`; } else { // Otherwise, assume first directory is the project projectPath = pathParts[0]; } projectPaths.add(projectPath); } } // For each discovered project path, gather information for (const projectPath of projectPaths) { const files: string[] = []; // Collect all files in this project directory for (const [path, zipEntry] of Object.entries(zip.files)) { if (path.startsWith(projectPath + '/') && !zipEntry.dir) { const relativePath = path.substring(projectPath.length + 1); files.push(relativePath); } } // Generate project ID and name from directory path let id: string; let name: string; if (projectPath.startsWith('projects/')) { const projectName = projectPath.substring('projects/'.length); id = projectName .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); name = projectName; } else { id = projectPath .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); name = projectPath; } // Skip if no files found (empty directory) if (files.length === 0) continue; // Check if this project conflicts with existing projects const isConflict = existingProjects.some(existing => existing.id === id); projects.push({ id, name, path: projectPath, files, isConflict, selected: !isConflict, // Auto-select non-conflicting projects }); } return projects; }, [existingProjects]); // Handle file selection const handleFileSelect = useCallback(async (file: File) => { // Only accept zip files if (!file.name.toLowerCase().endsWith('.zip')) { setError('Please select a ZIP file'); return; } setSelectedFile(file); setError(null); setGeneratedId(''); // Auto-generate ID from file name for single mode if (mode === 'single') { const baseName = file.name.replace(/\.zip$/i, ''); const id = baseName .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); setGeneratedId(id); } // For bulk mode, analyze the ZIP to discover projects if (mode === 'bulk') { setIsAnalyzing(true); setDiscoveredProjects([]); try { const arrayBuffer = await file.arrayBuffer(); const zip = await JSZip.loadAsync(arrayBuffer); setZipData(zip); const projects = await analyzeZipForProjects(zip); setDiscoveredProjects(projects); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to analyze ZIP file'); } finally { setIsAnalyzing(false); } } }, [mode, analyzeZipForProjects]); const isProjectIndicator = (path: string): boolean => { const indicators = [ 'package.json', 'index.html', 'src/', 'public/', 'tsconfig.json', 'vite.config.', 'webpack.config.', 'README.md', '.git/', ]; return indicators.some(indicator => path.includes('/' + indicator)); }; // Check for existing project when generated ID changes (single mode) useEffect(() => { if (mode === 'single' && generatedId && existingProjects.length > 0) { const existing = existingProjects.find(project => project.id === generatedId); if (existing) { setError(`A project with ID "${generatedId}" already exists. You can choose to overwrite it.`); } else { setError(null); } } }, [generatedId, existingProjects, mode]); // Drag and drop handlers const handleDragOver = useCallback((e: React.DragEvent) => { e.preventDefault(); setIsDragOver(true); }, []); const handleDragLeave = useCallback((e: React.DragEvent) => { e.preventDefault(); setIsDragOver(false); }, []); const handleDrop = useCallback((e: React.DragEvent) => { e.preventDefault(); setIsDragOver(false); const files = Array.from(e.dataTransfer.files); if (files.length > 0) { handleFileSelect(files[0]); } }, [handleFileSelect]); const handleClickUpload = () => { fileInputRef.current?.click(); }; const handleFileRemove = () => { setSelectedFile(null); setGeneratedId(''); setDiscoveredProjects([]); setZipData(null); setError(null); }; // Bulk import project selection handlers const handleProjectToggle = (projectId: string, checked: boolean) => { setDiscoveredProjects(prev => prev.map(project => project.id === projectId ? { ...project, selected: checked } : project ) ); }; const handleSelectAll = () => { setDiscoveredProjects(prev => prev.map(project => ({ ...project, selected: true })) ); }; const handleDeselectAll = () => { setDiscoveredProjects(prev => prev.map(project => ({ ...project, selected: false })) ); }; const selectedProjects = discoveredProjects.filter(project => project.selected); const conflictingProjects = selectedProjects.filter(project => project.isConflict); const handleImport = async (overwrite = false) => { if (!selectedFile) return; setIsImporting(true); setImportProgress(0); setError(null); try { if (mode === 'single') { // Single project import const progressInterval = setInterval(() => { setImportProgress(prev => Math.min(prev + 10, 90)); }, 200); await onImport({ file: selectedFile, projectId: generatedId }, overwrite); clearInterval(progressInterval); setImportProgress(100); } else { // Bulk project import const projectsToImport = await Promise.all( selectedProjects.map(async (project) => { const files = await projectsManager.extractFilesFromZip(zipData!, project.path); return { id: project.id, files, }; }) ); const progressInterval = setInterval(() => { setImportProgress(prev => Math.min(prev + 5, 90)); }, 100); await onImport({ projects: projectsToImport }, overwrite); clearInterval(progressInterval); setImportProgress(100); } // Close dialog and reset state immediately setIsOpen(false); handleFileRemove(); setImportProgress(0); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to import projects'); setImportProgress(0); } finally { setIsImporting(false); } }; const handleImportWithOverwriteCheck = async () => { if (mode === 'single') { // For single mode, check if project exists const existingProject = existingProjects.find(project => project.id === generatedId); if (existingProject) { setShowOverwriteDialog(true); } else { await handleImport(false); } } else { // For bulk mode, check for conflicts if (conflictingProjects.length > 0) { setShowOverwriteDialog(true); } else { await handleImport(false); } } }; const confirmOverwrite = async () => { setShowOverwriteDialog(false); await handleImport(true); }; const handleClose = () => { if (!isImporting && !isAnalyzing) { setIsOpen(false); handleFileRemove(); setImportProgress(0); } }; // Only render DialogTrigger if this component is being used in uncontrolled mode const isControlled = open !== undefined && onOpenChange !== undefined; const canImport = mode === 'single' ? selectedFile && generatedId : selectedProjects.length > 0; return ( <> {!isControlled && ( )} {mode === 'single' ? 'Import Project from ZIP' : 'Import Multiple Projects'} {mode === 'single' ? 'Upload a ZIP file containing your project source code to import it into Shakespeare.' : 'Upload a ZIP file containing multiple projects to import them into Shakespeare.' }
{!isImporting && !isAnalyzing && ( <> {/* Drag and Drop Area */}
{ const files = e.target.files; if (files && files.length > 0) { handleFileSelect(files[0]); } }} accept=".zip" className="hidden" disabled={isImporting || isAnalyzing} />
{selectedFile ? ( ) : ( )}
{selectedFile ? (

{selectedFile.name}

{(selectedFile.size / 1024 / 1024).toFixed(2)} MB

) : (

Drop your ZIP file here or click to browse

{mode === 'single' ? 'Supports ZIP files up to 50MB' : 'Supports ZIP files containing exported Shakespeare projects' }

)}
{/* Error Display */} {error && (
{error}
)} {/* Project List (Bulk Mode Only) */} {mode === 'bulk' && discoveredProjects.length > 0 && (

Found {discoveredProjects.length} project{discoveredProjects.length !== 1 ? 's' : ''}

{discoveredProjects.map((project) => (
handleProjectToggle(project.id, checked as boolean)} className="mt-1" />
{project.name} {project.isConflict && (
Conflict
)}
{project.isConflict && (
Conflict - Will overwrite existing project
)}

{project.files.length} file{project.files.length !== 1 ? 's' : ''} {project.isConflict && • Will overwrite existing project}

))}
)} {/* Import Button */} {selectedFile && (mode === 'single' || discoveredProjects.length > 0) && (
)} )} {/* Analysis Progress (Bulk Mode Only) */} {mode === 'bulk' && isAnalyzing && (
Analyzing ZIP file...

Discovering projects and checking for conflicts...

)} {/* Import Progress */} {isImporting && (
{mode === 'single' ? 'Importing project...' : `Importing ${selectedProjects.length} project${selectedProjects.length !== 1 ? 's' : ''}...`}

Extracting files and setting up projects...

)} {/* Success State */} {!isImporting && !isAnalyzing && importProgress === 100 && (
{mode === 'single' ? 'Project imported successfully!' : 'Projects imported successfully!'}
)}
{/* Overwrite Confirmation Dialog */} {mode === 'single' ? 'Overwrite Existing Project' : 'Overwrite Existing Projects'} {mode === 'single' ? ( <>

A project with ID "{generatedId}" already exists. Overwriting it will:

  • Delete all existing files in project
  • Replace them with files from the ZIP archive
  • Preserve Git history if it exists
  • Keep AI chat history and session data
) : ( <>

You have selected {conflictingProjects.length} project{conflictingProjects.length !== 1 ? 's' : ''} that already exist:

    {conflictingProjects.map((project) => (
  • {project.name} (ID: {project.id})
  • ))}

Overwriting will:

  • Delete all existing files in these projects
  • Replace them with files from the ZIP archive
  • Preserve Git history if it exists
  • Keep AI chat history and session data
)}

This action cannot be undone. Are you sure you want to continue?

Cancel Yes, {mode === 'single' ? 'Overwrite Project' : 'Overwrite Projects'}
); }