// File: monorepo/web/maplefile-frontend/src/pages/User/FileManager/FileManagerIndex.jsx
// UIX version - Theme-aware File Manager with Layout
import React, { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { useNavigate, useLocation } from "react-router";
import { useFiles, useCrypto, useAuth, useTags } from "../../../services/Services";
import withPasswordProtection from "../../../hocs/withPasswordProtection";
import Layout from "../../../components/Layout/Layout";
import {
  Button,
  Input,
  Alert,
  Modal,
  Checkbox,
  Spinner,
  Card,
  Breadcrumb,
  useUIXTheme,
  CollectionIcon,
} from "../../../components/UIX";
import TagColorIndicator from "../../../components/UIX/TagColorIndicator/TagColorIndicator";
import {
  FolderIcon,
  PhotoIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  CloudArrowUpIcon,
  ArrowPathIcon,
  FunnelIcon,
  UserIcon,
  UsersIcon,
  RectangleStackIcon,
  SparklesIcon,
  ChevronRightIcon,
  LockClosedIcon,
  ShareIcon,
  TrashIcon,
  TagIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";

// Cache the dynamic import to avoid repeated imports in loops
let CollectionCryptoServiceClassCache = null;
const getCollectionCryptoServiceClass = async () => {
  if (!CollectionCryptoServiceClassCache) {
    const module = await import("../../../services/Crypto/CollectionCryptoService.js");
    CollectionCryptoServiceClassCache = module.default;
  }
  return CollectionCryptoServiceClassCache;
};

const FileManagerIndex = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { getThemeClasses } = useUIXTheme();
  const {
    listCollectionManager,
    getCollectionManager,
    deleteCollectionManager,
  } = useFiles();
  const { CollectionCryptoService } = useCrypto();
  const { authManager } = useAuth();
  const { tagManager } = useTags();

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

  const [isLoading, setIsLoading] = useState(true);
  const [isInitialized, setIsInitialized] = useState(false);
  const [generalError, setGeneralError] = useState("");
  const [collectionTagsMap, setCollectionTagsMap] = useState({});
  const [fieldErrors, setFieldErrors] = useState({});
  const [collections, setCollections] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterType, setFilterType] = useState("all");
  const [showFilterMenu, setShowFilterMenu] = useState(false);
  const [hoveredCollection, setHoveredCollection] = useState(null);
  const [collectionCounts, setCollectionCounts] = useState({
    owned: 0,
    shared: 0,
    all: 0,
  });
  const [collectionToDelete, setCollectionToDelete] = useState(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

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

  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("[FileManagerIndex] Loaded available tags for filtering:", tags.length);
          }
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("[FileManagerIndex] Failed to load tags for filtering:", error);
        }
      }
    };
    loadAvailableTags();
  }, [tagManager, authManager]);

  const processCollections = useCallback(
    async (rawCollections) => {
      if (!Array.isArray(rawCollections) || rawCollections.length === 0)
        return [];

      // Process single collection - extracted for parallel execution
      const processSingleCollection = async (collection) => {
        try {
          let processedCollection = { ...collection };

          if (collection.encrypted_name || collection.encrypted_description) {
            let collectionKey = CollectionCryptoService.getCachedCollectionKey(
              collection.id,
            );

            if (!collectionKey && getCollectionManager) {
              try {
                const fullCollection = await getCollectionManager.getCollection(
                  collection.id,
                );
                if (fullCollection.collection_key) {
                  CollectionCryptoService.cacheCollectionKey(
                    collection.id,
                    fullCollection.collection_key,
                  );
                  collectionKey = fullCollection.collection_key;
                }
              } catch (keyError) {
                if (import.meta.env.DEV) {
                  console.warn(
                    `Could not get collection key for ${collection.id}:`,
                    keyError,
                  );
                }
              }
            }

            if (collectionKey) {
              try {
                const CollectionCryptoServiceClass = await getCollectionCryptoServiceClass();

                const decryptedCollection =
                  await CollectionCryptoServiceClass.decryptCollectionFromAPI(
                    collection,
                    collectionKey,
                  );
                processedCollection = decryptedCollection;
              } catch (decryptError) {
                processedCollection.name = "Locked Folder";
                processedCollection._isDecrypted = false;
              }
            } else {
              processedCollection.name = "Locked Folder";
              processedCollection._isDecrypted = false;
            }
          } else {
            processedCollection._isDecrypted = true;
          }

          processedCollection.type = collection.collection_type || "folder";
          processedCollection.fileCount = collection.file_count || 0;
          processedCollection.modified =
            collection.updated_at || collection.created_at;
          // Use decrypted custom_icon from processedCollection if available, otherwise fall back to original
          processedCollection.customIcon = processedCollection.custom_icon || collection.custom_icon || "";

          // A folder is "shared" only if it has members OTHER than the owner
          processedCollection.isShared = !!(
            collection.members &&
            collection.members.length > 0 &&
            collection.members.some(
              (member) => member.recipient_id !== collection.owner_id,
            )
          );
          processedCollection.isOwned =
            collection._isOwned !== undefined ? collection._isOwned : true;

          return processedCollection;
        } catch (error) {
          return {
            ...collection,
            name: "Locked Folder",
            type: "folder",
            fileCount: 0,
            _isDecrypted: false,
            isShared: false,
            isOwned: true,
          };
        }
      };

      // Process all collections in parallel for better performance
      const processedCollections = await Promise.all(
        rawCollections.map(processSingleCollection)
      );

      return processedCollections;
    },
    [CollectionCryptoService, getCollectionManager, authManager],
  );

  const loadCollections = useCallback(
    async (forceRefresh = false, currentFilterType = null) => {
      if (!listCollectionManager) return;

      setIsLoading(true);
      setGeneralError("");
      setFieldErrors({});

      try {
        const activeFilterType = currentFilterType || filterType;
        let result;

        if (import.meta.env.DEV) {
          console.log(
            "[FileManagerIndex] Loading collections with filter:",
            activeFilterType,
          );
        }

        switch (activeFilterType) {
          case "owned":
            result = await listCollectionManager.listCollections(forceRefresh);
            break;
          case "shared":
            result =
              await listCollectionManager.listSharedCollections(forceRefresh);
            break;
          case "all":
            result = await listCollectionManager.listFilteredCollections(
              true,
              true,
              forceRefresh,
            );
            if (result.owned_collections || result.shared_collections) {
              const owned = (result.owned_collections || []).map((c) => ({
                ...c,
                _isOwned: true,
              }));

              const ownedIds = new Set(
                (result.owned_collections || []).map((c) => c.id),
              );

              const shared = (result.shared_collections || [])
                .filter((c) => {
                  const isNotDuplicate = !ownedIds.has(c.id);
                  if (!isNotDuplicate && import.meta.env.DEV) {
                    console.log(
                      "[FileManagerIndex] Filtering out duplicate shared collection:",
                      c.id,
                    );
                  }
                  return isNotDuplicate;
                })
                .map((c) => ({
                  ...c,
                  _isOwned: false,
                }));

              result.collections = [...owned, ...shared];
            }
            break;
          default:
            result = await listCollectionManager.listCollections(forceRefresh);
        }

        if (result.collections) {
          const rootCollections = result.collections.filter(
            (collection) =>
              !collection.parent_id ||
              collection.parent_id === "00000000-0000-0000-0000-000000000000",
          );

          if (import.meta.env.DEV) {
            console.log(
              `[FileManagerIndex] Found ${rootCollections.length} root collections for filter: ${activeFilterType}`,
            );
          }

          const processedCollections =
            await processCollections(rootCollections);

          if (isMountedRef.current) {
            setCollections(processedCollections);
            setIsInitialized(true);
            // Load tags for the collections
            loadCollectionTags(processedCollections);
          }
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error("[FileManagerIndex] Failed to load collections:", err);
        }

        if (isMountedRef.current) {
          // Handle RFC 9457 errors with field-specific validation
          if (err.fieldErrors && Object.keys(err.fieldErrors).length > 0) {
            setFieldErrors(err.fieldErrors);
          }

          if (err.message) {
            setGeneralError(err.message);
          } else {
            setGeneralError("Could not load your folders. Please try again.");
          }
          setIsInitialized(true);
        }
      } finally {
        if (isMountedRef.current) {
          setIsLoading(false);
        }
      }
    },
    [listCollectionManager, filterType, processCollections],
  );

  // Load tags for all collections
  // NOW USES EMBEDDED TAGS - no API call needed!
  const loadCollectionTags = useCallback(
    async (collections) => {
      if (import.meta.env.DEV) {
        console.log("[FileManagerIndex] loadCollectionTags called with:", {
          collectionsCount: collections.length,
          sampleCollection: collections[0]
        });
      }

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

      try {
        // Build a map: collection_id -> array of tag objects
        // Tags are now EMBEDDED in each collection (already decrypted by CollectionCryptoService)
        const tagsMap = {};

        collections.forEach(collection => {
          if (import.meta.env.DEV) {
            console.log(`[FileManagerIndex] Processing collection ${collection.name}:`, {
              id: collection.id,
              hasTags: !!collection.tags,
              tagsLength: collection.tags?.length,
              tags: collection.tags
            });
          }

          // Use embedded tags (already decrypted)
          if (collection.tags && Array.isArray(collection.tags) && collection.tags.length > 0) {
            tagsMap[collection.id] = collection.tags;
            if (import.meta.env.DEV) {
              console.log(`[FileManagerIndex] Collection ${collection.name} has embedded tags:`, collection.tags);
            }
          } else {
            tagsMap[collection.id] = [];
          }
        });

        if (import.meta.env.DEV) {
          console.log("[FileManagerIndex] Final tagsMap (using embedded tags):", tagsMap);
        }

        setCollectionTagsMap(tagsMap);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("[FileManagerIndex] Failed to process collection tags:", error);
        }
        // Don't show error to user - tags are optional
      }
    },
    []  // No dependencies - tags are embedded in collections
  );

  useEffect(() => {
    const fetchCounts = async () => {
      if (!listCollectionManager) return;
      try {
        const result = await listCollectionManager.listFilteredCollections(
          true,
          true,
          false,
        );
        const owned =
          result.owned_collections?.filter(
            (c) =>
              !c.parent_id ||
              c.parent_id === "00000000-0000-0000-0000-000000000000",
          ) || [];

        const ownedIds = new Set(owned.map((c) => c.id));

        const shared =
          result.shared_collections?.filter(
            (c) =>
              (!c.parent_id ||
                c.parent_id === "00000000-0000-0000-0000-000000000000") &&
              !ownedIds.has(c.id),
          ) || [];

        if (isMountedRef.current) {
          setCollectionCounts({
            owned: owned.length,
            shared: shared.length,
            all: owned.length + shared.length,
          });
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error(
            "[FileManagerIndex] Failed to fetch collection counts:",
            err,
          );
        }
      }
    };
    if (authManager?.isAuthenticated()) {
      fetchCounts();
    }
  }, [listCollectionManager, authManager]);

  const handleFilterChange = useCallback(
    (newFilter) => {
      if (import.meta.env.DEV) {
        console.log("[FileManagerIndex] Filter changed to:", newFilter);
      }
      setFilterType(newFilter);
      setShowFilterMenu(false);
      loadCollections(false, newFilter);
    },
    [loadCollections],
  );

  const getTimeAgo = useCallback((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 handleDeleteClick = useCallback((e, collection) => {
    e.stopPropagation();
    setCollectionToDelete(collection);
    setShowDeleteConfirm(true);
  }, []);

  // Memoized handler for collection card navigation
  const handleCollectionClick = useCallback((collectionId) => {
    navigate(`/file-manager/collections/${collectionId}`);
  }, [navigate]);

  // Memoized handler for collection card keyboard navigation
  const handleCollectionKeyDown = useCallback((e, collectionId) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      navigate(`/file-manager/collections/${collectionId}`);
    }
  }, [navigate]);

  // Memoized handlers for hover state
  const handleCollectionMouseEnter = useCallback((collectionId) => {
    setHoveredCollection(collectionId);
  }, []);

  const handleCollectionMouseLeave = useCallback(() => {
    setHoveredCollection(null);
  }, []);

  const handleCancelDelete = useCallback(() => {
    setCollectionToDelete(null);
    setShowDeleteConfirm(false);
  }, []);

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

    if (!collectionToDelete) {
      if (import.meta.env.DEV) {
        console.error("[FileManagerIndex] No collection to delete");
      }
      return;
    }

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

    try {
      setIsDeleting(true);
      if (import.meta.env.DEV) {
        console.log(
          "[FileManagerIndex] Deleting collection:",
          collectionToDelete.id,
        );
      }

      await deleteCollectionManager.deleteCollection(collectionToDelete.id);

      if (import.meta.env.DEV) {
        console.log(
          "[FileManagerIndex] Collection deleted successfully:",
          collectionToDelete.name || "Locked Folder",
        );
      }

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

      // Clear local state immediately
      setCollections([]);

      // Refresh the collection list with force refresh
      await loadCollections(true);

      // Close the confirmation dialog
      setShowDeleteConfirm(false);
      setCollectionToDelete(null);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[FileManagerIndex] Failed to delete collection:", error);
      }

      // Handle RFC 9457 errors with field-specific validation
      if (error.fieldErrors && Object.keys(error.fieldErrors).length > 0) {
        setFieldErrors(error.fieldErrors);
      }

      if (error.message) {
        setGeneralError(`Failed to delete folder: ${error.message}`);
      } else {
        setGeneralError("Failed to delete folder. Please try again.");
      }
    } finally {
      setIsDeleting(false);
    }
  }, [
    collectionToDelete,
    deleteCollectionManager,
    listCollectionManager,
    loadCollections,
  ]);

  // Initial load when managers become available
  useEffect(() => {
    if (listCollectionManager && authManager?.isAuthenticated() && !isInitialized) {
      loadCollections();
    }
  }, [listCollectionManager, authManager, isInitialized, loadCollections]);

  useEffect(() => {
    const handleCollectionEvent = () => {
      if (import.meta.env.DEV) {
        console.log(
          "[FileManagerIndex] Collection event received, refreshing collections",
        );
      }
      if (listCollectionManager && authManager?.isAuthenticated()) {
        loadCollections(true);
      }
    };
    window.addEventListener("collectionCreated", handleCollectionEvent);
    window.addEventListener("rootCollectionCreated", handleCollectionEvent);
    return () => {
      window.removeEventListener("collectionCreated", handleCollectionEvent);
      window.removeEventListener(
        "rootCollectionCreated",
        handleCollectionEvent,
      );
    };
  }, [listCollectionManager, authManager, loadCollections]);

  // Listen for dashboard refresh events
  useEffect(() => {
    const handleDashboardRefresh = () => {
      if (import.meta.env.DEV) {
        console.log(
          "[FileManagerIndex] Dashboard refresh event received, reloading collections",
        );
      }
      if (listCollectionManager && authManager?.isAuthenticated()) {
        loadCollections(true);
      }
    };

    window.addEventListener("dashboardRefresh", handleDashboardRefresh);
    return () => {
      window.removeEventListener("dashboardRefresh", handleDashboardRefresh);
    };
  }, [listCollectionManager, authManager, loadCollections]);

  useEffect(() => {
    if (location.state?.refresh) {
      if (location.state?.newRootCollectionCreated && import.meta.env.DEV) {
        console.log(
          "[FileManagerIndex] Forcing refresh due to new root collection creation",
        );
      } else if (
        location.state?.reason === "collection_deleted" &&
        import.meta.env.DEV
      ) {
        console.log(
          "[FileManagerIndex] Forcing refresh due to collection deletion",
        );
      } else if (import.meta.env.DEV) {
        console.log(
          "[FileManagerIndex] Forcing refresh due to:",
          location.state?.reason || "unknown reason",
        );
      }

      if (listCollectionManager && authManager?.isAuthenticated()) {
        loadCollections(true);
      }
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [
    location.state,
    listCollectionManager,
    authManager,
    loadCollections,
    navigate,
    location.pathname,
  ]);

  // Memoize filtered collections to prevent recalculation on every render
  const filteredCollections = useMemo(() => {
    return collections.filter((collection) => {
      // Filter by search query
      if (searchQuery) {
        const query = searchQuery.toLowerCase();
        if (!(collection.name || "Locked Folder").toLowerCase().includes(query)) {
          return false;
        }
      }

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

      return true;
    });
  }, [collections, searchQuery, selectedTagIds, collectionTagsMap]);

  // Memoize filter types to prevent recreation on every render
  const filterTypes = useMemo(() => [
    {
      key: "owned",
      label: "My Folders",
      icon: UserIcon,
      description: "Folders you own",
      count: collectionCounts.owned,
    },
    {
      key: "shared",
      label: "Shared with Me",
      icon: UsersIcon,
      description: "Folders shared with you",
      count: collectionCounts.shared,
    },
    {
      key: "all",
      label: "All Folders",
      icon: RectangleStackIcon,
      description: "All folders you can access",
      count: collectionCounts.all,
    },
  ], [collectionCounts]);

  const currentFilter = useMemo(
    () => filterTypes.find((f) => f.key === filterType),
    [filterTypes, filterType]
  );

  // Memoize breadcrumb items (static)
  const breadcrumbItems = useMemo(() => [
    {
      label: "My Files",
      icon: HomeIcon,
      isActive: true,
    },
  ], []);

  return (
    <Layout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb Navigation */}
        <Breadcrumb items={breadcrumbItems} />

        {/* Main Card */}
        <Card>
          {/* Header with icon, title, and action buttons */}
          <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 ${getThemeClasses("bg-gradient-secondary")}`}>
                    <FolderIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                  </div>
                  {/* Title and subtitle */}
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                      My Files
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Organize and manage your encrypted files
                    </p>
                  </div>
                </div>
              </div>
              {/* Action buttons */}
              <div className="flex-shrink-0 flex items-center space-x-3">
              {/* Tag Filter Menu */}
              {availableTags.length > 0 && (
                <div className="relative">
                  <Button
                    onClick={() => setShowTagFilterMenu(!showTagFilterMenu)}
                    variant={selectedTagIds.length > 0 ? "primary" : "secondary"}
                  >
                    <span className="inline-flex items-center whitespace-nowrap">
                      {selectedTagIds.length > 0 ? (
                        <>
                          <span className="flex items-center -space-x-1 mr-2 flex-shrink-0">
                            {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>
                              );
                            })}
                          </span>
                          {selectedTagIds.length === 1
                            ? availableTags.find(t => t.id === selectedTagIds[0])?.name || 'Tag'
                            : `${selectedTagIds.length} tags`}
                          <Button
                            onClick={(e) => {
                              e.stopPropagation();
                              setSelectedTagIds([]);
                            }}
                            variant="ghost"
                            size="sm"
                            className="ml-1 p-0 min-w-0 h-auto"
                            aria-label="Clear tag filter"
                          >
                            <span className="text-xs">✕</span>
                          </Button>
                        </>
                      ) : (
                        <>
                          <TagIcon className="h-4 w-4 mr-2 flex-shrink-0" />
                          All Tags
                        </>
                      )}
                      <ChevronRightIcon
                        className={`h-4 w-4 ml-2 flex-shrink-0 transition-transform duration-200 ${
                          showTagFilterMenu ? "rotate-90" : ""
                        }`}
                      />
                    </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 text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                            Filter by Tags
                          </span>
                          {selectedTagIds.length > 0 && (
                            <Button
                              onClick={() => setSelectedTagIds([])}
                              variant="ghost"
                              size="sm"
                              className="text-xs"
                            >
                              Clear all
                            </Button>
                          )}
                        </div>

                        {/* Available tags with checkboxes */}
                        {availableTags.map((tag) => {
                          const isSelected = selectedTagIds.includes(tag.id);
                          return (
                            <div
                              key={tag.id}
                              role="checkbox"
                              tabIndex={0}
                              aria-checked={isSelected}
                              aria-label={`Filter by tag: ${tag.name}`}
                              className={`w-full px-4 py-2.5 transition-colors duration-200 cursor-pointer ${
                                isSelected
                                  ? getThemeClasses("bg-muted")
                                  : `hover:${getThemeClasses("bg-hover")}`
                              }`}
                              onClick={() => {
                                if (isSelected) {
                                  setSelectedTagIds(selectedTagIds.filter(id => id !== tag.id));
                                } else {
                                  setSelectedTagIds([...selectedTagIds, tag.id]);
                                }
                              }}
                              onKeyDown={(e) => {
                                if (e.key === "Enter" || e.key === " ") {
                                  e.preventDefault();
                                  if (isSelected) {
                                    setSelectedTagIds(selectedTagIds.filter(id => id !== tag.id));
                                  } else {
                                    setSelectedTagIds([...selectedTagIds, tag.id]);
                                  }
                                }
                              }}
                            >
                              <div className="flex items-center space-x-3">
                                <Checkbox
                                  checked={isSelected}
                                  onChange={(checked) => {
                                    if (checked) {
                                      setSelectedTagIds([...selectedTagIds, tag.id]);
                                    } else {
                                      setSelectedTagIds(selectedTagIds.filter(id => id !== tag.id));
                                    }
                                  }}
                                />
                                <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>
                            </div>
                          );
                        })}

                        {/* Footer note */}
                        {selectedTagIds.length > 1 && (
                          <div className="px-4 py-2 border-t border-gray-100 dark:border-gray-700">
                            <span className="text-xs text-gray-500 dark:text-gray-400">
                              Showing folders with all selected tags
                            </span>
                          </div>
                        )}
                      </div>
                    </>
                  )}
                </div>
              )}

              {/* Filter Menu */}
              <div className="relative">
                <Button
                  onClick={() => setShowFilterMenu(!showFilterMenu)}
                  variant="secondary"
                >
                  <span className="inline-flex items-center whitespace-nowrap">
                    <FunnelIcon className="h-4 w-4 mr-2 flex-shrink-0" />
                    {currentFilter.label}
                    <ChevronRightIcon
                      className={`h-4 w-4 ml-2 flex-shrink-0 transition-transform duration-200 ${
                        showFilterMenu ? "rotate-90" : ""
                      }`}
                    />
                  </span>
                </Button>

                {showFilterMenu && (
                  <>
                    <div
                      className="fixed inset-0 z-10"
                      onClick={() => setShowFilterMenu(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`}
                    >
                      {filterTypes.map((filter) => (
                        <div
                          key={filter.key}
                          role="button"
                          tabIndex={0}
                          onClick={() => handleFilterChange(filter.key)}
                          onKeyDown={(e) => e.key === 'Enter' && handleFilterChange(filter.key)}
                          className={`w-full text-left px-4 py-3 transition-colors duration-200 cursor-pointer ${
                            filterType === filter.key
                              ? getThemeClasses("bg-muted")
                              : `hover:${getThemeClasses("bg-hover")}`
                          }`}
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-3">
                              <filter.icon
                                className={`h-5 w-5 ${
                                  filterType === filter.key
                                    ? getThemeClasses("text-primary")
                                    : "text-gray-500"
                                }`}
                              />
                              <div>
                                <p
                                  className={`text-sm font-medium ${
                                    filterType === filter.key
                                      ? getThemeClasses("text-primary")
                                      : "text-gray-900 dark:text-gray-100"
                                  }`}
                                >
                                  {filter.label}
                                </p>
                                <p className="text-xs text-gray-500 dark:text-gray-400">
                                  {filter.description}
                                </p>
                              </div>
                            </div>
                            <span
                              className={`text-sm font-medium ${
                                filterType === filter.key
                                  ? getThemeClasses("text-primary")
                                  : "text-gray-500"
                              }`}
                            >
                              {filter.count}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>

              <Button
                onClick={() => loadCollections(true)}
                disabled={isLoading}
                variant="secondary"
                icon={ArrowPathIcon}
                className={isLoading ? "[&>svg]:animate-spin" : ""}
              >
                Refresh
              </Button>

              <Button
                onClick={() => navigate("/file-manager/upload")}
                variant="primary"
                icon={CloudArrowUpIcon}
              >
                Upload
              </Button>
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="p-6">
            {/* Search Bar */}
            <div className="mb-6">
              <div className="relative max-w-2xl">
                <MagnifyingGlassIcon className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                <Input
                  type="text"
                  value={searchQuery}
                  onChange={setSearchQuery}
                  placeholder="Search folders..."
                  aria-label="Search folders"
                  className="pl-12 h-12 text-base w-full"
                />
                {searchQuery && (
                  <Button
                    onClick={() => setSearchQuery("")}
                    variant="ghost"
                    size="sm"
                    className="absolute right-4 top-1/2 transform -translate-y-1/2"
                    aria-label="Clear search"
                  >
                    ✕
                  </Button>
                )}
              </div>
            </div>

            {/* Error Display */}
            {(generalError || Object.keys(fieldErrors).length > 0) && (
              <Alert type="error" className="mb-6">
                {generalError && <p>{generalError}</p>}
                {Object.keys(fieldErrors).length > 0 && (
                  <div className="mt-2">
                    <p className="font-semibold mb-1">
                      Please fix the following errors:
                    </p>
                    <ul className="list-disc list-inside space-y-1">
                      {Object.entries(fieldErrors).map(([field, message]) => (
                        <li key={field}>
                          <span className="font-medium capitalize">{field}:</span>{" "}
                          {message}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </Alert>
            )}

            {/* Collections Grid */}
            {isLoading ? (
              <div className="flex items-center justify-center py-24">
                <div className="text-center">
                  <Spinner size="lg" className="mx-auto mb-4" />
                  <p className="text-gray-600 dark:text-gray-400">
                    Loading folders...
                  </p>
                </div>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {filteredCollections.map((collection, index) => (
              <div
                key={collection.id}
                role="article"
                tabIndex={0}
                aria-label={`Folder: ${collection.name || "Locked Folder"}, ${collection.fileCount} ${collection.fileCount === 1 ? "file" : "files"}${collection.isShared ? ", shared" : ""}`}
                className={`${getThemeClasses("bg-card")} rounded-xl border ${getThemeClasses("border")} shadow-sm hover:shadow-md cursor-pointer transition-all duration-200 group relative focus:outline-none focus:ring-2 ${getThemeClasses("focus:ring-primary")}`}
                onClick={() => handleCollectionClick(collection.id)}
                onKeyDown={(e) => handleCollectionKeyDown(e, collection.id)}
                onMouseEnter={() => handleCollectionMouseEnter(collection.id)}
                onMouseLeave={handleCollectionMouseLeave}
              >
                {/* Delete Button - Only show if user is owner */}
                {collection.isOwned && (
                  <Button
                    onClick={(e) => handleDeleteClick(e, collection)}
                    variant="danger"
                    size="sm"
                    className="absolute top-4 right-4 opacity-0 group-hover:opacity-100 z-10"
                    aria-label={`Delete folder ${collection.name || 'Locked Folder'}`}
                  >
                    <TrashIcon className="h-4 w-4" />
                  </Button>
                )}

                <div className="p-6">
                  <div className="mb-4">
                    <TagColorIndicator
                      tags={collectionTagsMap[collection.id] || []}
                      variant="border"
                      size="md"
                    >
                      {(borderStyle) => (
                        <div
                          className={`h-14 w-14 rounded-xl flex items-center justify-center transition-all duration-200 ${
                            collection.customIcon
                              ? "bg-gray-100 group-hover:bg-gray-200"
                              : collection.type === "album"
                                ? "bg-gradient-to-br from-pink-500 to-pink-600 group-hover:from-pink-600 group-hover:to-pink-700"
                                : "bg-gradient-to-br from-blue-500 to-blue-600 group-hover:from-blue-600 group-hover:to-blue-700"
                          }`}
                          style={borderStyle}
                        >
                          <CollectionIcon
                            customIcon={collection.customIcon}
                            collectionType={collection.type}
                            size="lg"
                            iconClassName={collection.customIcon ? "text-gray-700" : "text-white"}
                          />
                        </div>
                      )}
                    </TagColorIndicator>
                  </div>

                  <div className="space-y-3">
                    <div>
                      <h3
                        className={`font-semibold text-lg flex items-center justify-between ${getThemeClasses("text-primary")}`}
                      >
                        <span className="truncate">
                          {collection.name || "Locked Folder"}
                        </span>
                        {!collection._isDecrypted && (
                          <LockClosedIcon className="h-4 w-4 text-gray-400 flex-shrink-0 ml-2" />
                        )}
                      </h3>
                      <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                        {collection.fileCount > 0
                          ? `${collection.fileCount} ${collection.fileCount === 1 ? "file" : "files"} here`
                          : "Empty folder"}
                      </p>
                      {/* Tag badges with names */}
                      {collectionTagsMap[collection.id] && collectionTagsMap[collection.id].length > 0 && (
                        <div className="mt-2 flex flex-wrap gap-1.5">
                          {collectionTagsMap[collection.id].slice(0, 3).map((tag) => (
                            <span
                              key={tag.id}
                              className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium"
                              style={{
                                backgroundColor: tag.color ? `${tag.color}20` : '#e5e7eb',
                                color: tag.color || '#6b7280',
                                borderLeft: `3px solid ${tag.color || '#6b7280'}`
                              }}
                              title={tag.name}
                            >
                              {tag.name}
                            </span>
                          ))}
                          {collectionTagsMap[collection.id].length > 3 && (
                            <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300">
                              +{collectionTagsMap[collection.id].length - 3}
                            </span>
                          )}
                        </div>
                      )}
                    </div>

                    <div className={`flex items-center justify-between pt-3 border-t ${getThemeClasses("border-muted")}`}>
                      <span className={`text-xs ${getThemeClasses("text-secondary")}`}>
                        {getTimeAgo(collection.modified)}
                      </span>
                      <div className="flex items-center space-x-2">
                        {collection.isShared && (
                          <div
                            className={`flex items-center space-x-1 px-2 py-1 rounded-full text-xs font-medium ${
                              collection.isOwned
                                ? `${getThemeClasses("bg-success-light")} ${getThemeClasses("text-success")}`
                                : `${getThemeClasses("bg-info-light")} ${getThemeClasses("text-info")}`
                            }`}
                          >
                            <ShareIcon className="h-3 w-3" />
                            <span>
                              {collection.isOwned ? "Shared" : "With me"}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                <div
                  className={`absolute inset-0 rounded-xl border-2 border-transparent transition-all duration-200 pointer-events-none ${
                    hoveredCollection === collection.id
                      ? getThemeClasses("border-accent")
                      : ""
                  }`}
                ></div>
              </div>
            ))}

            {/* Only show New Folder card when there are existing folders */}
            {(filterType === "owned" || filterType === "all") && filteredCollections.length > 0 && (
              <div
                role="button"
                tabIndex={0}
                aria-label="Create new folder"
                onClick={() => navigate("/file-manager/collections/create")}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    navigate("/file-manager/collections/create");
                  }
                }}
                className={`group ${getThemeClasses("bg-card")} rounded-xl border-2 border-dashed ${getThemeClasses("border")} ${getThemeClasses("hover:border-primary")} cursor-pointer transition-all duration-300 focus:outline-none focus:ring-2 ${getThemeClasses("focus:ring-primary")}`}
              >
                <div className="p-6 text-center">
                  <div
                    className={`h-14 w-14 rounded-xl ${getThemeClasses("bg-muted")} ${getThemeClasses("group-hover:bg-accent-light")} flex items-center justify-center mx-auto mb-4 transition-colors duration-200`}
                  >
                    <PlusIcon
                      className={`h-7 w-7 text-gray-400 ${getThemeClasses("group-hover:text-primary")} transition-colors duration-200`}
                    />
                  </div>
                  <h3 className="font-semibold text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-gray-100 text-lg transition-colors duration-200">
                    New Folder
                  </h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    Create a new encrypted folder
                  </p>
                </div>
              </div>
            )}
              </div>
            )}

            {/* Tag Filter Empty State */}
            {!isLoading && filteredCollections.length === 0 && selectedTagIds.length > 0 && !searchQuery && (
              <div className="text-center py-24">
                <div
                  className={`h-20 w-20 ${getThemeClasses("bg-muted")} rounded-2xl flex items-center justify-center mx-auto mb-6`}
                >
                  <TagIcon className="h-10 w-10 text-gray-400" />
                </div>
                <h3
                  className={`text-xl font-semibold mb-2 ${getThemeClasses("text-primary")}`}
                >
                  No folders with {selectedTagIds.length === 1 ? 'this tag' : 'these tags'}
                </h3>
                <p className="text-gray-600 dark:text-gray-400 mb-8 max-w-md mx-auto">
                  No folders 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">
                  <TagIcon className="h-4 w-4 mr-2" />
                  Clear Tag Filter
                </Button>
              </div>
            )}

            {/* Empty State */}
            {!isLoading && filteredCollections.length === 0 && !searchQuery && selectedTagIds.length === 0 && (
              <div className="text-center">
                <div
                  className={`h-20 w-20 ${getThemeClasses("bg-muted")} rounded-2xl flex items-center justify-center mx-auto mb-0.5`}
                >
                  <currentFilter.icon className="h-10 w-10 text-gray-400" />
                </div>
                <h3
                  className={`text-xl font-semibold mb-2 ${getThemeClasses("text-primary")}`}
                >
                  {filterType === "shared"
                    ? "No shared folders"
                    : filterType === "all"
                      ? "No folders found"
                      : "No folders yet"}
                </h3>
                <p className="text-gray-600 dark:text-gray-400 mb-8 max-w-md mx-auto">
                  {filterType === "shared"
                    ? "When someone shares a folder with you, it will appear here"
                    : "Create your first folder now"}
                </p>
                {filterType !== "shared" && (
                  <Button
                    onClick={() => navigate("/file-manager/collections/create")}
                    variant="primary"
                    icon={PlusIcon}
                  >
                    Create Your First Folder
                  </Button>
                )}
              </div>
            )}

            {/* Search Empty State */}
            {!isLoading && filteredCollections.length === 0 && searchQuery && (
              <div className="text-center py-24">
                <div
                  className={`h-20 w-20 ${getThemeClasses("bg-muted")} rounded-2xl flex items-center justify-center mx-auto mb-6`}
                >
                  <MagnifyingGlassIcon className="h-10 w-10 text-gray-400" />
                </div>
                <h3
                  className={`text-xl font-semibold mb-2 ${getThemeClasses("text-primary")}`}
                >
                  No folders found
                </h3>
                <p className="text-gray-600 dark:text-gray-400 mb-8">
                  No folders match your search for "{searchQuery}"
                  {selectedTagIds.length > 0 && ` with ${selectedTagIds.length === 1
                    ? `tag "${availableTags.find(t => t.id === selectedTagIds[0])?.name || 'selected tag'}"`
                    : `${selectedTagIds.length} selected tags`}`}
                </p>
                <div className="flex items-center justify-center space-x-3">
                  <Button onClick={() => setSearchQuery("")} variant="secondary">
                    Clear search
                  </Button>
                  {selectedTagIds.length > 0 && (
                    <Button onClick={() => setSelectedTagIds([])} variant="secondary">
                      Clear tag filter
                    </Button>
                  )}
                </div>
              </div>
            )}
          </div>
        </Card>

      </div>

      {/* Delete Confirmation Modal */}
      <Modal
        isOpen={showDeleteConfirm && !!collectionToDelete}
        onClose={handleCancelDelete}
        title="Delete Folder?"
        footer={
          <div className="flex items-center justify-end space-x-3">
            <Button
              onClick={handleCancelDelete}
              disabled={isDeleting}
              variant="secondary"
            >
              Cancel
            </Button>
            <Button
              onClick={handleConfirmDelete}
              disabled={isDeleting}
              variant="danger"
              loading={isDeleting}
              loadingText="Deleting..."
            >
              <TrashIcon className="h-4 w-4 mr-2" />
              Delete Folder
            </Button>
          </div>
        }
      >
        {collectionToDelete && (
          <>
            <p className={`${getThemeClasses("text-secondary")} mb-4`}>
              Are you sure you want to delete "
              <span className="font-semibold">
                {collectionToDelete.name || "Locked Folder"}
              </span>
              "? This will permanently delete:
            </p>
            <ul className={`text-sm ${getThemeClasses("text-secondary")} space-y-2 mb-6 ${getThemeClasses("bg-error-light")} 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>
          </>
        )}
      </Modal>
    </Layout>
  );
};

export default withPasswordProtection(FileManagerIndex);
