import { UploadFile } from '@/types';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { X, AlertCircle, CheckCircle2, FileText, Upload } from 'lucide-react';
import { FileIcon } from './FileIcon';
import { ScrollArea } from '@/components/ui/scroll-area';
import { formatBytes } from '@/lib/utils'; // Assuming this exists, if not we'll allow standard display

interface UploadPreviewProps {
    files: UploadFile[];
    onRemove: (id: string) => void;
    onUpload: () => void;
    isUploading: boolean;
    onClear: () => void;
}

export function UploadPreview({ files, onRemove, onUpload, isUploading, onClear }: UploadPreviewProps) {
    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 pendingCount = files.filter(f => f.status === 'pending').length;
    const uploadingCount = files.filter(f => f.status === 'uploading').length;
    const errorCount = files.filter(f => f.status === 'error').length;

    // Calculate total progress if uploading
    const totalProgress = uploadingCount > 0
        ? files.reduce((acc, curr) => acc + (curr.status === 'uploading' || curr.status === 'success' ? curr.progress : 0), 0) / (files.length || 1)
        : 0;

    return (
        <div className="flex flex-col h-full max-h-[600px]">
            <div className="flex items-center justify-between p-4 border-b">
                <div>
                    <h3 className="font-semibold text-lg flex items-center gap-2">
                        {isUploading ? 'Uploading Files...' : 'Selected Files'}
                        <span className="text-sm font-normal text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
                            {files.length}
                        </span>
                    </h3>
                    <p className="text-sm text-muted-foreground">
                        {isUploading
                            ? `${uploadingCount} uploading, ${files.filter(f => f.status === 'success').length} completed`
                            : 'Review files before uploading'}
                    </p>
                </div>
                {!isUploading && files.length > 0 && (
                    <Button variant="ghost" size="sm" onClick={onClear} className="text-muted-foreground hover:text-destructive">
                        Clear All
                    </Button>
                )}
            </div>

            <ScrollArea className="flex-1 p-4">
                <div className="space-y-3">
                    {files.map((file) => (
                        <div
                            key={file.id}
                            className="group relative flex items-center gap-4 rounded-lg border p-3 bg-card hover:bg-accent/50 transition-colors"
                        >
                            <div className="relative h-12 w-12 flex-shrink-0 overflow-hidden rounded-md border flex items-center justify-center bg-muted">
                                {file.preview ? (
                                    <img
                                        src={file.preview}
                                        alt={file.file.name}
                                        className="h-full w-full object-cover"
                                    />
                                ) : (
                                    <FileIcon mimeType={file.file.type} className="h-6 w-6" />
                                )}
                            </div>

                            <div className="flex-1 min-w-0 space-y-1">
                                <div className="flex items-center justify-between">
                                    <p className="truncate text-sm font-medium leading-none" title={file.file.name}>
                                        {file.file.name}
                                    </p>
                                    {!isUploading && (
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                                            onClick={() => onRemove(file.id)}
                                        >
                                            <X className="h-4 w-4 text-muted-foreground" />
                                            <span className="sr-only">Remove file</span>
                                        </Button>
                                    )}
                                </div>
                                <div className="flex items-center justify-between text-xs text-muted-foreground">
                                    <span>{formatFileSize(file.file.size)}</span>
                                    {file.status === 'error' && (
                                        <span className="text-destructive font-medium flex items-center gap-1">
                                            <AlertCircle className="h-3 w-3" />
                                            Failed
                                        </span>
                                    )}
                                    {file.status === 'success' && (
                                        <span className="text-green-600 font-medium flex items-center gap-1">
                                            <CheckCircle2 className="h-3 w-3" />
                                            Completed
                                        </span>
                                    )}
                                </div>
                                {['uploading', 'success', 'error'].includes(file.status) && (
                                    <Progress
                                        value={file.status === 'success' ? 100 : file.progress}
                                        className={`h-1.5 mt-2 ${file.status === 'error' ? 'bg-destructive/20' : ''}`}
                                    />
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </ScrollArea>

            <div className="p-4 border-t bg-muted/20">
                <Button
                    className="w-full"
                    size="lg"
                    onClick={onUpload}
                    disabled={isUploading || pendingCount === 0}
                >
                    {isUploading ? (
                        <>Processing Uploads...</>
                    ) : (
                        <>
                            <Upload className="mr-2 h-4 w-4" />
                            Upload {pendingCount} {pendingCount === 1 ? 'File' : 'Files'}
                        </>
                    )}
                </Button>
            </div>
        </div>
    );
}
