// File: src/pages/User/FileManager/Collections/CollectionDetails.jsx
// UIX version - Theme-aware Collection Details with Layout
import React, { useState, useEffect, useCallback, useRef } from "react";
import { useNavigate, useParams, useLocation } from "react-router";
import { useFiles, useCrypto, useAuth, useDashboard, useTags } from "../../../../services/Services";
import withPasswordProtection from "../../../../hocs/withPasswordProtection";
import Layout from "../../../../components/Layout/Layout";
import { Button, Input, Alert, Modal, Breadcrumb, Card, useUIXTheme, CollectionIcon } from "../../../../components/UIX";
import {
  FolderIcon,
  PhotoIcon,
  DocumentIcon,
  CloudArrowUpIcon,
  ShareIcon,
  ArrowDownTrayIcon,
  MagnifyingGlassIcon,
  ArrowPathIcon,
  PlusIcon,
  HomeIcon,
  ChevronRightIcon,
  ViewColumnsIcon,
  ListBulletIcon,
  EllipsisVerticalIcon,
  TrashIcon,
  StarIcon,
  ClockIcon,
  CheckCircleIcon,
  TagIcon,
  PencilIcon,
  FunnelIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import { StarIcon as StarIconSolid } from "@heroicons/react/24/solid";
import TagList from "../../../../components/UIX/TagList/TagList";
import TagSelector from "../../../../components/UIX/TagSelector/TagSelector";
import TagColorIndicator from "../../../../components/UIX/TagColorIndicator/TagColorIndicator";

const CollectionDetails = () => {
  const navigate = useNavigate();
  const { collectionId } = useParams();
  const location = useLocation();
  const { getThemeClasses } = useUIXTheme();

  const {
    getCollectionManager,
    listCollectionManager,
    downloadFileManager,
    deleteFileManager,
    deleteCollectionManager,
    authService,
  } = useFiles();
  const { CollectionCryptoService } = useCrypto();
  const { authManager } = useAuth();
  const { dashboardManager } = useDashboard();
  const { collectionTagManager, tagManager } = useTags();

  // Refs for cleanup
  const isMountedRef = useRef(true);

  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [fieldErrors, setFieldErrors] = useState({});
  const [success, setSuccess] = useState("");
  const [collection, setCollection] = useState(null);
  const [allFiles, setAllFiles] = useState([]);
  const [files, setFiles] = useState([]);
  const [subCollections, setSubCollections] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [downloadingFiles, setDownloadingFiles] = useState(new Set());
  const [fileManager, setFileManager] = useState(null);

  // Breadcrumb navigation state
  const [breadcrumbs, setBreadcrumbs] = useState([]);
  const [isLoadingBreadcrumbs, setIsLoadingBreadcrumbs] = useState(false);

  // State to track pending refresh operations
  const [pendingRefresh, setPendingRefresh] = useState(false);
  const [refreshReason, setRefreshReason] = useState(null);

  // UI State from new design
  const [viewMode, setViewMode] = useState("grid"); // grid or list
  const [selectedFiles, setSelectedFiles] = useState(new Set());
  const [showDropdown, setShowDropdown] = useState(null);

  // Delete state
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // Tag state
  const [collectionTags, setCollectionTags] = useState([]);
  const [isLoadingTags, setIsLoadingTags] = useState(false);
  const [showTagEditor, setShowTagEditor] = useState(false);
  const [editingTagIds, setEditingTagIds] = useState([]);
  const [isSavingTags, setIsSavingTags] = useState(false);
  const [subCollectionTagsMap, setSubCollectionTagsMap] = useState({});
  const [fileTagsMap, setFileTagsMap] = useState({});

  // Tag filtering state
  const [availableTags, setAvailableTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [showTagFilterMenu, setShowTagFilterMenu] = useState(false);

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  // Load available tags for filtering
  useEffect(() => {
    const loadAvailableTags = async () => {
      if (!tagManager || !authManager?.isAuthenticated()) return;
      try {
        const tags = await tagManager.listTags();
        if (isMountedRef.current && tags) {
          setAvailableTags(tags);
          if (import.meta.env.DEV) {
            console.log("[CollectionDetails] Loaded available tags for filtering:", tags.length);
          }
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("[CollectionDetails] Failed to load tags for filtering:", error);
        }
      }
    };
    loadAvailableTags();
  }, [tagManager, authManager]);

  // Initialize file manager
  useEffect(() => {
    const initializeManager = async () => {
      if (!authService?.isAuthenticated()) return;

      try {
        const { default: ListFileManager } = await import(
          "../../../../services/Manager/File/ListFileManager.js"
        );

        const manager = new ListFileManager(
          authService,
          getCollectionManager,
          listCollectionManager,
        );
        await manager.initialize();
        setFileManager(manager);

        if (import.meta.env.DEV) {
          console.log("[CollectionDetails] ListFileManager initialized");
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error(
            "[CollectionDetails] Failed to initialize ListFileManager:",
            err,
          );
        }
        setError(`Failed to initialize: ${err.message}`);
      }
    };

    initializeManager();
  }, [authService, getCollectionManager, listCollectionManager]);

  // Process collection for decryption
  const processCollection = useCallback(
    async (rawCollection) => {
      let processedCollection = { ...rawCollection };

      if (rawCollection.encrypted_name || rawCollection.encrypted_description) {
        try {
          let collectionKey =
            rawCollection.collection_key ||
            CollectionCryptoService.getCachedCollectionKey(rawCollection.id);

          if (collectionKey) {
            const { default: CollectionCryptoServiceClass } = await import(
              "../../../../services/Crypto/CollectionCryptoService.js"
            );

            const decryptedCollection =
              await CollectionCryptoServiceClass.decryptCollectionFromAPI(
                rawCollection,
                collectionKey,
              );
            processedCollection = decryptedCollection;
          } else {
            processedCollection.name = "Locked Folder";
            processedCollection._isDecrypted = false;
          }
        } catch (decryptError) {
          if (import.meta.env.DEV) {
            console.error("[CollectionDetails] Decryption error:", decryptError);
          }
          processedCollection.name = "Locked Folder";
          processedCollection._isDecrypted = false;
        }
      } else {
        processedCollection._isDecrypted = true;
      }

      processedCollection.type =
        processedCollection.collection_type || "folder";
      processedCollection.customIcon =
        processedCollection.custom_icon || "";

      // Check if current user is the owner by comparing email addresses
      const currentUserEmail = authManager?.getCurrentUserEmail();

      // Find if current user is in members list and check if their recipient_id matches owner_id
      // When you're the owner, you're also a member with recipient_id === owner_id
      const currentUserMember = rawCollection.members?.find(
        (member) => member.recipient_email === currentUserEmail
      );

      // You're the owner if:
      // 1. You're in the members list AND your recipient_id equals the owner_id
      // 2. OR there are no members (not shared yet) and backend verified access
      processedCollection.isOwned = currentUserMember
        ? currentUserMember.recipient_id === rawCollection.owner_id
        : true; // If not in members list but have access, must be owner

      return processedCollection;
    },
    [CollectionCryptoService, authManager],
  );

  // Build breadcrumb trail
  const loadBreadcrumbs = useCallback(
    async (currentCollection) => {
      if (!currentCollection || !getCollectionManager) return;

      setIsLoadingBreadcrumbs(true);
      try {
        const breadcrumbItems = [];
        const collectionChain = [];
        let current = currentCollection;

        collectionChain.unshift({
          id: current.id,
          name: current.name || "Locked Folder",
          isCurrent: true,
        });

        // Walk up the parent chain to build breadcrumbs
        // Check for valid parent_id (not null, not empty string, not zero UUID)
        const emptyUUID = "00000000-0000-0000-0000-000000000000";

        if (import.meta.env.DEV) {
          console.log("[CollectionDetails] Breadcrumb building - current collection:", {
            id: current.id,
            name: current.name,
            parent_id: current.parent_id,
            parent_id_type: typeof current.parent_id,
          });
        }

        while (
          current.parent_id &&
          current.parent_id !== emptyUUID &&
          current.parent_id.trim() !== ""
        ) {
          if (import.meta.env.DEV) {
            console.log("[CollectionDetails] Fetching parent collection:", current.parent_id);
          }
          const result = await getCollectionManager.getCollection(
            current.parent_id,
          );
          if (result.collection) {
            const processedParent = await processCollection(result.collection);
            collectionChain.unshift({
              id: processedParent.id,
              name: processedParent.name || "Locked Folder",
              isCurrent: false,
            });
            current = processedParent;
          } else {
            break;
          }
        }

        breadcrumbItems.push({
          id: "root",
          name: "My Files",
          path: "/file-manager",
          isRoot: true,
        });

        collectionChain.forEach((collection, index) => {
          const isLast = index === collectionChain.length - 1;
          breadcrumbItems.push({
            id: collection.id,
            name: collection.name,
            path: isLast ? null : `/file-manager/collections/${collection.id}`,
            isRoot: false,
            isCurrent: isLast,
          });
        });

        setBreadcrumbs(breadcrumbItems);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error(
            "[CollectionDetails] Failed to build breadcrumbs:",
            error,
          );
        }
        setBreadcrumbs([
          {
            id: "root",
            name: "My Files",
            path: "/file-manager",
            isRoot: true,
          },
          {
            id: currentCollection.id,
            name: currentCollection.name || "Current Folder",
            path: null,
            isRoot: false,
            isCurrent: true,
          },
        ]);
      } finally {
        setIsLoadingBreadcrumbs(false);
      }
    },
    [getCollectionManager, processCollection],
  );

  // Comprehensive cache clearing function
  const performComprehensiveCacheClearing = useCallback(() => {
    if (import.meta.env.DEV) {
      console.log(
        "[CollectionDetails] 🧹 Starting comprehensive cache clearing...",
      );
    }
    if (listCollectionManager) listCollectionManager.clearAllCache();
    if (getCollectionManager) getCollectionManager.clearAllCache();
    if (fileManager) fileManager.clearAllCaches();
    // Omitting other localStorage logic for brevity
  }, [listCollectionManager, getCollectionManager, fileManager]);

  // Load tags for files from embedded tags (already decrypted)
  const loadFileTags = useCallback((files) => {
    if (!files || files.length === 0) return;

    try {
      const tagsMap = {};

      files.forEach(file => {
        // Use embedded tags directly - they're already decrypted
        if (file.tags && file.tags.length > 0) {
          tagsMap[file.id] = file.tags;
        } else {
          tagsMap[file.id] = [];
        }
      });

      setFileTagsMap(tagsMap);
      if (import.meta.env.DEV) {
        console.log("[CollectionDetails] Loaded file embedded tags for", files.length, "files");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[CollectionDetails] Failed to load file tags:", error);
      }
    }
  }, []);

  // Load tags for sub-collections from embedded tags (already decrypted)
  const loadSubCollectionTags = useCallback((collections) => {
    if (!collections || collections.length === 0) return;

    try {
      const tagsMap = {};

      collections.forEach(col => {
        // Use embedded tags directly - they're already decrypted
        if (col.tags && col.tags.length > 0) {
          tagsMap[col.id] = col.tags;
        } else {
          tagsMap[col.id] = [];
        }
      });

      setSubCollectionTagsMap(tagsMap);
      if (import.meta.env.DEV) {
        console.log("[CollectionDetails] Loaded sub-collection embedded tags for", collections.length, "collections");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[CollectionDetails] Failed to load sub-collection tags:", error);
      }
    }
  }, []);

  // Filter files based on view mode
  const filterFilesByViewMode = useCallback(
    (filesToFilter, mode = "active") => {
      const filtered = filesToFilter.filter(
        (f) => f.state === "active" || (!f.state && f._is_active),
      );
      setFiles(filtered);
      // Load tags for the filtered files
      loadFileTags(filtered);
    },
    [loadFileTags],
  );

  // Load ALL files and store them for client-side filtering
  const loadAllCollectionFiles = useCallback(
    async (collectionId, forceRefresh = false) => {
      if (!fileManager) return;

      try {
        const allStates = Object.values(fileManager.FILE_STATES);
        const loadedFiles = await fileManager.listFilesByCollection(
          collectionId,
          allStates,
          forceRefresh,
        );
        setAllFiles(loadedFiles);
        filterFilesByViewMode(loadedFiles);
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error("[CollectionDetails] Failed to load files:", err);
        }
        setAllFiles([]);
        setFiles([]);
      }
    },
    [fileManager, filterFilesByViewMode],
  );

  // Load sub-collections
  const loadSubCollections = useCallback(
    async (parentCollectionId, forceRefresh = false) => {
      if (!listCollectionManager) return;
      try {
        const result =
          await listCollectionManager.listCollections(forceRefresh);
        if (result.collections) {
          const subCollections = result.collections.filter(
            (col) => col.parent_id === parentCollectionId,
          );
          const processedSubCollections = await Promise.all(
            subCollections.map((subCol) => processCollection(subCol)),
          );
          setSubCollections(processedSubCollections);
          // Load tags for sub-collections
          loadSubCollectionTags(processedSubCollections);
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error(
            "[CollectionDetails] Failed to load sub-collections:",
            err,
          );
        }
        setSubCollections([]);
      }
    },
    [listCollectionManager, processCollection],
  );

  // Main load collection function
  const loadCollection = useCallback(
    async (forceRefresh = false) => {
      if (!getCollectionManager || !collectionId || !fileManager) return;
      setIsLoading(true);
      setError("");
      try {
        if (forceRefresh) {
          performComprehensiveCacheClearing();
        }
        const result = await getCollectionManager.getCollection(
          collectionId,
          forceRefresh,
        );
        if (result.collection) {
          const processedCollection = await processCollection(
            result.collection,
          );
          setCollection(processedCollection);
          if (result.collection.collection_key) {
            CollectionCryptoService.cacheCollectionKey(
              collectionId,
              result.collection.collection_key,
            );
          }
          await loadBreadcrumbs(processedCollection);
        }
        await loadAllCollectionFiles(collectionId, forceRefresh);
        await loadSubCollections(collectionId, forceRefresh);
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error("[CollectionDetails] Failed to load collection:", err);
        }

        // Parse RFC 9457 error response
        if (err.fieldErrors && Object.keys(err.fieldErrors).length > 0) {
          setFieldErrors(err.fieldErrors);
        }

        if (err.message) {
          // Clean up technical error messages
          let userMessage = err.message;
          userMessage = userMessage.replace(/^Failed to load collection:\s*/i, '');
          userMessage = userMessage.replace(/^Request failed:\s*/i, '');
          userMessage = userMessage.replace(/^Error:\s*/i, '');

          if (userMessage.includes('One or more fields failed validation')) {
            userMessage = 'Could not load folder. Please try again.';
          }

          setError(userMessage);
        } else {
          setError("Could not load folder. Please try again.");
        }
      } finally {
        setIsLoading(false);
      }
    },
    [
      getCollectionManager,
      collectionId,
      fileManager,
      CollectionCryptoService,
      performComprehensiveCacheClearing,
      processCollection,
      loadBreadcrumbs,
      loadAllCollectionFiles,
      loadSubCollections,
    ],
  );

  // Load tags for the collection from embedded tags (already decrypted by CollectionCryptoService)
  const loadCollectionTags = useCallback(async (embeddedTags) => {
    if (!embeddedTags || embeddedTags.length === 0) {
      setCollectionTags([]);
      return;
    }

    try {
      setIsLoadingTags(true);
      // Embedded tags are already decrypted by CollectionCryptoService.decryptCollectionFromAPI
      // They have: id, name, color (decrypted)
      setCollectionTags(embeddedTags);
      if (import.meta.env.DEV) {
        console.log("[CollectionDetails] Loaded embedded tags:", embeddedTags.length);
      }
    } catch (error) {
      console.error("[CollectionDetails] Failed to load tags:", error);
      setCollectionTags([]);
    } finally {
      setIsLoadingTags(false);
    }
  }, []);

  // Handle opening tag editor
  const handleEditTags = useCallback(() => {
    // Get tag IDs from embedded tags
    const tagIds = collectionTags.map(t => t.id) || [];
    setEditingTagIds(tagIds);
    setShowTagEditor(true);
  }, [collectionTags]);

  // Handle saving tags
  const handleSaveTags = useCallback(async () => {
    if (!collection || !collectionTagManager) return;

    try {
      setIsSavingTags(true);
      setError("");

      // Get current tag IDs from embedded tags
      const currentTagIds = collectionTags.map(t => t.id) || [];

      await collectionTagManager.updateCollectionTags(
        collection.id,
        currentTagIds,
        editingTagIds
      );

      // Force refresh the collection to get updated embedded tags from server
      await loadCollection(true);

      setShowTagEditor(false);
      setSuccess("Tags updated successfully!");
      setTimeout(() => setSuccess(""), 3000);
    } catch (error) {
      console.error("[CollectionDetails] Failed to save tags:", error);
      setError("Failed to update tags. Please try again.");
    } finally {
      setIsSavingTags(false);
    }
  }, [collection, collectionTags, collectionTagManager, editingTagIds, loadCollection]);

  // Load tags when collection changes - use embedded tags directly
  useEffect(() => {
    if (collection?.tags) {
      loadCollectionTags(collection.tags);
    } else {
      setCollectionTags([]);
    }
  }, [collection?.tags, loadCollectionTags]);

  // Refresh detection from navigation state
  useEffect(() => {
    const shouldRefresh = location.state?.refresh;
    if (shouldRefresh) {
      if (location.state?.newCollectionCreated) {
        setRefreshReason("collection_creation");
      }
      if (location.state?.refreshFiles || location.state?.forceFileRefresh) {
        setRefreshReason("file_upload");
        if (location.state?.uploadedFileCount) {
          setSuccess(
            `${location.state.uploadedFileCount} file(s) uploaded successfully!`,
          );
        }
      }
      if (location.state?.deletedFileId) {
        setRefreshReason("file_deletion");
        setSuccess("File moved to trash successfully!");
      }
      setPendingRefresh(true);
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [location.state, navigate, location.pathname]);

  // Execute pending refresh
  useEffect(() => {
    if (
      pendingRefresh &&
      getCollectionManager &&
      fileManager &&
      collectionId &&
      authManager?.isAuthenticated()
    ) {
      loadCollection(true);
      setPendingRefresh(false);
      setRefreshReason(null);
    }
  }, [
    pendingRefresh,
    getCollectionManager,
    fileManager,
    collectionId,
    authManager,
    loadCollection,
  ]);

  // Initial load
  useEffect(() => {
    if (
      getCollectionManager &&
      fileManager &&
      collectionId &&
      authManager?.isAuthenticated() &&
      !pendingRefresh
    ) {
      // Force refresh to get latest data (especially important for shared collections)
      loadCollection(true);
    }
  }, [
    getCollectionManager,
    fileManager,
    collectionId,
    authManager,
    loadCollection,
    pendingRefresh,
  ]);

  // Handlers
  const handleCreateSubCollection = () => {
    navigate("/file-manager/collections/create", {
      state: {
        parentCollectionId: collectionId,
        parentCollectionName: collection?.name || "Parent Folder",
      },
    });
  };

  const handleDownloadFile = async (fileId, fileName) => {
    if (!downloadFileManager) return;
    const file = files.find((f) => f.id === fileId);
    if (file && fileManager && !fileManager.canDownloadFile(file)) {
      setError("This file cannot be downloaded in its current state.");
      return;
    }
    try {
      setDownloadingFiles((prev) => new Set(prev).add(fileId));
      setSuccess(`Preparing download for "${fileName}"...`);
      await downloadFileManager.downloadFile(fileId, { saveToDisk: true });
      setSuccess(`File "${fileName}" downloaded successfully!`);
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("[CollectionDetails] Failed to download file:", err);
      }

      // Parse RFC 9457 error response
      if (err.fieldErrors && Object.keys(err.fieldErrors).length > 0) {
        setFieldErrors(err.fieldErrors);
      }

      if (err.message) {
        let userMessage = err.message;
        userMessage = userMessage.replace(/^Failed to download file:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');
        setError(userMessage);
      } else {
        setError("Could not download file. Please try again.");
      }
    } finally {
      setDownloadingFiles((prev) => {
        const next = new Set(prev);
        next.delete(fileId);
        return next;
      });
    }
  };

  const handleDeleteFile = async (fileId, fileName) => {
    if (!deleteFileManager) return;

    try {
      setSuccess(`Deleting "${fileName}"...`);
      await deleteFileManager.deleteFile(fileId, null);
      setSuccess(`File "${fileName}" moved to trash successfully!`);

      // Clear the dashboard cache to update stats
      if (dashboardManager && dashboardManager.clearAllCaches) {
        if (import.meta.env.DEV) {
          console.log("[CollectionDetails] Clearing dashboard cache after file deletion");
        }
        dashboardManager.clearAllCaches();
      }

      // Dispatch event to notify other components
      window.dispatchEvent(new CustomEvent("dashboardRefresh"));

      // Refresh the file list after deletion
      setPendingRefresh(true);
      setRefreshReason("file_deletion");
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("[CollectionDetails] Failed to delete file:", err);
      }

      // Parse RFC 9457 error response
      if (err.fieldErrors && Object.keys(err.fieldErrors).length > 0) {
        setFieldErrors(err.fieldErrors);
      }

      if (err.message) {
        let userMessage = err.message;
        userMessage = userMessage.replace(/^Failed to delete file:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');
        setError(userMessage);
      } else {
        setError("Could not delete file. Please try again.");
      }
    }
  };

  const handleDeleteSelectedFiles = async () => {
    if (!deleteFileManager || selectedFiles.size === 0) return;

    const filesToDelete = Array.from(selectedFiles);
    const fileCount = filesToDelete.length;

    try {
      setSuccess(`Deleting ${fileCount} file${fileCount > 1 ? 's' : ''}...`);

      // Delete files sequentially to avoid overwhelming the server
      for (const fileId of filesToDelete) {
        await deleteFileManager.deleteFile(fileId, null);
      }

      setSuccess(`${fileCount} file${fileCount > 1 ? 's' : ''} moved to trash successfully!`);

      // Clear selection
      setSelectedFiles(new Set());

      // Clear the dashboard cache to update stats
      if (dashboardManager && dashboardManager.clearAllCaches) {
        if (import.meta.env.DEV) {
          console.log("[CollectionDetails] Clearing dashboard cache after bulk file deletion");
        }
        dashboardManager.clearAllCaches();
      }

      // Dispatch event to notify other components
      window.dispatchEvent(new CustomEvent("dashboardRefresh"));

      // Refresh the file list after deletion
      setPendingRefresh(true);
      setRefreshReason("file_deletion");
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("[CollectionDetails] Failed to delete selected files:", err);
      }

      // Parse RFC 9457 error response
      if (err.fieldErrors && Object.keys(err.fieldErrors).length > 0) {
        setFieldErrors(err.fieldErrors);
      }

      if (err.message) {
        let userMessage = err.message;
        userMessage = userMessage.replace(/^Failed to delete file:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');
        setError(userMessage);
      } else {
        setError("Could not delete selected files. Please try again.");
      }
    }
  };

  const handleUploadToCollection = () => {
    navigate(`/file-manager/upload?collection=${collectionId}`);
  };

  const handleShareCollection = () => {
    navigate(`/file-manager/collections/${collectionId}/share`);
  };

  const handleManualRefresh = async () => {
    await loadCollection(true);
  };

  // Delete handlers
  const handleDeleteClick = () => {
    setShowDeleteConfirm(true);
  };

  const handleCancelDelete = () => {
    setShowDeleteConfirm(false);
  };

  const handleConfirmDelete = async () => {
    if (import.meta.env.DEV) {
      console.log("[CollectionDetails] handleConfirmDelete called");
      console.log("[CollectionDetails] collectionId:", collectionId);
      console.log("[CollectionDetails] deleteCollectionManager:", deleteCollectionManager);
    }

    if (!deleteCollectionManager) {
      if (import.meta.env.DEV) {
        console.error("[CollectionDetails] deleteCollectionManager is not available");
      }
      setError("Delete functionality is not available");
      return;
    }

    try {
      setIsDeleting(true);
      if (import.meta.env.DEV) {
        console.log("[CollectionDetails] Calling deleteCollectionManager.deleteCollection with ID:", collectionId);
      }

      const result = await deleteCollectionManager.deleteCollection(collectionId);

      if (import.meta.env.DEV) {
        console.log("[CollectionDetails] Delete successful, result:", result);
      }

      // Clear the collection list cache to ensure fresh data
      if (listCollectionManager && listCollectionManager.clearCache) {
        if (import.meta.env.DEV) {
          console.log("[CollectionDetails] Clearing collection list cache");
        }
        listCollectionManager.clearCache();
      }

      // Clear the dashboard cache to update stats
      if (dashboardManager && dashboardManager.clearAllCaches) {
        if (import.meta.env.DEV) {
          console.log("[CollectionDetails] Clearing dashboard cache");
        }
        dashboardManager.clearAllCaches();
      }

      // Dispatch event to notify other components (like sidebar)
      if (import.meta.env.DEV) {
        console.log("[CollectionDetails] Dispatching dashboardRefresh event");
      }
      window.dispatchEvent(new CustomEvent("dashboardRefresh"));

      if (import.meta.env.DEV) {
        console.log("[CollectionDetails] Navigating to /file-manager with state to force refresh");
      }

      // Navigate back to file manager after successful deletion
      // Pass state to trigger a refresh
      navigate("/file-manager", { state: { refresh: true, reason: "collection_deleted" } });
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[CollectionDetails] Failed to delete collection:", error);
      }

      // Parse RFC 9457 error response
      if (error.fieldErrors && Object.keys(error.fieldErrors).length > 0) {
        setFieldErrors(error.fieldErrors);
      }

      if (error.message) {
        let userMessage = error.message;
        userMessage = userMessage.replace(/^Failed to delete collection:\s*/i, '');
        userMessage = userMessage.replace(/^Failed to delete folder:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');

        if (userMessage.includes('One or more fields failed validation')) {
          userMessage = 'Could not delete folder. Please try again.';
        }

        setError(userMessage);
      } else {
        setError("Could not delete folder. Please try again.");
      }
      setIsDeleting(false);
    }
  };

  // UI Helpers
  const formatFileSize = (bytes) => {
    if (!bytes) return "0 B";
    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${Math.round(bytes / Math.pow(1024, i))} ${sizes[i]}`;
  };

  const getTimeAgo = (dateString) => {
    if (!dateString) return "Recently";
    const now = new Date();
    const date = new Date(dateString);
    const diffInMinutes = Math.floor((now - date) / (1000 * 60));
    if (diffInMinutes < 60) return "Just now";
    if (diffInMinutes < 1440) return "Today";
    if (diffInMinutes < 2880) return "Yesterday";
    return "This week";
  };

  const getFileIcon = (mimeType, sizeClass = "h-10 w-10") => {
    if (!mimeType)
      return <DocumentIcon className={`${sizeClass} ${getThemeClasses("text-secondary")}`} />;
    if (mimeType.includes("pdf"))
      return <DocumentIcon className={`${sizeClass} ${getThemeClasses("text-error")}`} />;
    if (mimeType.includes("word"))
      return <DocumentIcon className={`${sizeClass} ${getThemeClasses("text-info")}`} />;
    if (mimeType.includes("sheet"))
      return <DocumentIcon className={`${sizeClass} ${getThemeClasses("text-success")}`} />;
    if (mimeType.startsWith("image/"))
      return <PhotoIcon className={`${sizeClass} ${getThemeClasses("text-accent")}`} />;
    return <DocumentIcon className={`${sizeClass} ${getThemeClasses("text-secondary")}`} />;
  };

  const toggleFileSelection = (fileId) => {
    const newSelection = new Set(selectedFiles);
    if (newSelection.has(fileId)) newSelection.delete(fileId);
    else newSelection.add(fileId);
    setSelectedFiles(newSelection);
  };

  // Filtered data for rendering
  const filteredFiles = files.filter((file) => {
    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      if (!(file.name || "").toLowerCase().includes(query)) {
        return false;
      }
    }

    // Filter by selected tags (file must have ALL selected tags)
    if (selectedTagIds.length > 0) {
      const fileTags = fileTagsMap[file.id] || [];
      const fileTagIdSet = new Set(fileTags.map(tag => tag.id));
      const hasAllSelectedTags = selectedTagIds.every(tagId => fileTagIdSet.has(tagId));
      if (!hasAllSelectedTags) {
        return false;
      }
    }

    return true;
  });
  const filteredSubCollections = subCollections.filter((col) =>
    (col.name || "").toLowerCase().includes(searchQuery.toLowerCase()),
  );

  // Clear messages
  useEffect(() => {
    if (success || error) {
      const timer = setTimeout(() => {
        setSuccess("");
        setError("");
      }, 5000);
      return () => clearTimeout(timer);
    }
  }, [success, error]);

  if (isLoading) {
    return (
      <Layout>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className={`animate-spin rounded-full h-8 w-8 border-b-2 ${getThemeClasses("border-primary")} mx-auto mb-4`}></div>
              <p className={getThemeClasses("text-secondary")}>
                Loading folder...
                {pendingRefresh && (
                  <span className={`block text-sm ${getThemeClasses("text-accent")} mt-2`}>
                    🔄 Refreshing with latest data
                  </span>
                )}
              </p>
            </div>
          </div>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb Navigation */}
        <Breadcrumb
          items={breadcrumbs.map(crumb => ({
            label: crumb.name,
            to: crumb.isCurrent ? undefined : crumb.path,
            icon: crumb.isRoot ? HomeIcon : undefined,
            isActive: crumb.isCurrent
          }))}
        />

        {/* Main Card */}
        <Card>
          {/* Header with icon, title, and actions */}
          <div className={`p-6 border-b ${getThemeClasses("border-secondary")}`}>
            <div className="flex flex-col space-y-4 lg:flex-row lg:items-center lg:justify-between lg:space-y-0">
              <div className="flex-1 min-w-0">
                <div className="flex items-start">
                  {/* Icon */}
                  <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${
                    collection?.customIcon
                      ? "bg-gray-100"
                      : collection?.type === "album"
                        ? "bg-gradient-to-br from-pink-500 to-pink-600"
                        : getThemeClasses("bg-gradient-secondary")
                  }`}>
                    <CollectionIcon
                      customIcon={collection?.customIcon}
                      collectionType={collection?.type}
                      size="xl"
                      iconClassName={collection?.customIcon ? "text-gray-700" : "text-white"}
                    />
                  </div>
                  {/* Title and subtitle */}
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                      {collection?.name || "Locked Folder"}
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg lg:text-xl ${getThemeClasses("text-secondary")} font-medium`}>
                      {filteredSubCollections.length + filteredFiles.length} items
                    </p>
                    {/* Tags Display */}
                    {collectionTags.length > 0 && (
                      <div className="mt-3">
                        <div className="flex items-center gap-2 flex-wrap">
                          <TagIcon className={`h-4 w-4 ${getThemeClasses("text-secondary")}`} />
                          <TagList
                            tags={collectionTags}
                            size="sm"
                            clickable={false}
                          />
                          {collection?.isOwned && (
                            <button
                              onClick={handleEditTags}
                              className={`text-sm ${getThemeClasses("text-secondary")} hover:${getThemeClasses("text-primary")} transition-colors`}
                            >
                              <PencilIcon className="h-3.5 w-3.5" />
                            </button>
                          )}
                        </div>
                      </div>
                    )}
                    {collectionTags.length === 0 && collection?.isOwned && (
                      <button
                        onClick={handleEditTags}
                        className={`mt-3 inline-flex items-center gap-1.5 text-sm ${getThemeClasses("text-secondary")} hover:${getThemeClasses("text-primary")} transition-colors`}
                      >
                        <TagIcon className="h-4 w-4" />
                        <span>Add tags</span>
                      </button>
                    )}
                  </div>
                </div>
              </div>
              {/* Action buttons */}
              <div className="flex-shrink-0 flex flex-wrap items-center gap-3">
                <Button onClick={handleManualRefresh} variant="secondary" size="sm">
                  <span className="inline-flex items-center gap-2">
                    <ArrowPathIcon className="h-4 w-4" />
                    <span>Refresh</span>
                  </span>
                </Button>
                <Button
                  onClick={() =>
                    navigate(`/file-manager/collections/${collection?.id}/share`)
                  }
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ShareIcon className="h-4 w-4" />
                    <span>Share</span>
                  </span>
                </Button>
                <Button
                  onClick={handleUploadToCollection}
                  variant="primary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <CloudArrowUpIcon className="h-4 w-4" />
                    <span>Upload</span>
                  </span>
                </Button>
                {collection?.isOwned && (
                  <Button
                    onClick={handleDeleteClick}
                    variant="danger"
                    size="sm"
                  >
                    <span className="inline-flex items-center gap-2">
                      <TrashIcon className="h-4 w-4" />
                      <span>Delete</span>
                    </span>
                  </Button>
                )}
              </div>
            </div>
          </div>

          {/* Messages */}
          <div className="px-6">
            {error && (
              <Alert type="error" className="mb-4">
                {error}
              </Alert>
            )}
            {success && (
              <Alert type="success" className="mb-4">
                {success}
              </Alert>
            )}
          </div>

          {/* Toolbar */}
          <div className="px-6 pb-6">
            <div className={`${getThemeClasses("bg-muted")} p-4 rounded-lg`}>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4 flex-1">
                  <div className="relative flex-1 max-w-md">
                    <MagnifyingGlassIcon className={`absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 ${getThemeClasses("text-secondary")}`} />
                    <Input
                      type="text"
                      value={searchQuery}
                      onChange={(value) => setSearchQuery(value)}
                      placeholder="Search in this folder..."
                      className="pl-10"
                    />
                  </div>
                  <div className={`flex items-center ${getThemeClasses("bg-card")} rounded-lg p-1 border ${getThemeClasses("border-secondary")}`}>
                    <button
                      onClick={() => setViewMode("grid")}
                      className={`p-2 rounded ${
                        viewMode === "grid"
                          ? `${getThemeClasses("bg-primary")} text-white shadow-sm`
                          : `${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-primary")}`
                      } transition-all duration-200`}
                    >
                      <ViewColumnsIcon className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => setViewMode("list")}
                      className={`p-2 rounded ${
                        viewMode === "list"
                          ? `${getThemeClasses("bg-primary")} text-white shadow-sm`
                          : `${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-primary")}`
                      } transition-all duration-200`}
                    >
                      <ListBulletIcon className="h-4 w-4" />
                    </button>
                  </div>

                  {/* Tag Filter Dropdown */}
                  {availableTags.length > 0 && (
                    <div className="relative">
                      <Button
                        onClick={() => setShowTagFilterMenu(!showTagFilterMenu)}
                        variant={selectedTagIds.length > 0 ? "primary" : "secondary"}
                        size="sm"
                      >
                        <span className="inline-flex items-center gap-2">
                          {selectedTagIds.length > 0 ? (
                            <>
                              <div className="flex items-center -space-x-1">
                                {selectedTagIds.slice(0, 3).map(tagId => {
                                  const tag = availableTags.find(t => t.id === tagId);
                                  return (
                                    <span
                                      key={tagId}
                                      className="h-3 w-3 rounded-full border border-white"
                                      style={{ backgroundColor: tag?.color || '#6b7280' }}
                                    ></span>
                                  );
                                })}
                              </div>
                              <span>
                                {selectedTagIds.length === 1
                                  ? availableTags.find(t => t.id === selectedTagIds[0])?.name || 'Tag'
                                  : `${selectedTagIds.length} tags`}
                              </span>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setSelectedTagIds([]);
                                }}
                                className="ml-1 hover:opacity-70"
                              >
                                <XMarkIcon className="h-3 w-3" />
                              </button>
                            </>
                          ) : (
                            <>
                              <FunnelIcon className="h-4 w-4" />
                              <span>Filter by Tag</span>
                            </>
                          )}
                        </span>
                      </Button>

                      {showTagFilterMenu && (
                        <>
                          <div
                            className="fixed inset-0 z-10"
                            onClick={() => setShowTagFilterMenu(false)}
                          ></div>
                          <div
                            className={`absolute right-0 mt-2 w-64 ${getThemeClasses("bg-card")} rounded-xl shadow-xl border ${getThemeClasses("border")} py-2 z-20 max-h-80 overflow-y-auto`}
                          >
                            {/* Header with clear button */}
                            <div className="px-4 py-2 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between">
                              <span className={`text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}>
                                Filter by Tags
                              </span>
                              {selectedTagIds.length > 0 && (
                                <button
                                  onClick={() => setSelectedTagIds([])}
                                  className={`text-xs ${getThemeClasses("text-secondary")} hover:${getThemeClasses("text-primary")} transition-colors`}
                                >
                                  Clear all
                                </button>
                              )}
                            </div>

                            {/* Available tags with checkboxes */}
                            {availableTags.map((tag) => {
                              const isSelected = selectedTagIds.includes(tag.id);
                              return (
                                <button
                                  key={tag.id}
                                  onClick={() => {
                                    if (isSelected) {
                                      setSelectedTagIds(selectedTagIds.filter(id => id !== tag.id));
                                    } else {
                                      setSelectedTagIds([...selectedTagIds, tag.id]);
                                    }
                                  }}
                                  className={`w-full text-left px-4 py-2.5 transition-colors duration-200 ${
                                    isSelected
                                      ? getThemeClasses("bg-muted")
                                      : `hover:${getThemeClasses("bg-hover")}`
                                  }`}
                                >
                                  <div className="flex items-center space-x-3">
                                    <input
                                      type="checkbox"
                                      checked={isSelected}
                                      onChange={() => {}}
                                      className={`h-4 w-4 rounded ${getThemeClasses("checkbox-focus")}`}
                                    />
                                    <span
                                      className="h-4 w-4 rounded-full flex-shrink-0"
                                      style={{ backgroundColor: tag.color || '#6b7280' }}
                                    ></span>
                                    <span
                                      className={`text-sm font-medium truncate ${
                                        isSelected
                                          ? getThemeClasses("text-primary")
                                          : "text-gray-900 dark:text-gray-100"
                                      }`}
                                    >
                                      {tag.name}
                                    </span>
                                  </div>
                                </button>
                              );
                            })}

                            {/* Footer note */}
                            {selectedTagIds.length > 1 && (
                              <div className="px-4 py-2 border-t border-gray-100 dark:border-gray-700">
                                <span className={`text-xs ${getThemeClasses("text-secondary")}`}>
                                  Showing files with all selected tags
                                </span>
                              </div>
                            )}
                          </div>
                        </>
                      )}
                    </div>
                  )}
                </div>
                <div className="flex items-center space-x-3">
                  <Button
                    onClick={handleCreateSubCollection}
                    variant="secondary"
                    size="sm"
                  >
                    <span className="inline-flex items-center gap-2">
                      <PlusIcon className="h-4 w-4" />
                      <span>New Folder</span>
                    </span>
                  </Button>
                </div>
              </div>
            </div>
          </div>

          {/* Sub-Collections (Folders) */}
          {filteredSubCollections.length > 0 && (
            <div className="px-6 pb-6">
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4`}>
                Folders
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {filteredSubCollections.map((subCol) => (
                  <Card
                    key={subCol.id}
                    onClick={() => navigate(`/file-manager/collections/${subCol.id}`)}
                    className="cursor-pointer hover:shadow-lg transition-all duration-200 aspect-square !border-4"
                  >
                    <div className="p-4 h-full flex flex-col">
                      <div className="flex-1 flex flex-col items-center justify-center text-center">
                        <div className="mb-3">
                          <TagColorIndicator
                            tags={subCollectionTagsMap[subCol.id] || []}
                            variant="border"
                            size="md"
                          >
                            {(borderStyle) => (
                              <div
                                className={`h-16 w-16 rounded-2xl flex items-center justify-center transition-all duration-200 shadow-lg ${
                                  subCol.customIcon
                                    ? "bg-gray-100"
                                    : subCol.type === "album"
                                      ? "bg-gradient-to-br from-pink-500 to-pink-600"
                                      : getThemeClasses("bg-gradient-secondary")
                                }`}
                                style={borderStyle}
                              >
                                <CollectionIcon
                                  customIcon={subCol.customIcon}
                                  collectionType={subCol.type}
                                  size="lg"
                                  iconClassName={subCol.customIcon ? "text-gray-700" : "text-white"}
                                />
                              </div>
                            )}
                          </TagColorIndicator>
                        </div>
                        <h3 className={`text-sm font-semibold ${getThemeClasses("text-primary")} truncate w-full`}>
                          {subCol.name}
                        </h3>
                        {/* Tag color dots */}
                        {subCollectionTagsMap[subCol.id] && subCollectionTagsMap[subCol.id].length > 0 && (
                          <div className="mt-2">
                            <TagColorIndicator
                              tags={subCollectionTagsMap[subCol.id]}
                              variant="dots"
                              size="sm"
                            />
                          </div>
                        )}
                      </div>
                      <div className={`text-xs ${getThemeClasses("text-muted")} text-center pt-2 border-t-4 ${getThemeClasses("border-secondary")}`}>
                        <div>Folder</div>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </div>
          )}

          {/* Files Grid View */}
          {filteredFiles.length > 0 && viewMode === "grid" && (
            <div className="px-6 pb-6">
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4`}>
                Files
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {filteredFiles.map((file, index) => (
                  <div
                    key={file.id}
                    className={`${getThemeClasses("bg-card")} rounded-lg border ${getThemeClasses("border-secondary")} ${getThemeClasses("hover:shadow")} group animate-fade-in-up relative`}
                    style={{ animationDelay: `${(index + 4) * 50}ms` }}
                  >
                    <div
                      className="p-4 cursor-pointer"
                      onClick={() =>
                        navigate(`/file-manager/files/${file.id}`)
                      }
                    >
                      <div
                        className="absolute top-4 left-4"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <input
                          type="checkbox"
                          checked={selectedFiles.has(file.id)}
                          onChange={() => toggleFileSelection(file.id)}
                          className={`h-4 w-4 rounded ${getThemeClasses("checkbox-focus")}`}
                        />
                      </div>
                      <div className="mb-4 mt-8">
                        <TagColorIndicator
                          tags={fileTagsMap[file.id] || []}
                          variant="border"
                          size="md"
                        >
                          {(borderStyle) => (
                            <div
                              className={`h-32 ${getThemeClasses("bg-muted")} rounded-lg flex items-center justify-center`}
                              style={borderStyle}
                            >
                              {getFileIcon(file.mime_type, "h-12 w-12")}
                            </div>
                          )}
                        </TagColorIndicator>
                      </div>
                      <div className="space-y-2">
                        <div className="flex items-start justify-between">
                          <h3 className={`text-sm font-medium ${getThemeClasses("text-primary")} truncate flex-1 pr-2`}>
                            {file.name}
                          </h3>
                          <button
                            onClick={(e) => e.stopPropagation()}
                            className="flex-shrink-0"
                          >
                            {file.isFavorite ? (
                              <StarIconSolid className={`h-4 w-4 ${getThemeClasses("text-warning")}`} />
                            ) : (
                              <StarIcon className={`h-4 w-4 ${getThemeClasses("text-muted")} hover:opacity-80`} />
                            )}
                          </button>
                        </div>
                        {/* Tag color dots */}
                        {fileTagsMap[file.id] && fileTagsMap[file.id].length > 0 && (
                          <div className="mt-1">
                            <TagColorIndicator
                              tags={fileTagsMap[file.id]}
                              variant="dots"
                              size="sm"
                            />
                          </div>
                        )}
                        <div className={`flex items-center justify-between text-xs ${getThemeClasses("text-secondary")}`}>
                          <span>
                            {formatFileSize(
                              file.size || file.encrypted_file_size_in_bytes,
                            )}
                          </span>
                          <span className="flex items-center">
                            <ClockIcon className="h-3 w-3 mr-1" />
                            {getTimeAgo(file.modified_at || file.created_at)}
                          </span>
                        </div>
                      </div>
                      <div
                        className={`mt-3 pt-3 border-t ${getThemeClasses("border-secondary")} flex items-center justify-center space-x-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200`}
                        onClick={(e) => e.stopPropagation()}
                      >
                        <button
                          onClick={() =>
                            handleDownloadFile(file.id, file.name)
                          }
                          disabled={downloadingFiles.has(file.id)}
                          className={`p-2 ${getThemeClasses("text-secondary")} hover:opacity-80 ${getThemeClasses("bg-muted")} rounded-lg transition-all duration-200 disabled:opacity-50`}
                        >
                          {downloadingFiles.has(file.id) ? (
                            <div className={`animate-spin rounded-full h-4 w-4 border-b ${getThemeClasses("border-primary")}`}></div>
                          ) : (
                            <ArrowDownTrayIcon className="h-4 w-4" />
                          )}
                        </button>
                        <button
                          onClick={handleShareCollection}
                          className={`p-2 ${getThemeClasses("text-secondary")} hover:opacity-80 ${getThemeClasses("bg-muted")} rounded-lg transition-all duration-200`}
                          title="Share collection"
                        >
                          <ShareIcon className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => handleDeleteFile(file.id, file.name)}
                          className={`p-2 ${getThemeClasses("text-error")} hover:opacity-80 ${getThemeClasses("alert-error-bg")} rounded-lg transition-all duration-200`}
                          title="Move to trash"
                        >
                          <TrashIcon className="h-4 w-4" />
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Files List View */}
          {filteredFiles.length > 0 && viewMode === "list" && (
            <div className="px-6 pb-6">
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4`}>
                Files
              </h2>
              <div className={`${getThemeClasses("bg-card")} rounded-lg border ${getThemeClasses("border-secondary")} overflow-hidden`}>
                <table className="w-full">
                  <thead className={`${getThemeClasses("bg-muted")} border-b ${getThemeClasses("border-secondary")}`}>
                    <tr>
                      <th className="px-4 py-3 text-left">
                        <input
                          type="checkbox"
                          checked={
                            selectedFiles.size === filteredFiles.length &&
                            filteredFiles.length > 0
                          }
                          onChange={() => {
                            if (selectedFiles.size === filteredFiles.length) {
                              setSelectedFiles(new Set());
                            } else {
                              setSelectedFiles(
                                new Set(filteredFiles.map((f) => f.id)),
                              );
                            }
                          }}
                          className={`h-4 w-4 rounded ${getThemeClasses("checkbox-focus")}`}
                        />
                      </th>
                      <th className={`px-4 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}>
                        Name
                      </th>
                      <th className={`px-4 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}>
                        Size
                      </th>
                      <th className={`px-4 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}>
                        Modified
                      </th>
                      <th className="px-4 py-3"></th>
                    </tr>
                  </thead>
                  <tbody className={`divide-y ${getThemeClasses("border-secondary")}`}>
                    {filteredFiles.map((file) => (
                      <tr
                        key={file.id}
                        className={`${getThemeClasses("hover:bg-muted")} transition-colors duration-200 cursor-pointer`}
                        onClick={() =>
                          navigate(`/file-manager/files/${file.id}`)
                        }
                      >
                        <td
                          className="px-4 py-3"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <input
                            type="checkbox"
                            checked={selectedFiles.has(file.id)}
                            onChange={() => toggleFileSelection(file.id)}
                            className={`h-4 w-4 rounded ${getThemeClasses("checkbox-focus")}`}
                          />
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center space-x-3">
                            <TagColorIndicator
                              tags={fileTagsMap[file.id] || []}
                              variant="border"
                              size="sm"
                            >
                              {(borderStyle) => (
                                <div
                                  className={`p-1 rounded ${getThemeClasses("bg-muted")}`}
                                  style={borderStyle}
                                >
                                  {getFileIcon(file.mime_type, "h-5 w-5")}
                                </div>
                              )}
                            </TagColorIndicator>
                            <div className="flex flex-col min-w-0">
                              <span className={`text-sm font-medium ${getThemeClasses("text-primary")} truncate`}>
                                {file.name}
                              </span>
                              {/* Tag color dots for list view */}
                              {fileTagsMap[file.id] && fileTagsMap[file.id].length > 0 && (
                                <div className="mt-0.5">
                                  <TagColorIndicator
                                    tags={fileTagsMap[file.id]}
                                    variant="dots"
                                    size="sm"
                                  />
                                </div>
                              )}
                            </div>
                            {file.isFavorite && (
                              <StarIconSolid className={`h-4 w-4 ${getThemeClasses("text-warning")} flex-shrink-0`} />
                            )}
                          </div>
                        </td>
                        <td className={`px-4 py-3 text-sm ${getThemeClasses("text-secondary")}`}>
                          {formatFileSize(
                            file.size || file.encrypted_file_size_in_bytes,
                          )}
                        </td>
                        <td className={`px-4 py-3 text-sm ${getThemeClasses("text-secondary")}`}>
                          {getTimeAgo(file.modified_at || file.created_at)}
                        </td>
                        <td
                          className="px-4 py-3 text-right"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <div className="flex items-center justify-end space-x-2">
                            <button
                              onClick={() =>
                                handleDownloadFile(file.id, file.name)
                              }
                              disabled={downloadingFiles.has(file.id)}
                              className={`p-2 ${getThemeClasses("text-muted")} hover:opacity-80 ${getThemeClasses("bg-muted")} rounded-lg transition-all duration-200 disabled:opacity-50`}
                              title="Download file"
                            >
                              {downloadingFiles.has(file.id) ? (
                                <div className={`animate-spin rounded-full h-4 w-4 border-b ${getThemeClasses("border-primary")}`}></div>
                              ) : (
                                <ArrowDownTrayIcon className="h-4 w-4" />
                              )}
                            </button>
                            <button
                              onClick={() =>
                                handleDeleteFile(file.id, file.name)
                              }
                              className={`p-2 ${getThemeClasses("text-error")} hover:opacity-80 ${getThemeClasses("alert-error-bg")} rounded-lg transition-all duration-200`}
                              title="Move to trash"
                            >
                              <TrashIcon className="h-4 w-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Tag Filter Empty State */}
          {filteredFiles.length === 0 && filteredSubCollections.length === 0 && selectedTagIds.length > 0 && !searchQuery && (
            <div className="text-center py-8 animate-fade-in px-6">
              <div className={`h-16 w-16 ${getThemeClasses("bg-muted")} rounded-2xl flex items-center justify-center mx-auto mb-4`}>
                <TagIcon className={`h-8 w-8 ${getThemeClasses("text-secondary")}`} />
              </div>
              <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                No files with {selectedTagIds.length === 1 ? 'this tag' : 'these tags'}
              </h3>
              <p className={`text-sm ${getThemeClasses("text-secondary")} mb-6 max-w-md mx-auto`}>
                No files in this folder are tagged with {selectedTagIds.length === 1
                  ? `"${availableTags.find(t => t.id === selectedTagIds[0])?.name || 'this tag'}"`
                  : `all ${selectedTagIds.length} selected tags`}
              </p>
              <Button onClick={() => setSelectedTagIds([])} variant="secondary">
                <span className="inline-flex items-center gap-2">
                  <XMarkIcon className="h-4 w-4" />
                  <span>Clear Tag Filter</span>
                </span>
              </Button>
            </div>
          )}

          {/* Empty State */}
          {filteredFiles.length === 0 &&
            filteredSubCollections.length === 0 && selectedTagIds.length === 0 && (
              <div className="text-center py-8 animate-fade-in px-6">
                <div className={`h-16 w-16 ${getThemeClasses("bg-muted")} rounded-2xl flex items-center justify-center mx-auto mb-4`}>
                  <DocumentIcon className={`h-8 w-8 ${getThemeClasses("text-secondary")}`} />
                </div>
                <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                  {searchQuery ? "No items found" : "This folder is empty"}
                </h3>
                <p className={`text-sm ${getThemeClasses("text-secondary")} mb-6 max-w-md mx-auto`}>
                  {searchQuery
                    ? `No items match "${searchQuery}"`
                    : "Upload files or create folders to get started"}
                </p>
                {!searchQuery && (
                  <div className="flex justify-center space-x-3">
                    <Button
                      onClick={handleUploadToCollection}
                      variant="primary"
                    >
                      <span className="inline-flex items-center gap-2">
                        <CloudArrowUpIcon className="h-4 w-4" />
                        <span>Upload Files</span>
                      </span>
                    </Button>
                    <Button
                      onClick={handleCreateSubCollection}
                      variant="secondary"
                    >
                      <span className="inline-flex items-center gap-2">
                        <PlusIcon className="h-4 w-4" />
                        <span>New Folder</span>
                      </span>
                    </Button>
                  </div>
                )}
              </div>
            )}
        </Card>

        {/* Selected Items Bar */}
        {selectedFiles.size > 0 && (
          <div className="mb-6 animate-fade-in-down">
            <div className={`${getThemeClasses("alert-info-bg")} border ${getThemeClasses("alert-info-border")} p-4 rounded-lg`}>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <CheckCircleIcon className={`h-5 w-5 ${getThemeClasses("text-accent")}`} />
                  <span className={`text-sm font-medium ${getThemeClasses("text-primary")}`}>
                    {selectedFiles.size} item{selectedFiles.size > 1 ? "s" : ""}{" "}
                    selected
                  </span>
                </div>
                <div className="flex items-center space-x-3">
                  <button
                    onClick={handleDeleteSelectedFiles}
                    className={`text-sm ${getThemeClasses("text-error")} font-medium flex items-center hover:opacity-80 transition-opacity`}
                  >
                    <TrashIcon className="h-4 w-4 mr-1" />
                    Delete Selected
                  </button>
                  <button
                    onClick={() => setSelectedFiles(new Set())}
                    className={`text-sm ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-primary")}`}
                  >
                    Clear Selection
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Delete Confirmation Modal */}
        <Modal
          isOpen={showDeleteConfirm}
          onClose={handleCancelDelete}
          title="Delete Folder?"
          icon={<TrashIcon className="h-6 w-6" />}
          iconColor="danger"
        >
          <div className="space-y-4">
            <p className={getThemeClasses("text-secondary")}>
              Are you sure you want to delete "
              <span className="font-semibold">
                {collection?.name || "Locked Folder"}
              </span>
              "? This will permanently delete:
            </p>
            <ul className={`text-sm ${getThemeClasses("text-secondary")} space-y-2 ${getThemeClasses("alert-error-bg")} p-4 rounded-lg`}>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-error")} mr-2`}>•</span>
                <span>All files in this folder</span>
              </li>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-error")} mr-2`}>•</span>
                <span>All sub-folders and their contents</span>
              </li>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-error")} mr-2`}>•</span>
                <span>All files in sub-folders</span>
              </li>
            </ul>
            <p className={`text-sm ${getThemeClasses("text-error")} font-medium`}>
              This action cannot be undone.
            </p>
          </div>
          <div className="flex items-center justify-end space-x-3 mt-6">
            <Button
              onClick={handleCancelDelete}
              disabled={isDeleting}
              variant="secondary"
            >
              Cancel
            </Button>
            <Button
              onClick={handleConfirmDelete}
              disabled={isDeleting}
              variant="danger"
            >
              {isDeleting ? (
                <>
                  <div className={`h-4 w-4 animate-spin rounded-full border-b-2 border-white mr-2`}></div>
                  Deleting...
                </>
              ) : (
                <>
                  <TrashIcon className="h-4 w-4 mr-2" />
                  Delete Folder
                </>
              )}
            </Button>
          </div>
        </Modal>

        {/* Tag Editor Modal */}
        <Modal
          isOpen={showTagEditor}
          onClose={() => !isSavingTags && setShowTagEditor(false)}
          title="Manage Tags"
          icon={<TagIcon className="h-6 w-6" />}
          iconColor="primary"
        >
          <div className="space-y-4">
            <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
              Select tags to organize this folder
            </p>
            <TagSelector
              value={editingTagIds}
              onChange={setEditingTagIds}
              disabled={isSavingTags}
              label=""
              placeholder="Select tags..."
            />
          </div>
          <div className="flex items-center justify-end space-x-3 mt-6">
            <Button
              onClick={() => setShowTagEditor(false)}
              disabled={isSavingTags}
              variant="secondary"
            >
              Cancel
            </Button>
            <Button
              onClick={handleSaveTags}
              disabled={isSavingTags}
              variant="primary"
            >
              {isSavingTags ? (
                <>
                  <div className={`h-4 w-4 animate-spin rounded-full border-b-2 border-white mr-2`}></div>
                  Saving...
                </>
              ) : (
                <>
                  <CheckCircleIcon className="h-4 w-4 mr-2" />
                  Save Tags
                </>
              )}
            </Button>
          </div>
        </Modal>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(CollectionDetails);
