// File: src/components/UIX/EntityFileView/EntityFileView.jsx
// EntityFileView Component - Google Drive-like file and folder viewer

import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
  memo,
} from "react";
import { useNavigate } from "react-router";
import {
  Squares2X2Icon,
  ListBulletIcon,
  FolderIcon,
  DocumentIcon,
  FolderOpenIcon,
  ChevronRightIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import {
  Button,
  useUIXTheme,
  SearchFilter,
  Card,
} from "../";

// Constants
const VIEW_TYPE_GRID = "grid";
const VIEW_TYPE_LIST = "list";
const ITEM_TYPE_FOLDER = "folder";
const ITEM_TYPE_FILE = "file";

/**
 * EntityFileView - A reusable file and folder viewer component
 *
 * Features:
 * - Grid and List view modes
 * - Folder navigation with breadcrumbs
 * - File and folder display
 * - Search and filtering
 * - E2EE support via config callbacks
 * - Google Drive-like interface
 *
 * @param {object} config - Configuration object
 * @param {function} config.fetchData - Fetch function (params, onUnauthorized, forceRefresh) => response
 * @param {function} config.buildParams - Build fetch parameters
 * @param {function} config.onItemClick - Handle item click (item, type) => void
 * @param {function} config.onFolderOpen - Handle folder open (folderId) => void
 * @param {function} config.processItems - Process/decrypt items (items) => processedItems
 * @param {function} config.renderFileIcon - Custom file icon renderer (file) => ReactNode
 * @param {function} config.renderFolderIcon - Custom folder icon renderer (folder) => ReactNode
 * @param {function} config.renderItemActions - Render item actions (item, type) => ReactNode
 * @param {array} config.breadcrumbItems - Breadcrumb items for current path
 * @param {string} config.currentFolderId - Current folder ID (null for root)
 * @param {string} config.emptyStateTitle - Empty state title
 * @param {string} config.emptyStateDescription - Empty state description
 * @param {boolean} config.showCreateButton - Show create folder button
 * @param {function} config.onCreateFolder - Create folder handler
 * @param {object} config.filterOptions - Filter configuration (statusOptions, typeOptions, sortOptions, etc.)
 */
const EntityFileView = memo(({ config }) => {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Refs for cleanup
  const isMounted = useRef(true);
  const timeoutRef = useRef(null);

  // List state
  const [items, setItems] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [successMessage, setSuccessMessage] = useState("");

  // Pagination state (cursor-based)
  const [pageSize, setPageSize] = useState(config.defaultPageSize || 50);
  const [previousCursors, setPreviousCursors] = useState([]);
  const [currentCursor, setCurrentCursor] = useState("");
  const [nextCursor, setNextCursor] = useState("");

  // Filter state
  const [sortBy, setSortBy] = useState(config.defaultSort || "name");
  const [sortOrder, setSortOrder] = useState(config.defaultSortOrder || "ASC");
  const [status, setStatus] = useState(config.defaultStatus || "1");
  const [type, setType] = useState(config.defaultType || "0");
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");
  const [viewType, setViewType] = useState(
    config.defaultViewType || VIEW_TYPE_GRID,
  );

  // Force refresh counter
  const [refreshCounter, setRefreshCounter] = useState(0);

  // Mount/cleanup effect - Reset isMounted on each mount for StrictMode compatibility
  useEffect(() => {
    isMounted.current = true;

    return () => {
      isMounted.current = false;
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  // Memoized callbacks
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  const resetPagination = useCallback(() => {
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  }, []);

  // Extract config methods and values to prevent infinite loops
  // These are extracted once and won't change during component lifecycle
  const currentFolderId = config.currentFolderId;
  const buildParamsRef = useRef(config.buildParams);
  const fetchDataRef = useRef(config.fetchData);
  const processItemsRef = useRef(config.processItems);

  // Update refs when config changes (but don't trigger re-renders)
  useEffect(() => {
    buildParamsRef.current = config.buildParams;
    fetchDataRef.current = config.fetchData;
    processItemsRef.current = config.processItems;
  }, [config.buildParams, config.fetchData, config.processItems]);

  // Fetch items - no config object in dependencies to prevent infinite loops
  const fetchItems = useCallback(
    async (forceRefresh = false) => {
      if (!isMounted.current) return;

      setIsLoading(true);
      setErrors({});

      try {
        const params = buildParamsRef.current({
          pageSize,
          currentCursor,
          sortBy,
          sortOrder,
          status,
          type,
          searchQuery,
          folderId: currentFolderId,
        });

        const response = await fetchDataRef.current(
          params,
          onUnauthorized,
          forceRefresh,
        );

        if (!isMounted.current) return;

        // Process items (decrypt if needed)
        let processedItems = response.results || [];
        if (processItemsRef.current) {
          processedItems = await processItemsRef.current(processedItems);
        }

        setItems(processedItems);
        setNextCursor(
          response.hasNextPage || response.nextCursor
            ? response.nextCursor || ""
            : "",
        );
      } catch (error) {
        if (!isMounted.current) return;

        setErrors({
          general: "Failed to load items. Please try again.",
        });

        // Only log errors in development
        if (import.meta.env.DEV) {
          console.warn("EntityFileView: Failed to fetch items");
        }
      } finally {
        if (isMounted.current) {
          setIsLoading(false);
        }
      }
    },
    [
      currentCursor,
      pageSize,
      sortBy,
      sortOrder,
      status,
      type,
      searchQuery,
      currentFolderId,
      onUnauthorized,
    ],
  );

  // Pagination handlers
  const handlePageChange = useCallback(
    (direction) => {
      if (direction === "next" && nextCursor) {
        setPreviousCursors((prev) => [...prev, currentCursor]);
        setCurrentCursor(nextCursor);
      } else if (direction === "previous" && previousCursors.length > 0) {
        setPreviousCursors((prev) => {
          const newPrev = [...prev];
          const previousCursor = newPrev.pop();
          setCurrentCursor(previousCursor);
          return newPrev;
        });
      }
    },
    [currentCursor, nextCursor, previousCursors],
  );

  // Search handler
  const handleSearch = useCallback(() => {
    setSearchQuery(tempSearchQuery);
    resetPagination();
  }, [tempSearchQuery, resetPagination]);

  // Filter handlers
  const handleStatusChange = useCallback(
    (newStatus) => {
      setStatus(newStatus);
      resetPagination();
    },
    [resetPagination],
  );

  const handleTypeChange = useCallback(
    (newType) => {
      setType(newType);
      resetPagination();
    },
    [resetPagination],
  );

  const handleSortChange = useCallback(
    (sortValue) => {
      const [field, order] = sortValue.split(",");
      setSortBy(field);
      setSortOrder(order);
      resetPagination();
    },
    [resetPagination],
  );

  const handlePageSizeChange = useCallback(
    (newPageSize) => {
      setPageSize(parseInt(newPageSize));
      resetPagination();
    },
    [resetPagination],
  );

  const handleClearFilters = useCallback(() => {
    setStatus(config.defaultStatus || "1");
    setType(config.defaultType || "0");
    setSortBy(config.defaultSort || "name");
    setSortOrder(config.defaultSortOrder || "ASC");
    setSearchQuery("");
    setTempSearchQuery("");
    resetPagination();
    setRefreshCounter((prev) => prev + 1);
  }, [config, resetPagination]);

  const handleRefresh = useCallback(() => {
    fetchItems(true);
  }, [fetchItems]);

  const handleSuccessMessageClose = useCallback(() => {
    setSuccessMessage("");
  }, []);

  // View type handlers
  const handleViewTypeChange = useCallback((newViewType) => {
    setViewType(newViewType);
  }, []);

  // Item interaction handlers
  const handleItemClick = useCallback(
    (item, itemType) => {
      if (config.onItemClick) {
        config.onItemClick(item, itemType);
      }
    },
    [config],
  );

  const handleFolderOpen = useCallback(
    (folder) => {
      if (config.onFolderOpen) {
        config.onFolderOpen(folder);
      }
    },
    [config],
  );

  // Determine item type
  const getItemType = useCallback((item) => {
    // Check if item has a type field
    if (item.type === ITEM_TYPE_FOLDER || item.type === "collection") {
      return ITEM_TYPE_FOLDER;
    }
    if (item.type === ITEM_TYPE_FILE) {
      return ITEM_TYPE_FILE;
    }

    // Check for folder-specific fields
    if (item.isFolder || item.collection_id || item.collectionId) {
      return ITEM_TYPE_FOLDER;
    }

    // Default to file
    return ITEM_TYPE_FILE;
  }, []);

  // Get file icon
  const getFileIcon = useCallback(
    (file) => {
      if (config.renderFileIcon) {
        return config.renderFileIcon(file);
      }

      // Default file icon based on extension
      const fileName = file.name || file.encrypted_name || "";
      const extension = fileName.split(".").pop()?.toLowerCase() || "";

      const iconClass = "h-8 w-8";

      if (["pdf"].includes(extension)) {
        return <DocumentIcon className={`${iconClass} ${getThemeClasses("file-icon-pdf")}`} />;
      }
      if (["doc", "docx", "txt"].includes(extension)) {
        return <DocumentIcon className={`${iconClass} ${getThemeClasses("file-icon-doc")}`} />;
      }
      if (["jpg", "jpeg", "png", "gif", "svg"].includes(extension)) {
        return <DocumentIcon className={`${iconClass} ${getThemeClasses("file-icon-design")}`} />;
      }

      return <DocumentIcon className={`${iconClass} ${getThemeClasses("file-icon-default")}`} />;
    },
    [config, getThemeClasses],
  );

  // Get folder icon
  const getFolderIcon = useCallback(
    (folder) => {
      if (config.renderFolderIcon) {
        return config.renderFolderIcon(folder);
      }

      return <FolderIcon className={`h-8 w-8 ${getThemeClasses("icon-info")}`} />;
    },
    [config, getThemeClasses],
  );

  // Separate items into folders and files
  const { folders, files } = useMemo(() => {
    const foldersList = [];
    const filesList = [];

    items.forEach((item) => {
      const itemType = getItemType(item);
      if (itemType === ITEM_TYPE_FOLDER) {
        foldersList.push(item);
      } else {
        filesList.push(item);
      }
    });

    return { folders: foldersList, files: filesList };
  }, [items, getItemType]);

  // Memoized configurations
  const searchFilterConfig = useMemo(
    () => ({
      searchTerm: searchQuery,
      tempSearchTerm: tempSearchQuery,
      onSearchTermChange: setTempSearchQuery,
      onSearch: handleSearch,
      searchPlaceholder: config.searchPlaceholder || "Search files and folders...",
      statusOptions: config.filterOptions?.statusOptions || [],
      statusFilter: status,
      onStatusFilterChange: handleStatusChange,
      typeOptions: config.filterOptions?.typeOptions || [],
      typeFilter: type,
      onTypeFilterChange: handleTypeChange,
      sortOptions: config.filterOptions?.sortOptions || [],
      sortValue: `${sortBy},${sortOrder}`,
      onSortChange: handleSortChange,
      pageSizeOptions: config.filterOptions?.pageSizeOptions || [],
      pageSize,
      onPageSizeChange: handlePageSizeChange,
      onClearFilters: handleClearFilters,
      onRefresh: handleRefresh,
    }),
    [
      searchQuery,
      tempSearchQuery,
      handleSearch,
      config,
      status,
      handleStatusChange,
      type,
      handleTypeChange,
      sortBy,
      sortOrder,
      handleSortChange,
      pageSize,
      handlePageSizeChange,
      handleClearFilters,
      handleRefresh,
    ],
  );

  // Memoized header actions
  const headerActions = useMemo(
    () => [
      <div key="view-toggle" className="flex items-center gap-1">
        <Button
          variant={viewType === VIEW_TYPE_LIST ? "primary" : "ghost"}
          onClick={() => handleViewTypeChange(VIEW_TYPE_LIST)}
          size="sm"
          title="List View"
        >
          <ListBulletIcon className="w-5 h-5" />
        </Button>
        <Button
          variant={viewType === VIEW_TYPE_GRID ? "primary" : "ghost"}
          onClick={() => handleViewTypeChange(VIEW_TYPE_GRID)}
          size="sm"
          title="Grid View"
        >
          <Squares2X2Icon className="w-5 h-5" />
        </Button>
      </div>,
      ...(config.showCreateButton
        ? [
            <Button
              key="create"
              variant="success"
              size="md"
              onClick={config.onCreateFolder}
              icon={FolderIcon}
            >
              New Folder
            </Button>,
          ]
        : []),
    ],
    [viewType, handleViewTypeChange, config],
  );

  // Render grid item
  const renderGridItem = useCallback(
    (item) => {
      const itemType = getItemType(item);
      const isFolder = itemType === ITEM_TYPE_FOLDER;
      const name = item.name || item.encrypted_name || "Untitled";
      const isDecrypted = item._isDecrypted !== false;

      return (
        <Card
          key={item.id}
          onClick={() =>
            isFolder ? handleFolderOpen(item) : handleItemClick(item, itemType)
          }
          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">
              {/* Icon */}
              <div className="mb-3">
                {isFolder ? getFolderIcon(item) : getFileIcon(item)}
              </div>

              {/* Name */}
              <h3
                className={`text-sm font-semibold ${getThemeClasses("text-primary")} truncate w-full`}
                title={name}
              >
                {isDecrypted ? name : "🔒 Locked"}
              </h3>
            </div>

            {/* Item-specific info at bottom */}
            <div
              className={`text-xs ${getThemeClasses("text-muted")} text-center pt-2 border-t-4 ${getThemeClasses("border-secondary")}`}
            >
              {isFolder && item.file_count !== undefined && (
                <div>{item.file_count} file{item.file_count !== 1 ? 's' : ''}</div>
              )}
              {!isFolder && item.size && (
                <div>{formatFileSize(item.size)}</div>
              )}
            </div>
          </div>
        </Card>
      );
    },
    [
      getItemType,
      handleFolderOpen,
      handleItemClick,
      getFolderIcon,
      getFileIcon,
      getThemeClasses,
      config,
    ],
  );

  // Render list item
  const renderListItem = useCallback(
    (item) => {
      const itemType = getItemType(item);
      const isFolder = itemType === ITEM_TYPE_FOLDER;
      const name = item.name || item.encrypted_name || "Untitled";
      const isDecrypted = item._isDecrypted !== false;

      return (
        <div
          key={item.id}
          onClick={() =>
            isFolder ? handleFolderOpen(item) : handleItemClick(item, itemType)
          }
          className={`flex items-center p-4 border-b ${getThemeClasses("border-secondary")} hover:${getThemeClasses("bg-hover")} cursor-pointer transition-colors`}
        >
          {/* Icon */}
          <div className="flex-shrink-0 mr-4">
            {isFolder ? getFolderIcon(item) : getFileIcon(item)}
          </div>

          {/* Name and Description */}
          <div className="flex-1 min-w-0">
            <h3
              className={`text-base font-semibold ${getThemeClasses("text-primary")} truncate`}
              title={name}
            >
              {isDecrypted ? name : "🔒 Locked"}
            </h3>
            {item.description && isDecrypted && (
              <p
                className={`text-sm ${getThemeClasses("text-secondary")} truncate mt-1`}
              >
                {item.description || item.encrypted_description}
              </p>
            )}
          </div>

          {/* Metadata */}
          <div
            className={`flex-shrink-0 ml-4 text-sm ${getThemeClasses("text-muted")} text-right space-y-1`}
          >
            {isFolder && item.file_count !== undefined && (
              <div>{item.file_count} file{item.file_count !== 1 ? 's' : ''}</div>
            )}
            {!isFolder && item.size && <div>{formatFileSize(item.size)}</div>}
            {item.created_at && <div>{formatDate(item.created_at)}</div>}
          </div>

          {/* Actions */}
          {config.renderItemActions && (
            <div className="flex-shrink-0 ml-4">
              {config.renderItemActions(item, itemType)}
            </div>
          )}

          {/* Chevron for folders */}
          {isFolder && (
            <ChevronRightIcon
              className={`w-5 h-5 ml-2 ${getThemeClasses("text-muted")}`}
            />
          )}
        </div>
      );
    },
    [
      getItemType,
      handleFolderOpen,
      handleItemClick,
      getFolderIcon,
      getFileIcon,
      getThemeClasses,
      config,
    ],
  );

  // Render content
  const renderContent = useCallback(() => {
    if (isLoading) {
      return (
        <div className="flex items-center justify-center py-12">
          <div
            className={`animate-spin rounded-full h-8 w-8 border-b-2 ${getThemeClasses("border-primary")}`}
          ></div>
          <span className={`ml-3 ${getThemeClasses("text-secondary")}`}>
            Loading...
          </span>
        </div>
      );
    }

    if (items.length === 0) {
      return (
        <div className="text-center py-12">
          <FolderOpenIcon
            className={`mx-auto h-12 w-12 ${getThemeClasses("text-muted")}`}
          />
          <h3
            className={`mt-2 text-sm font-medium ${getThemeClasses("text-primary")}`}
          >
            {config.emptyStateTitle || "No items found"}
          </h3>
          <p className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}>
            {config.emptyStateDescription || "This folder is empty."}
          </p>
          {config.showCreateButton && (
            <div className="mt-6">
              <Button
                variant="success"
                onClick={config.onCreateFolder}
                icon={FolderIcon}
              >
                Create Folder
              </Button>
            </div>
          )}
        </div>
      );
    }

    // Render based on view type
    if (viewType === VIEW_TYPE_GRID) {
      return (
        <div className="space-y-8">
          {/* Folders Section */}
          {folders.length > 0 && (
            <div>
              <h2
                className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center`}
              >
                <FolderIcon className="w-5 h-5 mr-2" />
                Folders ({folders.length})
              </h2>
              <div className="grid gap-4 grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
                {folders.map(renderGridItem)}
              </div>
            </div>
          )}

          {/* Files Section */}
          {files.length > 0 && (
            <div>
              <h2
                className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center`}
              >
                <DocumentIcon className="w-5 h-5 mr-2" />
                Files ({files.length})
              </h2>
              <div className="grid gap-4 grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
                {files.map(renderGridItem)}
              </div>
            </div>
          )}
        </div>
      );
    } else {
      // List view
      return (
        <div className="space-y-8">
          {/* Folders Section */}
          {folders.length > 0 && (
            <div>
              <h2
                className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center px-4`}
              >
                <FolderIcon className="w-5 h-5 mr-2" />
                Folders ({folders.length})
              </h2>
              <div className={`border ${getThemeClasses("border-secondary")} rounded-lg overflow-hidden`}>
                {folders.map(renderListItem)}
              </div>
            </div>
          )}

          {/* Files Section */}
          {files.length > 0 && (
            <div>
              <h2
                className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center px-4`}
              >
                <DocumentIcon className="w-5 h-5 mr-2" />
                Files ({files.length})
              </h2>
              <div className={`border ${getThemeClasses("border-secondary")} rounded-lg overflow-hidden`}>
                {files.map(renderListItem)}
              </div>
            </div>
          )}
        </div>
      );
    }
  }, [
    isLoading,
    items,
    folders,
    files,
    viewType,
    config,
    getThemeClasses,
    renderGridItem,
    renderListItem,
  ]);

  // Initial load effect
  // NOTE: We only include "trigger" dependencies here, not fetchItems itself
  // fetchItems already captures all its dependencies via useCallback
  // Including fetchItems here would cause infinite loops
  useEffect(() => {
    if (import.meta.env.DEV) {
      console.log("[EntityFileView] useEffect triggered - fetching items");
    }
    fetchItems(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    currentCursor,
    pageSize,
    sortBy,
    sortOrder,
    status,
    type,
    searchQuery,
    refreshCounter,
    currentFolderId, // Re-fetch when folder changes
    // NOTE: fetchItems is NOT included to prevent infinite loops
    // fetchItems is stable via useCallback and captures all these dependencies
  ]);

  return (
    <div className={`min-h-screen ${getThemeClasses("bg-page")}`}>
      {/* Decorative background elements */}
      <div className="fixed inset-0 overflow-hidden pointer-events-none">
        <div
          className={`absolute -top-40 -right-40 w-80 h-80 ${getThemeClasses("decorative-primary")} rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob`}
        ></div>
        <div
          className={`absolute -bottom-40 -left-40 w-80 h-80 ${getThemeClasses("decorative-secondary")} rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000`}
        ></div>
        <div
          className={`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-80 h-80 ${getThemeClasses("decorative-accent")} rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000`}
        ></div>
      </div>

      <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
        {/* Success Message */}
        {successMessage && (
          <div
            className={`mb-6 sm:mb-8 p-4 ${getThemeClasses("success-bg")} border ${getThemeClasses("success-border")} rounded-lg flex items-center`}
          >
            <span className={`text-sm ${getThemeClasses("success-text")}`}>
              {successMessage}
            </span>
            <button
              onClick={handleSuccessMessageClose}
              className={`ml-auto ${getThemeClasses("success-text")} hover:opacity-75`}
            >
              ×
            </button>
          </div>
        )}

        {/* Error Message */}
        {errors.general && (
          <div
            className={`mb-6 sm:mb-8 p-4 ${getThemeClasses("error-bg")} border ${getThemeClasses("error-border")} rounded-lg`}
          >
            <span className={`text-sm ${getThemeClasses("error-text")}`}>
              {errors.general}
            </span>
          </div>
        )}

        {/* Main Content Layout */}
        <div className="max-w-7xl mx-auto">
          <div
            className={`${getThemeClasses("bg-card")} shadow-xl rounded-2xl overflow-hidden border ${getThemeClasses("border-secondary")} hover:shadow-2xl transition-shadow duration-300`}
          >
            {/* Header Section */}
            <div
              className={`px-6 sm:px-8 py-6 border-b ${getThemeClasses("border-secondary")}`}
            >
              {/* Breadcrumbs */}
              {config.breadcrumbItems && config.breadcrumbItems.length > 0 && (
                <div className="mb-4">
                  <nav className="flex items-center space-x-2 text-sm">
                    {config.breadcrumbItems.map((item, index) => (
                      <React.Fragment key={index}>
                        {index > 0 && (
                          <ChevronRightIcon
                            className={`w-4 h-4 ${getThemeClasses("text-muted")}`}
                          />
                        )}
                        <button
                          onClick={item.onClick}
                          className={`${
                            index === config.breadcrumbItems.length - 1
                              ? getThemeClasses("text-primary") + " font-semibold"
                              : getThemeClasses("link-primary") + " hover:underline"
                          }`}
                        >
                          {index === 0 && <HomeIcon className="w-4 h-4 inline mr-1" />}
                          {item.label}
                        </button>
                      </React.Fragment>
                    ))}
                  </nav>
                </div>
              )}

              {/* Header with actions */}
              <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 if provided */}
                    {config.icon && (
                      <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses("bg-gradient-secondary")}`}>
                        <config.icon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                      </div>
                    )}
                    <div className={config.icon ? "" : "w-full"}>
                      <h1
                        className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}
                      >
                        {config.title || "File Manager"}
                      </h1>
                      {config.subtitle && (
                        <p
                          className={`mt-2 text-base sm:text-lg lg:text-xl ${getThemeClasses("text-secondary")} font-medium`}
                        >
                          {config.subtitle}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
                <div className="flex-shrink-0 flex items-center gap-3">
                  {headerActions}
                </div>
              </div>
            </div>

            {/* Search Filter Component */}
            <SearchFilter {...searchFilterConfig} />

            {/* Content Section */}
            <div className="p-6">{renderContent()}</div>

            {/* Pagination */}
            {(previousCursors.length > 0 || nextCursor) && (
              <div
                className={`px-6 py-4 border-t ${getThemeClasses("border-secondary")} flex items-center justify-between`}
              >
                <Button
                  variant="secondary"
                  disabled={previousCursors.length === 0}
                  onClick={() => handlePageChange("previous")}
                >
                  Previous
                </Button>
                <span className={`text-sm ${getThemeClasses("text-secondary")}`}>
                  Page {previousCursors.length + 1}
                </span>
                <Button
                  variant="secondary"
                  disabled={!nextCursor}
                  onClick={() => handlePageChange("next")}
                >
                  Next
                </Button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
});

// Helper functions
function formatFileSize(bytes) {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + " " + sizes[i];
}

function formatDate(dateString) {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

// Add display name
EntityFileView.displayName = "EntityFileView";

export default EntityFileView;
