import React, { useState, useRef } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
    Image,
    Upload,
    Trash2,
    X,
    Star,
    Download,
    Eye,
    MoreVertical,
    GripVertical,
    ChevronLeft,
    ChevronRight,
    Calendar,
    FileText,
    Loader2,
    ImagePlus,
    Share2,
    AlertCircle,
} from 'lucide-react';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, rectSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
    Dialog,
    DialogContent,
} from '@/components/ui/dialog';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { Checkbox } from '@/components/ui/checkbox';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { usePropertyAttachments } from '@/hooks/useProperties';
import { logPropertyImageAdded } from '@/hooks/usePropertyActivities';
import { cn } from '@/lib/utils';

interface PropertyImagesTabProps {
    propertyId: string;
}

interface ImageAttachment {
    id: string;
    file_name: string;
    file_path: string;
    file_size: number;
    mime_type: string;
    created_at: string;
    is_primary?: boolean;
    display_order?: number;
}

// Sortable Image Item Component
function SortableImageItem({
    image,
    selected,
    onSelect,
    onDelete,
    onSetPrimary,
    onPreview,
    isPrimary,
    getImageUrl,
    index,
}: {
    image: ImageAttachment;
    selected: boolean;
    onSelect: (id: string) => void;
    onDelete: (id: string) => void;
    onSetPrimary: (id: string) => void;
    onPreview: (index: number) => void;
    isPrimary: boolean;
    getImageUrl: (path: string) => string;
    index: number;
}) {
    const [imageLoaded, setImageLoaded] = useState(false);
    const [imageError, setImageError] = useState(false);
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({ id: image.id });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
    };

    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 Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    };

    return (
        <div
            ref={setNodeRef}
            style={style}
            className={cn(
                'relative group aspect-square rounded-xl overflow-hidden border-2 transition-all',
                selected ? 'border-primary ring-2 ring-primary/20' : 'border-border hover:border-primary/50',
                isDragging && 'z-50 shadow-2xl scale-105'
            )}
        >
            {/* Drag Handle */}
            <TooltipProvider>
                <Tooltip>
                    <TooltipTrigger asChild>
                        <div
                            {...attributes}
                            {...listeners}
                            className="absolute top-2 left-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab active:cursor-grabbing"
                        >
                            <div className="bg-black/70 backdrop-blur-sm rounded-lg p-1.5 hover:bg-black/80 transition-colors">
                                <GripVertical className="h-4 w-4 text-white" />
                            </div>
                        </div>
                    </TooltipTrigger>
                    <TooltipContent>
                        <p>Drag to reorder</p>
                    </TooltipContent>
                </Tooltip>
            </TooltipProvider>

            {/* Selection Checkbox */}
            <div className="absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity">
                <Checkbox
                    checked={selected}
                    onCheckedChange={() => onSelect(image.id)}
                    className="bg-white border-2 shadow-lg"
                    onClick={(e) => e.stopPropagation()}
                />
            </div>

            {/* Primary Badge */}
            {isPrimary && (
                <div className="absolute top-2 left-1/2 -translate-x-1/2 z-10">
                    <Badge className="bg-amber-500 text-white border-0 gap-1 shadow-lg">
                        <Star className="h-3 w-3 fill-white" />
                        Featured
                    </Badge>
                </div>
            )}

            {/* Image Loading State */}
            {!imageLoaded && !imageError && (
                <div className="absolute inset-0 bg-muted animate-pulse flex items-center justify-center">
                    <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                </div>
            )}

            {/* Image Error State */}
            {imageError && (
                <div className="absolute inset-0 bg-muted flex flex-col items-center justify-center gap-2">
                    <AlertCircle className="h-8 w-8 text-muted-foreground" />
                    <p className="text-xs text-muted-foreground">Failed to load</p>
                </div>
            )}

            {/* Image */}
            <img
                src={getImageUrl(image.file_path)}
                alt={image.file_name}
                className={cn(
                    'w-full h-full object-cover cursor-pointer transition-all duration-300',
                    imageLoaded ? 'opacity-100' : 'opacity-0',
                    'group-hover:scale-110'
                )}
                loading="lazy"
                onLoad={() => setImageLoaded(true)}
                onError={() => setImageError(true)}
                onClick={() => onPreview(index)}
            />

            {/* Hover Overlay */}
            <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity">
                <div className="absolute bottom-0 left-0 right-0 p-3 space-y-2">
                    {/* File Info */}
                    <div className="text-white space-y-1">
                        <p className="text-sm font-medium truncate">{image.file_name}</p>
                        <div className="flex items-center gap-2 text-xs opacity-90">
                            <span>{formatFileSize(image.file_size)}</span>
                            <span>•</span>
                            <span>{format(new Date(image.created_at), 'MMM d, yyyy')}</span>
                        </div>
                    </div>

                    {/* Action Buttons */}
                    <div className="flex items-center gap-2">
                        <Button
                            size="sm"
                            variant="secondary"
                            className="flex-1 h-8 text-xs"
                            onClick={(e) => {
                                e.stopPropagation();
                                onPreview(index);
                            }}
                        >
                            <Eye className="h-3 w-3 mr-1" />
                            View
                        </Button>
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
                                <Button size="sm" variant="secondary" className="h-8 w-8 p-0">
                                    <MoreVertical className="h-3 w-3" />
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                                <DropdownMenuItem onClick={(e) => {
                                    e.stopPropagation();
                                    onSetPrimary(image.id);
                                }}>
                                    <Star className={cn("h-4 w-4 mr-2", isPrimary && "fill-amber-500 text-amber-500")} />
                                    {isPrimary ? 'Remove Featured' : 'Set as Featured'}
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        const link = document.createElement('a');
                                        link.href = getImageUrl(image.file_path);
                                        link.download = image.file_name;
                                        link.click();
                                        toast.success('Download started');
                                    }}
                                >
                                    <Download className="h-4 w-4 mr-2" />
                                    Download
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        navigator.clipboard.writeText(getImageUrl(image.file_path));
                                        toast.success('Link copied to clipboard');
                                    }}
                                >
                                    <Share2 className="h-4 w-4 mr-2" />
                                    Copy Link
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                    className="text-destructive focus:text-destructive"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        onDelete(image.id);
                                    }}
                                >
                                    <Trash2 className="h-4 w-4 mr-2" />
                                    Delete
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    </div>
                </div>
            </div>
        </div>
    );
}

export function PropertyImagesTab({ propertyId }: PropertyImagesTabProps) {
    const { user } = useAuth();
    const queryClient = useQueryClient();
    const fileInputRef = useRef<HTMLInputElement>(null);
    const { data: images = [], isLoading } = usePropertyAttachments(propertyId, 'image');

    const [orderedImages, setOrderedImages] = useState<ImageAttachment[]>([]);
    const [selectedImages, setSelectedImages] = useState<Set<string>>(new Set());
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [bulkDeleteDialogOpen, setBulkDeleteDialogOpen] = useState(false);
    const [imageToDelete, setImageToDelete] = useState<string | null>(null);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewIndex, setPreviewIndex] = useState(0);
    const [primaryImageId, setPrimaryImageId] = useState<string | null>(null);

    // Initialize ordered images
    React.useEffect(() => {
        if (images.length > 0) {
            const sorted = [...images].sort((a, b) => {
                const orderA = a.display_order ?? 999;
                const orderB = b.display_order ?? 999;
                if (orderA !== orderB) return orderA - orderB;
                // Fallback to creation date
                return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
            });
            setOrderedImages(sorted);
            const primary = sorted.find(img => img.is_primary);
            if (primary) setPrimaryImageId(primary.id);
        } else {
            setOrderedImages([]);
            setPrimaryImageId(null);
        }
    }, [images]);

    // Drag and Drop sensors
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 8,
            },
        }),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    );

    const uploadMutation = useMutation({
        mutationFn: async (file: File) => {
            if (!user) throw new Error('Not authenticated');

            // Validate file size (max 10MB)
            if (file.size > 10 * 1024 * 1024) {
                throw new Error('File size must be less than 10MB');
            }

            // Validate file type
            if (!file.type.startsWith('image/')) {
                throw new Error('File must be an image');
            }

            const fileExt = file.name.split('.').pop();
            const fileName = `${propertyId}/${Date.now()}-${Math.random().toString(36).substring(7)}.${fileExt}`;
            const filePath = `property-images/${fileName}`;

            // Upload to storage
            const { error: uploadError } = await supabase.storage
                .from('attachments')
                .upload(filePath, file, {
                    cacheControl: '3600',
                    upsert: false
                });

            if (uploadError) throw uploadError;

            // Get public URL
            const { data: { publicUrl } } = supabase.storage
                .from('attachments')
                .getPublicUrl(filePath);

            // Create attachment record
            const { error: insertError } = await supabase
                .from('attachments')
                .insert({
                    entity_type: 'property',
                    entity_id: propertyId,
                    property_id: propertyId,
                    file_name: file.name,
                    file_path: filePath,
                    file_size: file.size,
                    mime_type: file.type,
                    category: 'image',
                    uploaded_by: user.id,
                    display_order: images.length,
                    is_primary: images.length === 0, // First image is primary by default
                });

            if (insertError) throw insertError;

            return { publicUrl, fileName: file.name };
        },
        onSuccess: (data) => {
            queryClient.invalidateQueries({ queryKey: ['property-attachments', propertyId, 'image'] });
            queryClient.invalidateQueries({ queryKey: ['property-activities', propertyId] });

            if (user?.id) {
                logPropertyImageAdded(user.id, propertyId, data.fileName);
            }
        },
        onError: (error: Error) => {
            toast.error('Upload failed', {
                description: error.message,
            });
        },
    });

    const deleteMutation = useMutation({
        mutationFn: async (id: string) => {
            const attachment = images.find(img => img.id === id);
            if (!attachment) throw new Error('Image not found');

            // Delete from storage
            const { error: storageError } = await supabase.storage
                .from('attachments')
                .remove([attachment.file_path]);

            if (storageError) throw storageError;

            // Delete record
            const { error: deleteError } = await supabase
                .from('attachments')
                .delete()
                .eq('id', id);

            if (deleteError) throw deleteError;
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['property-attachments', propertyId, 'image'] });
            toast.success('Image deleted successfully');
        },
        onError: (error: Error) => {
            toast.error('Delete failed', {
                description: error.message,
            });
        },
    });

    const updateOrderMutation = useMutation({
        mutationFn: async (images: ImageAttachment[]) => {
            const updates = images.map((img, index) => ({
                id: img.id,
                display_order: index,
            }));

            for (const update of updates) {
                const { error } = await supabase
                    .from('attachments')
                    .update({ display_order: update.display_order })
                    .eq('id', update.id);

                if (error) throw error;
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['property-attachments', propertyId, 'image'] });
            toast.success('Image order updated');
        },
        onError: (error: Error) => {
            toast.error('Failed to update order', {
                description: error.message,
            });
        }
    });

    const setPrimaryMutation = useMutation({
        mutationFn: async (imageId: string) => {
            // Remove primary flag from all images first
            const { error: clearError } = await supabase
                .from('attachments')
                .update({ is_primary: false })
                .eq('property_id', propertyId)
                .eq('category', 'image');

            if (clearError) throw clearError;

            // Set new primary image
            const { error: setError } = await supabase
                .from('attachments')
                .update({ is_primary: true })
                .eq('id', imageId);

            if (setError) throw setError;

            return imageId;
        },
        onSuccess: (imageId) => {
            queryClient.invalidateQueries({ queryKey: ['property-attachments', propertyId, 'image'] });
            setPrimaryImageId(imageId);
            toast.success('Featured image updated');
        },
        onError: (error: Error) => {
            toast.error('Failed to set featured image', {
                description: error.message,
            });
        }
    });

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = e.target.files;
        if (!files || files.length === 0) return;

        const validFiles = Array.from(files).filter(file => {
            if (!file.type.startsWith('image/')) {
                toast.error(`${file.name} is not an image`);
                return false;
            }
            if (file.size > 10 * 1024 * 1024) {
                toast.error(`${file.name} is too large (max 10MB)`);
                return false;
            }
            return true;
        });

        if (validFiles.length === 0) return;

        // Upload files sequentially to avoid overwhelming the server
        let successCount = 0;
        let errorCount = 0;

        for (const file of validFiles) {
            try {
                await uploadMutation.mutateAsync(file);
                successCount++;
            } catch (error) {
                errorCount++;
            }
        }

        if (successCount > 0) {
            toast.success(`${successCount} image${successCount > 1 ? 's' : ''} uploaded successfully`);
        }
        if (errorCount > 0) {
            toast.error(`${errorCount} image${errorCount > 1 ? 's' : ''} failed to upload`);
        }

        // Reset file input
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    const handleDragEnd = (event: any) => {
        const { active, over } = event;

        if (!over || active.id === over.id) return;

        setOrderedImages((items) => {
            const oldIndex = items.findIndex(i => i.id === active.id);
            const newIndex = items.findIndex(i => i.id === over.id);

            if (oldIndex === -1 || newIndex === -1) return items;

            const newOrder = arrayMove(items, oldIndex, newIndex);
            updateOrderMutation.mutate(newOrder);
            return newOrder;
        });
    };

    const handleDelete = (id: string) => {
        setImageToDelete(id);
        setDeleteDialogOpen(true);
    };

    const handleBulkDelete = async () => {
        const promises = Array.from(selectedImages).map(id => deleteMutation.mutateAsync(id));

        try {
            await Promise.all(promises);
            toast.success(`${selectedImages.size} image${selectedImages.size > 1 ? 's' : ''} deleted successfully`);
            setSelectedImages(new Set());
            setBulkDeleteDialogOpen(false);
        } catch (error) {
            toast.error('Failed to delete some images');
        }
    };

    const confirmDelete = async () => {
        if (imageToDelete) {
            await deleteMutation.mutateAsync(imageToDelete);
            setDeleteDialogOpen(false);
            setImageToDelete(null);
        }
    };

    const toggleSelectAll = () => {
        if (selectedImages.size === orderedImages.length) {
            setSelectedImages(new Set());
        } else {
            setSelectedImages(new Set(orderedImages.map(img => img.id)));
        }
    };

    const toggleSelect = (id: string) => {
        setSelectedImages(prev => {
            const next = new Set(prev);
            if (next.has(id)) {
                next.delete(id);
            } else {
                next.add(id);
            }
            return next;
        });
    };

    const getImageUrl = (filePath: string) => {
        const { data: { publicUrl } } = supabase.storage
            .from('attachments')
            .getPublicUrl(filePath);
        return publicUrl;
    };

    const navigatePreview = (direction: 'prev' | 'next') => {
        if (direction === 'prev') {
            setPreviewIndex(prev => (prev - 1 + orderedImages.length) % orderedImages.length);
        } else {
            setPreviewIndex(prev => (prev + 1) % orderedImages.length);
        }
    };

    // Keyboard navigation for preview
    React.useEffect(() => {
        if (!previewOpen) return;

        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'ArrowLeft') navigatePreview('prev');
            if (e.key === 'ArrowRight') navigatePreview('next');
            if (e.key === 'Escape') setPreviewOpen(false);
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [previewOpen]);

    return (
        <>
            <Card>
                <CardHeader>
                    <div className="flex items-center justify-between flex-wrap gap-4">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-primary/10 rounded-lg">
                                <Image className="h-5 w-5 text-primary" />
                            </div>
                            <div>
                                <CardTitle className="text-xl">Property Images</CardTitle>
                                <p className="text-sm text-muted-foreground mt-1">
                                    {images.length} {images.length === 1 ? 'image' : 'images'} uploaded
                                </p>
                            </div>
                        </div>

                        <div className="flex items-center gap-2 flex-wrap">
                            {selectedImages.size > 0 && (
                                <div className="flex items-center gap-2">
                                    <Badge variant="secondary" className="gap-1">
                                        {selectedImages.size} selected
                                    </Badge>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => setBulkDeleteDialogOpen(true)}
                                        disabled={deleteMutation.isPending}
                                        className="text-destructive hover:text-destructive"
                                    >
                                        <Trash2 className="h-4 w-4 mr-1" />
                                        Delete
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={() => setSelectedImages(new Set())}
                                    >
                                        <X className="h-4 w-4" />
                                    </Button>
                                </div>
                            )}

                            <Button
                                onClick={() => fileInputRef.current?.click()}
                                disabled={uploadMutation.isPending}
                                className="gap-2"
                            >
                                {uploadMutation.isPending ? (
                                    <>
                                        <Loader2 className="h-4 w-4 animate-spin" />
                                        Uploading...
                                    </>
                                ) : (
                                    <>
                                        <ImagePlus className="h-4 w-4" />
                                        Upload Images
                                    </>
                                )}
                            </Button>
                            <input
                                ref={fileInputRef}
                                type="file"
                                accept="image/*"
                                multiple
                                onChange={handleFileChange}
                                className="hidden"
                            />
                        </div>
                    </div>
                </CardHeader>

                <CardContent>
                    {isLoading ? (
                        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                            {[...Array(8)].map((_, i) => (
                                <Skeleton key={i} className="aspect-square rounded-xl" />
                            ))}
                        </div>
                    ) : orderedImages.length === 0 ? (
                        <div className="flex flex-col items-center justify-center py-16 text-center border-2 border-dashed rounded-xl bg-muted/20">
                            <div className="p-4 bg-primary/10 rounded-full mb-4">
                                <ImagePlus className="h-10 w-10 text-primary" />
                            </div>
                            <h3 className="text-lg font-semibold mb-2">No images yet</h3>
                            <p className="text-muted-foreground mb-6 max-w-sm">
                                Upload photos of this property to showcase it to potential buyers or renters
                            </p>
                            <Button onClick={() => fileInputRef.current?.click()}>
                                <Upload className="mr-2 h-4 w-4" />
                                Upload Your First Image
                            </Button>
                        </div>
                    ) : (
                        <>
                            <div className="flex items-center justify-between mb-4 pb-3 border-b">
                                <div className="flex items-center gap-2">
                                    <Checkbox
                                        checked={selectedImages.size === orderedImages.length}
                                        onCheckedChange={toggleSelectAll}
                                    />
                                    <span className="text-sm text-muted-foreground">
                                        {selectedImages.size === orderedImages.length ? 'Deselect all' : 'Select all'}
                                    </span>
                                </div>
                                <p className="text-sm text-muted-foreground flex items-center gap-2">
                                    <GripVertical className="h-4 w-4" />
                                    Drag images to reorder
                                </p>
                            </div>

                            <DndContext
                                sensors={sensors}
                                collisionDetection={closestCenter}
                                onDragEnd={handleDragEnd}
                            >
                                <SortableContext
                                    items={orderedImages.map(img => img.id)}
                                    strategy={rectSortingStrategy}
                                >
                                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                                        {orderedImages.map((image, index) => (
                                            <SortableImageItem
                                                key={image.id}
                                                image={image}
                                                index={index}
                                                selected={selectedImages.has(image.id)}
                                                onSelect={toggleSelect}
                                                onDelete={handleDelete}
                                                onSetPrimary={(id) => {
                                                    setPrimaryMutation.mutate(id);
                                                }}
                                                onPreview={(idx) => {
                                                    setPreviewIndex(idx);
                                                    setPreviewOpen(true);
                                                }}
                                                isPrimary={image.id === primaryImageId}
                                                getImageUrl={getImageUrl}
                                            />
                                        ))}
                                    </div>
                                </SortableContext>
                            </DndContext>
                        </>
                    )}
                </CardContent>
            </Card>

            {/* Enhanced Image Preview Dialog */}
            <Dialog open={previewOpen} onOpenChange={setPreviewOpen}>
                <DialogContent className="max-w-[95vw] max-h-[95vh] p-0 overflow-hidden">
                    <div className="relative w-full h-[90vh] bg-black">
                        {/* Close Button */}
                        <Button
                            size="icon"
                            variant="ghost"
                            className="absolute top-4 right-4 z-50 text-white hover:bg-white/20"
                            onClick={() => setPreviewOpen(false)}
                        >
                            <X className="h-5 w-5" />
                        </Button>

                        {/* Navigation */}
                        {orderedImages.length > 1 && (
                            <>
                                <Button
                                    size="icon"
                                    variant="ghost"
                                    className="absolute left-4 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12"
                                    onClick={() => navigatePreview('prev')}
                                >
                                    <ChevronLeft className="h-8 w-8" />
                                </Button>
                                <Button
                                    size="icon"
                                    variant="ghost"
                                    className="absolute right-4 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12"
                                    onClick={() => navigatePreview('next')}
                                >
                                    <ChevronRight className="h-8 w-8" />
                                </Button>
                            </>
                        )}

                        {/* Image Counter */}
                        <div className="absolute top-4 left-4 z-50 bg-black/70 backdrop-blur-sm text-white px-3 py-1.5 rounded-lg text-sm font-medium">
                            {previewIndex + 1} / {orderedImages.length}
                        </div>

                        {/* Featured Badge */}
                        {orderedImages[previewIndex]?.id === primaryImageId && (
                            <div className="absolute top-4 left-1/2 -translate-x-1/2 z-50">
                                <Badge className="bg-amber-500 text-white border-0 gap-1">
                                    <Star className="h-3 w-3 fill-white" />
                                    Featured Image
                                </Badge>
                            </div>
                        )}

                        {/* Image */}
                        {orderedImages[previewIndex] && (
                            <img
                                src={getImageUrl(orderedImages[previewIndex].file_path)}
                                alt={orderedImages[previewIndex].file_name}
                                className="w-full h-full object-contain"
                            />
                        )}

                        {/* Image Info */}
                        {orderedImages[previewIndex] && (
                            <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 via-black/60 to-transparent p-6 text-white">
                                <div className="flex items-end justify-between gap-4">
                                    <div className="space-y-2 flex-1 min-w-0">
                                        <p className="font-semibold text-lg truncate">
                                            {orderedImages[previewIndex].file_name}
                                        </p>
                                        <div className="flex items-center gap-4 text-sm opacity-90">
                                            <span className="flex items-center gap-1.5">
                                                <Calendar className="h-4 w-4" />
                                                {format(new Date(orderedImages[previewIndex].created_at), 'MMM d, yyyy')}
                                            </span>
                                            <span className="flex items-center gap-1.5">
                                                <FileText className="h-4 w-4" />
                                                {(orderedImages[previewIndex].file_size / 1024).toFixed(0)} KB
                                            </span>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2 flex-shrink-0">
                                        <Button
                                            size="sm"
                                            variant="secondary"
                                            onClick={() => {
                                                navigator.clipboard.writeText(getImageUrl(orderedImages[previewIndex].file_path));
                                                toast.success('Link copied to clipboard');
                                            }}
                                        >
                                            <Share2 className="h-4 w-4 mr-1" />
                                            Share
                                        </Button>
                                        <Button
                                            size="sm"
                                            variant="secondary"
                                            onClick={() => {
                                                const link = document.createElement('a');
                                                link.href = getImageUrl(orderedImages[previewIndex].file_path);
                                                link.download = orderedImages[previewIndex].file_name;
                                                link.click();
                                                toast.success('Download started');
                                            }}
                                        >
                                            <Download className="h-4 w-4 mr-1" />
                                            Download
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                </DialogContent>
            </Dialog>

            {/* Single Delete Confirmation */}
            <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle className="flex items-center gap-2">
                            <AlertCircle className="h-5 w-5 text-destructive" />
                            Delete Image
                        </AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to delete this image? This action cannot be undone and the image will be permanently removed from storage.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={confirmDelete}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            {deleteMutation.isPending ? (
                                <>
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                    Deleting...
                                </>
                            ) : (
                                'Delete Image'
                            )}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Bulk Delete Confirmation */}
            <AlertDialog open={bulkDeleteDialogOpen} onOpenChange={setBulkDeleteDialogOpen}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle className="flex items-center gap-2">
                            <AlertCircle className="h-5 w-5 text-destructive" />
                            Delete {selectedImages.size} Images
                        </AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to delete {selectedImages.size} selected image{selectedImages.size > 1 ? 's' : ''}?
                            This action cannot be undone and all images will be permanently removed from storage.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={handleBulkDelete}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            {deleteMutation.isPending ? (
                                <>
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                    Deleting...
                                </>
                            ) : (
                                `Delete ${selectedImages.size} Image${selectedImages.size > 1 ? 's' : ''}`
                            )}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    );
}