/**
 * Media Gallery Page
 *
 * Allows users to upload and manage images organized into albums.
 * Includes storage quota tracking and bulk operations.
 */

import React, { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  FolderPlus,
  Upload,
  Image as ImageIcon,
  Trash2,
  MoreVertical,
  Edit,
  FolderOpen,
  X,
  Check,
  Copy,
  ExternalLink,
  ChevronLeft,
} from 'lucide-react';
import { Modal, FormInput, Button, Alert, FormTextarea } from '../components/ui';
import {
  Album,
  MediaFile,
  StorageUsage,
  listAlbums,
  listMediaFiles,
  getStorageUsage,
  createAlbum,
  updateAlbum,
  deleteAlbum,
  uploadMediaFile,
  updateMediaFile,
  deleteMediaFile,
  bulkMoveFiles,
  bulkDeleteFiles,
  formatFileSize,
  isAllowedFileType,
  isFileSizeAllowed,
  getAllowedFileTypes,
  MAX_FILE_SIZE,
} from '../api/media';

// ============================================================================
// Storage Usage Bar Component
// ============================================================================

interface StorageUsageBarProps {
  usage: StorageUsage | undefined;
  isLoading: boolean;
}

const StorageUsageBar: React.FC<StorageUsageBarProps> = ({ usage, isLoading }) => {
  if (isLoading || !usage) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 animate-pulse">
        <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/3 mb-2" />
        <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded" />
      </div>
    );
  }

  const percentUsed = usage.percent_used;
  const barColor =
    percentUsed >= 95
      ? 'bg-red-500'
      : percentUsed >= 80
        ? 'bg-yellow-500'
        : 'bg-primary-500';

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
      <div className="flex items-center justify-between mb-2">
        <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
          Storage: {usage.used_display} / {usage.total_display}
        </span>
        <span className="text-sm text-gray-500 dark:text-gray-400">
          {usage.file_count} files
        </span>
      </div>
      <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
        <div
          className={`${barColor} h-2 rounded-full transition-all duration-300`}
          style={{ width: `${Math.min(percentUsed, 100)}%` }}
        />
      </div>
      {percentUsed >= 80 && (
        <p className="text-xs text-yellow-600 dark:text-yellow-400 mt-2">
          {percentUsed >= 95
            ? 'Storage almost full! Delete files or upgrade your plan.'
            : 'Storage usage is getting high.'}
        </p>
      )}
    </div>
  );
};

// ============================================================================
// Album Card Component
// ============================================================================

interface AlbumCardProps {
  album: Album;
  isSelected: boolean;
  onSelect: () => void;
  onEdit: () => void;
  onDelete: () => void;
}

const AlbumCard: React.FC<AlbumCardProps> = ({
  album,
  isSelected,
  onSelect,
  onEdit,
  onDelete,
}) => {
  const [showMenu, setShowMenu] = useState(false);

  return (
    <div
      className={`relative group cursor-pointer rounded-lg border-2 transition-all ${
        isSelected
          ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
          : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
      }`}
      onClick={onSelect}
    >
      <div className="aspect-square bg-gray-100 dark:bg-gray-800 rounded-t-lg overflow-hidden">
        {album.cover_url ? (
          <img
            src={album.cover_url}
            alt={album.name}
            className="w-full h-full object-cover"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <FolderOpen className="w-16 h-16 text-gray-400 dark:text-gray-600" />
          </div>
        )}
      </div>
      <div className="p-3">
        <h3 className="font-medium text-gray-900 dark:text-white truncate">{album.name}</h3>
        <p className="text-sm text-gray-500 dark:text-gray-400">
          {album.file_count} {album.file_count === 1 ? 'file' : 'files'}
        </p>
      </div>

      {/* Menu button */}
      <div className="absolute top-2 right-2">
        <button
          onClick={(e) => {
            e.stopPropagation();
            setShowMenu(!showMenu);
          }}
          className="p-1 rounded-full bg-black/50 text-white opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/70"
        >
          <MoreVertical className="w-4 h-4" />
        </button>
        {showMenu && (
          <div className="absolute right-0 mt-1 w-36 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 z-10">
            <button
              onClick={(e) => {
                e.stopPropagation();
                onEdit();
                setShowMenu(false);
              }}
              className="w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
            >
              <Edit className="w-4 h-4" />
              Edit
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                onDelete();
                setShowMenu(false);
              }}
              className="w-full px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center gap-2"
            >
              <Trash2 className="w-4 h-4" />
              Delete
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

// ============================================================================
// Media Thumbnail Component
// ============================================================================

interface MediaThumbnailProps {
  file: MediaFile;
  isSelected: boolean;
  onSelect: () => void;
  onPreview: () => void;
}

const MediaThumbnail: React.FC<MediaThumbnailProps> = ({
  file,
  isSelected,
  onSelect,
  onPreview,
}) => {
  return (
    <div
      className={`relative group cursor-pointer rounded-lg overflow-hidden border-2 transition-all ${
        isSelected
          ? 'border-primary-500 ring-2 ring-primary-200'
          : 'border-transparent hover:border-gray-300 dark:hover:border-gray-600'
      }`}
      onClick={onPreview}
    >
      <div className="aspect-square bg-gray-100 dark:bg-gray-800">
        <img
          src={file.url}
          alt={file.alt_text || file.filename}
          className="w-full h-full object-cover"
          loading="lazy"
        />
      </div>

      {/* Checkbox for selection */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          onSelect();
        }}
        className={`absolute top-2 left-2 w-6 h-6 rounded border-2 flex items-center justify-center transition-all ${
          isSelected
            ? 'bg-primary-500 border-primary-500 text-white'
            : 'bg-white/80 border-gray-300 opacity-0 group-hover:opacity-100'
        }`}
      >
        {isSelected && <Check className="w-4 h-4" />}
      </button>

      {/* File info overlay */}
      <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity">
        <p className="text-white text-xs truncate">{file.filename}</p>
        <p className="text-white/70 text-xs">{formatFileSize(file.file_size)}</p>
      </div>
    </div>
  );
};

// ============================================================================
// Image Preview Modal
// ============================================================================

interface ImagePreviewModalProps {
  file: MediaFile | null;
  isOpen: boolean;
  onClose: () => void;
  onUpdate: (id: number, data: { alt_text?: string; album?: number | null }) => void;
  onDelete: (id: number) => void;
  albums: Album[];
}

const ImagePreviewModal: React.FC<ImagePreviewModalProps> = ({
  file,
  isOpen,
  onClose,
  onUpdate,
  onDelete,
  albums,
}) => {
  const [altText, setAltText] = useState(file?.alt_text || '');
  const [selectedAlbum, setSelectedAlbum] = useState<number | null>(file?.album || null);
  const [copied, setCopied] = useState(false);

  React.useEffect(() => {
    if (file) {
      setAltText(file.alt_text || '');
      setSelectedAlbum(file.album);
    }
  }, [file]);

  if (!file) return null;

  const handleSave = () => {
    onUpdate(file.id, {
      alt_text: altText,
      album: selectedAlbum,
    });
  };

  const handleCopyUrl = () => {
    navigator.clipboard.writeText(file.url);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Image Details" size="lg">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Image preview */}
        <div className="bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden">
          <img
            src={file.url}
            alt={file.alt_text || file.filename}
            className="w-full h-auto max-h-96 object-contain"
          />
        </div>

        {/* Details form */}
        <div className="space-y-4">
          <div>
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Filename
            </p>
            <p className="text-gray-900 dark:text-white">{file.filename}</p>
          </div>

          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <p className="text-gray-500 dark:text-gray-400">Size</p>
              <p className="text-gray-900 dark:text-white">{formatFileSize(file.file_size)}</p>
            </div>
            <div>
              <p className="text-gray-500 dark:text-gray-400">Dimensions</p>
              <p className="text-gray-900 dark:text-white">
                {file.width && file.height ? `${file.width} x ${file.height}` : 'Unknown'}
              </p>
            </div>
          </div>

          <FormInput
            label="Alt Text"
            value={altText}
            onChange={(e) => setAltText(e.target.value)}
            placeholder="Describe this image for accessibility"
          />

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Album
            </label>
            <select
              value={selectedAlbum?.toString() || ''}
              onChange={(e) => setSelectedAlbum(e.target.value ? Number(e.target.value) : null)}
              className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-gray-900 dark:text-white"
            >
              <option value="">No album (Uncategorized)</option>
              {albums.map((album) => (
                <option key={album.id} value={album.id}>
                  {album.name}
                </option>
              ))}
            </select>
          </div>

          <div className="flex gap-2">
            <button
              onClick={handleCopyUrl}
              className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              {copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
              {copied ? 'Copied!' : 'Copy URL'}
            </button>
            <a
              href={file.url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center justify-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              <ExternalLink className="w-4 h-4" />
            </a>
          </div>
        </div>
      </div>

      <div className="flex justify-between mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
        <Button
          variant="outline"
          onClick={() => {
            if (confirm('Are you sure you want to delete this image?')) {
              onDelete(file.id);
              onClose();
            }
          }}
          className="text-red-600 border-red-300 hover:bg-red-50"
        >
          <Trash2 className="w-4 h-4 mr-2" />
          Delete
        </Button>
        <div className="flex gap-2">
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button onClick={handleSave}>Save Changes</Button>
        </div>
      </div>
    </Modal>
  );
};

// ============================================================================
// Album Modal
// ============================================================================

interface AlbumModalProps {
  album: Album | null;
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: { name: string; description: string }) => void;
}

const AlbumModal: React.FC<AlbumModalProps> = ({ album, isOpen, onClose, onSave }) => {
  const [name, setName] = useState(album?.name || '');
  const [description, setDescription] = useState(album?.description || '');

  React.useEffect(() => {
    if (album) {
      setName(album.name);
      setDescription(album.description);
    } else {
      setName('');
      setDescription('');
    }
  }, [album]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (name.trim()) {
      onSave({ name: name.trim(), description: description.trim() });
      onClose();
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} title={album ? 'Edit Album' : 'Create Album'}>
      <form onSubmit={handleSubmit} className="space-y-4">
        <FormInput
          label="Album Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Enter album name"
          required
        />
        <FormTextarea
          label="Description"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Optional description"
          rows={3}
        />
        <div className="flex justify-end gap-2 pt-4">
          <Button type="button" variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button type="submit">{album ? 'Save Changes' : 'Create Album'}</Button>
        </div>
      </form>
    </Modal>
  );
};

// ============================================================================
// Main Gallery Page Component
// ============================================================================

type ViewMode = 'albums' | 'files';

const MediaGalleryPage: React.FC = () => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const fileInputRef = useRef<HTMLInputElement>(null);

  // State
  const [viewMode, setViewMode] = useState<ViewMode>('albums');
  const [currentAlbumId, setCurrentAlbumId] = useState<number | 'null' | null>(null);
  const [selectedFiles, setSelectedFiles] = useState<Set<number>>(new Set());
  const [previewFile, setPreviewFile] = useState<MediaFile | null>(null);
  const [albumModalOpen, setAlbumModalOpen] = useState(false);
  const [editingAlbum, setEditingAlbum] = useState<Album | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  // Queries
  const { data: storageUsage, isLoading: usageLoading } = useQuery({
    queryKey: ['storageUsage'],
    queryFn: getStorageUsage,
  });

  const { data: albums = [], isLoading: albumsLoading } = useQuery({
    queryKey: ['albums'],
    queryFn: listAlbums,
  });

  const { data: files = [], isLoading: filesLoading } = useQuery({
    queryKey: ['mediaFiles', currentAlbumId],
    queryFn: () => listMediaFiles(currentAlbumId === null ? undefined : currentAlbumId),
    enabled: viewMode === 'files',
  });

  // Mutations
  const createAlbumMutation = useMutation({
    mutationFn: createAlbum,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['albums'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  const updateAlbumMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: { name: string; description: string } }) =>
      updateAlbum(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['albums'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  const deleteAlbumMutation = useMutation({
    mutationFn: deleteAlbum,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['albums'] });
      queryClient.invalidateQueries({ queryKey: ['mediaFiles'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  const uploadMutation = useMutation({
    mutationFn: ({
      file,
      albumId,
    }: {
      file: File;
      albumId?: number | null;
    }) => uploadMediaFile(file, albumId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mediaFiles'] });
      queryClient.invalidateQueries({ queryKey: ['storageUsage'] });
      queryClient.invalidateQueries({ queryKey: ['albums'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  const updateFileMutation = useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: number;
      data: { alt_text?: string; album?: number | null };
    }) => updateMediaFile(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mediaFiles'] });
      queryClient.invalidateQueries({ queryKey: ['albums'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  const deleteFileMutation = useMutation({
    mutationFn: deleteMediaFile,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mediaFiles'] });
      queryClient.invalidateQueries({ queryKey: ['storageUsage'] });
      queryClient.invalidateQueries({ queryKey: ['albums'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  const bulkDeleteMutation = useMutation({
    mutationFn: bulkDeleteFiles,
    onSuccess: () => {
      setSelectedFiles(new Set());
      queryClient.invalidateQueries({ queryKey: ['mediaFiles'] });
      queryClient.invalidateQueries({ queryKey: ['storageUsage'] });
      queryClient.invalidateQueries({ queryKey: ['albums'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  const bulkMoveMutation = useMutation({
    mutationFn: ({ fileIds, albumId }: { fileIds: number[]; albumId: number | null }) =>
      bulkMoveFiles(fileIds, albumId),
    onSuccess: () => {
      setSelectedFiles(new Set());
      queryClient.invalidateQueries({ queryKey: ['mediaFiles'] });
      queryClient.invalidateQueries({ queryKey: ['albums'] });
    },
    onError: (err: Error) => setError(err.message),
  });

  // Handlers
  const handleFileUpload = useCallback(
    async (fileList: FileList | null) => {
      if (!fileList || fileList.length === 0) return;

      setError(null);
      setIsUploading(true);

      const filesToUpload = Array.from(fileList);
      const errors: string[] = [];

      for (const file of filesToUpload) {
        // Validate file
        if (!isAllowedFileType(file)) {
          errors.push(`${file.name}: Invalid file type. Use JPEG, PNG, GIF, or WebP.`);
          continue;
        }
        if (!isFileSizeAllowed(file)) {
          errors.push(
            `${file.name}: File too large. Maximum size is ${formatFileSize(MAX_FILE_SIZE)}.`
          );
          continue;
        }

        try {
          await uploadMutation.mutateAsync({
            file,
            albumId: typeof currentAlbumId === 'number' ? currentAlbumId : null,
          });
        } catch {
          errors.push(`${file.name}: Upload failed.`);
        }
      }

      setIsUploading(false);
      if (errors.length > 0) {
        setError(errors.join('\n'));
      }
    },
    [currentAlbumId, uploadMutation]
  );

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      handleFileUpload(e.dataTransfer.files);
    },
    [handleFileUpload]
  );

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const toggleFileSelection = (fileId: number) => {
    setSelectedFiles((prev) => {
      const next = new Set(prev);
      if (next.has(fileId)) {
        next.delete(fileId);
      } else {
        next.add(fileId);
      }
      return next;
    });
  };

  const handleAlbumClick = (albumId: number | 'null') => {
    setCurrentAlbumId(albumId);
    setViewMode('files');
    setSelectedFiles(new Set());
  };

  const handleBackToAlbums = () => {
    setViewMode('albums');
    setCurrentAlbumId(null);
    setSelectedFiles(new Set());
  };

  const handleDeleteSelectedFiles = () => {
    if (selectedFiles.size === 0) return;
    if (confirm(`Delete ${selectedFiles.size} selected file(s)?`)) {
      bulkDeleteMutation.mutate(Array.from(selectedFiles));
    }
  };

  const handleAlbumSave = (data: { name: string; description: string }) => {
    if (editingAlbum) {
      updateAlbumMutation.mutate({ id: editingAlbum.id, data });
    } else {
      createAlbumMutation.mutate(data);
    }
    setEditingAlbum(null);
    setAlbumModalOpen(false);
  };

  const handleDeleteAlbum = (album: Album) => {
    if (
      confirm(
        `Delete album "${album.name}"? Files will be moved to Uncategorized.`
      )
    ) {
      deleteAlbumMutation.mutate(album.id);
    }
  };

  const currentAlbum =
    typeof currentAlbumId === 'number'
      ? albums.find((a) => a.id === currentAlbumId)
      : null;

  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          {viewMode === 'files' && (
            <button
              onClick={handleBackToAlbums}
              className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
            >
              <ChevronLeft className="w-5 h-5" />
            </button>
          )}
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
              {viewMode === 'albums'
                ? t('gallery.title', 'Media Gallery')
                : currentAlbum?.name || t('gallery.uncategorized', 'Uncategorized')}
            </h1>
            {viewMode === 'files' && currentAlbum?.description && (
              <p className="text-gray-500 dark:text-gray-400 mt-1">
                {currentAlbum.description}
              </p>
            )}
          </div>
        </div>

        <div className="flex gap-2">
          {viewMode === 'albums' && (
            <Button
              onClick={() => {
                setEditingAlbum(null);
                setAlbumModalOpen(true);
              }}
              variant="outline"
            >
              <FolderPlus className="w-4 h-4 mr-2" />
              {t('gallery.newAlbum', 'New Album')}
            </Button>
          )}
          <Button
            onClick={() => fileInputRef.current?.click()}
            disabled={isUploading}
          >
            <Upload className="w-4 h-4 mr-2" />
            {isUploading
              ? t('gallery.uploading', 'Uploading...')
              : t('gallery.upload', 'Upload')}
          </Button>
          <input
            ref={fileInputRef}
            type="file"
            accept={getAllowedFileTypes()}
            multiple
            className="hidden"
            onChange={(e) => handleFileUpload(e.target.files)}
          />
        </div>
      </div>

      {/* Storage usage */}
      <StorageUsageBar usage={storageUsage} isLoading={usageLoading} />

      {/* Error message */}
      {error && (
        <Alert type="error" className="mt-4" onClose={() => setError(null)}>
          <pre className="whitespace-pre-wrap text-sm">{error}</pre>
        </Alert>
      )}

      {/* Bulk actions bar */}
      {selectedFiles.size > 0 && (
        <div className="mt-4 flex items-center gap-4 p-3 bg-primary-50 dark:bg-primary-900/20 border border-primary-200 dark:border-primary-800 rounded-lg">
          <span className="text-sm font-medium text-primary-700 dark:text-primary-300">
            {selectedFiles.size} selected
          </span>
          <div className="flex-1" />
          <select
            onChange={(e) => {
              const albumId = e.target.value === '' ? null : Number(e.target.value);
              bulkMoveMutation.mutate({
                fileIds: Array.from(selectedFiles),
                albumId,
              });
              e.target.value = '';
            }}
            className="text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-2 py-1"
            defaultValue=""
          >
            <option value="" disabled>
              Move to album...
            </option>
            <option value="">Uncategorized</option>
            {albums.map((album) => (
              <option key={album.id} value={album.id}>
                {album.name}
              </option>
            ))}
          </select>
          <Button
            size="sm"
            variant="outline"
            onClick={() => setSelectedFiles(new Set())}
          >
            <X className="w-4 h-4 mr-1" />
            Clear
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={handleDeleteSelectedFiles}
            className="text-red-600 border-red-300 hover:bg-red-50"
          >
            <Trash2 className="w-4 h-4 mr-1" />
            Delete
          </Button>
        </div>
      )}

      {/* Content */}
      <div
        className="mt-6"
        onDrop={handleDrop}
        onDragOver={handleDragOver}
      >
        {viewMode === 'albums' ? (
          // Albums view
          <div>
            {/* Quick access buttons */}
            <div className="flex gap-2 mb-6">
              <button
                onClick={() => handleAlbumClick(null as never)}
                className="px-4 py-2 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg text-sm font-medium"
              >
                {t('gallery.allFiles', 'All Files')}
              </button>
              <button
                onClick={() => handleAlbumClick('null')}
                className="px-4 py-2 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg text-sm font-medium"
              >
                {t('gallery.uncategorized', 'Uncategorized')}
              </button>
            </div>

            {/* Albums grid */}
            {albumsLoading ? (
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                {[...Array(5)].map((_, i) => (
                  <div key={i} className="animate-pulse">
                    <div className="aspect-square bg-gray-200 dark:bg-gray-700 rounded-t-lg" />
                    <div className="p-3">
                      <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-2/3 mb-2" />
                      <div className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-1/3" />
                    </div>
                  </div>
                ))}
              </div>
            ) : albums.length === 0 ? (
              <div className="text-center py-12">
                <FolderOpen className="w-16 h-16 mx-auto text-gray-400 dark:text-gray-600 mb-4" />
                <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                  {t('gallery.noAlbums', 'No albums yet')}
                </h3>
                <p className="text-gray-500 dark:text-gray-400 mb-4">
                  {t('gallery.noAlbumsDesc', 'Create an album to organize your images')}
                </p>
                <Button
                  onClick={() => {
                    setEditingAlbum(null);
                    setAlbumModalOpen(true);
                  }}
                >
                  <FolderPlus className="w-4 h-4 mr-2" />
                  {t('gallery.createFirstAlbum', 'Create First Album')}
                </Button>
              </div>
            ) : (
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                {albums.map((album) => (
                  <AlbumCard
                    key={album.id}
                    album={album}
                    isSelected={currentAlbumId === album.id}
                    onSelect={() => handleAlbumClick(album.id)}
                    onEdit={() => {
                      setEditingAlbum(album);
                      setAlbumModalOpen(true);
                    }}
                    onDelete={() => handleDeleteAlbum(album)}
                  />
                ))}
              </div>
            )}
          </div>
        ) : (
          // Files view
          <div>
            {filesLoading ? (
              <div className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
                {[...Array(12)].map((_, i) => (
                  <div key={i} className="animate-pulse">
                    <div className="aspect-square bg-gray-200 dark:bg-gray-700 rounded-lg" />
                  </div>
                ))}
              </div>
            ) : files.length === 0 ? (
              <div
                className="text-center py-16 border-2 border-dashed border-gray-300 dark:border-gray-700 rounded-lg"
                onDrop={handleDrop}
                onDragOver={handleDragOver}
              >
                <ImageIcon className="w-16 h-16 mx-auto text-gray-400 dark:text-gray-600 mb-4" />
                <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                  {t('gallery.noFiles', 'No files here')}
                </h3>
                <p className="text-gray-500 dark:text-gray-400 mb-4">
                  {t('gallery.dropFiles', 'Drop files here or click Upload')}
                </p>
                <Button onClick={() => fileInputRef.current?.click()}>
                  <Upload className="w-4 h-4 mr-2" />
                  {t('gallery.upload', 'Upload')}
                </Button>
              </div>
            ) : (
              <div className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
                {files.map((file) => (
                  <MediaThumbnail
                    key={file.id}
                    file={file}
                    isSelected={selectedFiles.has(file.id)}
                    onSelect={() => toggleFileSelection(file.id)}
                    onPreview={() => setPreviewFile(file)}
                  />
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Album modal */}
      <AlbumModal
        album={editingAlbum}
        isOpen={albumModalOpen}
        onClose={() => {
          setAlbumModalOpen(false);
          setEditingAlbum(null);
        }}
        onSave={handleAlbumSave}
      />

      {/* Image preview modal */}
      <ImagePreviewModal
        file={previewFile}
        isOpen={!!previewFile}
        onClose={() => setPreviewFile(null)}
        onUpdate={(id, data) => {
          updateFileMutation.mutate({ id, data });
          setPreviewFile(null);
        }}
        onDelete={(id) => {
          deleteFileMutation.mutate(id);
          setPreviewFile(null);
        }}
        albums={albums}
      />
    </div>
  );
};

export default MediaGalleryPage;
