"use client"

import { useState, useEffect } from "react"
import {
  Box,
  Container,
  Typography,
  Grid,
  Paper,
  InputBase,
  IconButton,
  Button,
  Divider,
  Breadcrumbs,
  Link,
  LinearProgress,
} from "@mui/material"
import {
  Search as SearchIcon,
  ArrowBack as ArrowBackIcon,
  NavigateNext as NavigateNextIcon,
  Home as HomeIcon,
  GridView as GridViewIcon,
  ViewList as ViewListIcon,
  MoreVert as MoreVertIcon,
} from "@mui/icons-material"
import DocumentCard from "./components/document-card"
import FolderCard from "./components/folder-card"
import StorageUsage from "./components/storage-usage"
import type { FolderDTO, DocumentDTO, FolderDetails } from "@/shared/types/document"
import UploadFileDialog from "./components/upload-file-dialog"
import CreateFolderDialog from "./components/create-folder-dialog"
import FileTypeFilter from "./components/file-type-filter"
import { HEADER } from "@/layouts/config-layout"
import { ScrollBox } from "@/shared/theme/css"
import DocumentManagerPanel from "./components/document-manager-panel"
import EmptyContent from "@/shared/components/empty-content"
import FileThumbnail from "@/shared/components/file-thumbnail"
import { faStar } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { fileTypes } from "@/shared/_mock"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useFolderStore } from "../../../../api/stores/document-service/folderStore"
import RenameFolderDialog from "./components/rename-folder-dialog";
import MoveFolderDialog from "./components/MoveFolderDialog"
import ConfirmDeleteDialog from "./components/ConfirmFolderDeleteDialog"
import FolderDetailsDialog from "./components/FolderDetailsDialog"
import { useStorageStore } from "@/shared/api/stores/document-service/storageStore"
import { useDocumentStore } from "@/shared/api/stores/document-service/docsStore"
import DocumentPreviewDialog from "./components/DocumentPreviewDialog"
import DocumentDetailsDialog from "./components/DocumentDetailsDialog"
import MoveDocumentDialog from "./components/MoveDocumentDialog"


interface DocumentDriveProps {
  onShowDemandes: () => void
}

export default function DocumentDrive({ onShowDemandes }: DocumentDriveProps) {
  const [docs, setDocs] = useState<DocumentDTO[]>([])
  const [folders, setFolders] = useState<FolderDTO[]>([])
  const [currentFolder, setCurrentFolder] = useState<FolderDTO | null>(null)
  const [folderPath, setFolderPath] = useState<FolderDTO[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const [filteredDocuments, setFilteredDocuments] = useState<DocumentDTO[]>([])
  const [filteredFolders, setFilteredFolders] = useState<FolderDTO[]>([])
  const [selectedFileTypes, setSelectedFileTypes] = useState<string[]>([])
  const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false)
  const [isCreateFolderDialogOpen, setIsCreateFolderDialogOpen] = useState(false)
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid")
  const [foldersCollapsed, setFoldersCollapsed] = useState(false)
  const [filesCollapsed, setFilesCollapsed] = useState(false)
  const [showOnlyFavorites, setShowOnlyFavorites] = useState(false)
  const [renameDialogOpen, setRenameDialogOpen] = useState(false);
  const [folderToRename, setFolderToRename] = useState<FolderDTO | null>(null);
  const [moveDialogOpen, setMoveDialogOpen] = useState(false)
  const [folderToMove, setFolderToMove] = useState<FolderDTO | null>(null)
  const [selectedFolderToDelete, setSelectedFolderToDelete] = useState<FolderDTO | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  const [selectedFolderDetails, setSelectedFolderDetails] = useState<FolderDetails | null>(null);
  const [selectedDocument, setSelectedDocument] = useState<DocumentDTO | null>(null);
  const [documentDetailsDialogOpen, setDocumentDetailsDialogOpen] = useState(false);
  const [moveDocumentDialogOpen, setMoveDocumentDialogOpen] = useState(false);
  const [previewDocumentDialogOpen, setPreviewDocumentDialogOpen] = useState(false);


  const { createFolder, getRootFolders, renameFolder, moveFolder, searchFolders, toggleFavorite, toggleUnfavorite } = useFolderStore();
  const {documents, getRoot, search, download, share, rename, markFavorite, unmarkFavorite} = useDocumentStore();
  const { quota, loading, error, fetchStorageQuota } = useStorageStore();

  const userUuid = localStorage.getItem('userUuid');
  useEffect(() => {   
    fetchStorageQuota(userUuid as string)
    // Load real folders from backend
    const loadRootFolders = async () => {
      try {
        const rootFolders = await getRootFolders(userUuid as string) // Using owner ID userUuid as string
        setFolders(rootFolders)
        setFilteredFolders(rootFolders)

        // Extract documents from all root folders
        const allDocuments = rootFolders.flatMap((folder : FolderDTO) => folder.documents || [])
        setDocs(allDocuments)
        setFilteredDocuments(allDocuments)
      } catch (error) {
        console.error("Failed to load root folders:", error)
        // Fallback to empty arrays if API fails
        setFolders([])
        setFilteredFolders([])
        setDocs([])
        setFilteredDocuments([])
      }
    }
    const loadRootDocuments = async () => {
      try {
        const rootDocuments = await getRoot(userUuid as string) // Using owner ID userUuid as string
        setDocs(rootDocuments)
        setFilteredDocuments(rootDocuments)
      } catch (error) {
        console.error("Failed to load root documents:", error)
        // Fallback to empty arrays if API fails
        setDocs([])
        setFilteredDocuments([])
      }
    }
    loadRootFolders();
    loadRootDocuments();
  }, [])

  useEffect(() => {
  const availableFolders = currentFolder ? currentFolder.subFolders || [] : folders;
  const availableDocuments = currentFolder ? currentFolder.documents || [] : docs;
  
  let filteredFoldersResult = availableFolders;
  let filteredDocsResult = availableDocuments;
  
  // Apply search query filter
  if (searchQuery.trim()) {
    const query = searchQuery.toLowerCase().trim();
    
    filteredFoldersResult = availableFolders.filter(folder => 
      folder.name.toLowerCase().includes(query)
    );
    
    filteredDocsResult = availableDocuments.filter(doc => 
      doc.name.toLowerCase().includes(query)
    );
  }
  
  // Apply file type filter with better matching
  if (selectedFileTypes.length > 0) {
    filteredDocsResult = filteredDocsResult.filter(doc => {
      // Check exact matches
      if (selectedFileTypes.includes(doc.contentType) || 
          selectedFileTypes.includes(doc.documentType)) {
        return true;
      }
      
      // Check partial matches for content types like "application/pdf" -> "PDF"
      return selectedFileTypes.some(selectedType => 
        doc.contentType?.toLowerCase().includes(selectedType.toLowerCase()) ||
        doc.documentType?.toLowerCase().includes(selectedType.toLowerCase())
      );
    });
  }
  
  setFilteredFolders(filteredFoldersResult);
  setFilteredDocuments(filteredDocsResult);
  
}, [searchQuery, selectedFileTypes, currentFolder, folders, docs])

useEffect(() => {
  if (currentFolder) {
    setFilteredDocuments(currentFolder.documents || []);
  } else {
    setFilteredDocuments(docs); // show root docs only when in root
  }
}, [currentFolder, docs]);
  const handleCreateFolder = () => {
    setIsCreateFolderDialogOpen(true)
  }

  const handleUploadFile = () => {
    setIsUploadDialogOpen(true)
  }

  const handleViewModeChange = (mode: "grid" | "list") => {
    setViewMode(mode)
  }

  const handleAddFolder = async (folderName: string) => {
    try {
      await createFolder({
        name: folderName,
        ownerId : 1,
        parentId: currentFolder?.id || null, // null for root folders
        ownerUuid: userUuid, // Using owner ID userUuid as string
      })

      // Reload folders and documents after creation
      const updatedFolders = await getRootFolders(userUuid as string)
      setFolders(updatedFolders)
      setFilteredFolders(updatedFolders)
      fetchStorageQuota(userUuid as string)
      setIsCreateFolderDialogOpen(false)
    } catch (error) {
      console.error("Failed to create folder:", error)
      // Handle error - you might want to show a toast notification here
    }
  }
  const handleOpenMoveDialog = (folder: FolderDTO) => {
  setFolderToMove(folder)
  setMoveDialogOpen(true)
}

  const handleShowDetails = async (folder: FolderDTO) => {
    const details = await useFolderStore.getState().getFolderDetails(folder.id, userUuid as string);
    setSelectedFolderDetails(details);
    setDetailsDialogOpen(true);
  };

  const handleAddDocument = async (document: DocumentDTO) => {
  try {
    if (currentFolder) {
      const updatedFolders = await getRootFolders(userUuid as string)
      setFolders(updatedFolders)
      
      // Find and update the current folder
      const findFolderById = (folders: FolderDTO[], id: number): FolderDTO | null => {
        for (const f of folders) {
          if (f.id === id) return f;
          if (f.subFolders) {
            const found = findFolderById(f.subFolders, id);
            if (found) return found;
          }
        }
        return null;
      };
      
      const refreshedCurrentFolder = findFolderById(updatedFolders, currentFolder.id);
      if (refreshedCurrentFolder) {
        setCurrentFolder(refreshedCurrentFolder);
      }
    } else {
      // Refresh root documents
      const rootDocuments = await getRoot(userUuid as string)
      setDocs(rootDocuments)
    }
    
    // Refresh storage quota
    fetchStorageQuota(userUuid as string)
    
  } catch (error) {
    console.error("Failed to refresh after upload:", error)
  }
  
  setIsUploadDialogOpen(false)
}

  const handleMoveFolder = async (newParentId: number | null) => {
  if (folderToMove) {
    await moveFolder(folderToMove.id, newParentId, userUuid as string);
    const updatedFolders = await getRootFolders(userUuid as string);
    setFolders(updatedFolders);
    setFilteredFolders(updatedFolders);
    setMoveDialogOpen(false);
    setFolderToMove(null);

  }
};
  const handleRenameFolder = async (newName: string) => {
  if (folderToRename) {
    try {
      await renameFolder(folderToRename.id, newName, userUuid as string);
      const updatedFolders = await getRootFolders(userUuid as string);
      setFolders(updatedFolders);
      setFilteredFolders(updatedFolders);
      setRenameDialogOpen(false);
      setFolderToRename(null);
    } catch (error) {
      console.error("Rename failed:", error);
    }
  }
};

  const handleDeleteFolder = (folder: FolderDTO) => {
    setSelectedFolderToDelete(folder);
    setIsDeleteDialogOpen(true);
  };

  const confirmDeleteFolder = async () => {
  if (!selectedFolderToDelete) return;

  try {
    await useFolderStore.getState().deleteFolder(selectedFolderToDelete.id, userUuid as string)

    // Supprimer des subFolders du dossier courant
    if (currentFolder) {
      const updatedSubFolders = (currentFolder.subFolders || []).filter(
        (folder) => folder.id !== selectedFolderToDelete.id
      )

      setCurrentFolder({
        ...currentFolder,
        subFolders: updatedSubFolders,
      })

      setFilteredFolders(updatedSubFolders)
    } else {
      // Cas où le dossier supprimé est à la racine
      const updatedRootFolders = folders.filter(folder => folder.id !== selectedFolderToDelete.id)
      setFolders(updatedRootFolders)
      setFilteredFolders(updatedRootFolders)
    }

    setSelectedFolderToDelete(null)
    setIsDeleteDialogOpen(false)

  } catch (error) {
    console.error("Erreur lors de la suppression du dossier :", error)
  }
}

const updateFolderRecursively = (folders: FolderDTO[], folderId: number, updater: (f: FolderDTO) => FolderDTO): FolderDTO[] => {
  return folders.map(folder => {
    if (folder.id === folderId) return updater(folder);
    if (folder.subFolders) {
      return {
        ...folder,
        subFolders: updateFolderRecursively(folder.subFolders, folderId, updater),
      };
    }
    return folder;
  });
};

const handleToggleFavorite = async (folder: FolderDTO) => {
  try {
    
    if (folder.favorite) {
      await toggleUnfavorite(folder.id, folder.ownerUuid);
    } else {
      await toggleFavorite(folder.id, folder.ownerUuid);
    }

    // Refresh data from server
    const updatedFolders = await getRootFolders(userUuid as string);     
    setFolders(updatedFolders);
    
    // Update filtered folders based on current context
    if (currentFolder) {
      const findFolderById = (folders: FolderDTO[], id: number): FolderDTO | null => {
        for (const f of folders) {
          if (f.id === id) return f;
          if (f.subFolders) {
            const found = findFolderById(f.subFolders, id);
            if (found) return found;
          }
        }
        return null;
      };
      
      const refreshedCurrentFolder = findFolderById(updatedFolders, currentFolder.id);
      
      if (refreshedCurrentFolder) {
        setCurrentFolder(refreshedCurrentFolder);
        setFilteredFolders(refreshedCurrentFolder.subFolders || []);
      }
    } else {
      setFilteredFolders(updatedFolders);
    }

  } catch (error) {
    console.error("Erreur lors de la mise à jour du favori", error);
  }
};

  const handleFileTypeFilterChange = (fileTypes: string[]) => {
    setSelectedFileTypes(fileTypes)
  }

  const handleFolderClick = (folder: FolderDTO) => {
    setCurrentFolder(folder)

    if (currentFolder) {
      // We're already in a folder, add current to path
      setFolderPath([...folderPath, currentFolder])
    } else {
      // We're at root level
      setFolderPath([])
    }

    // Set documents and subfolders of the clicked folder
    setFilteredDocuments(folder.documents || [])
    setFilteredFolders(folder.subFolders || [])

    // Clear search when navigating
    setSearchQuery("")
    setSelectedFileTypes([])
  }

  const handleBackToParent = () => {
    if (folderPath.length > 0) {
      // Go to parent folder
      const parentFolder = folderPath[folderPath.length - 1]
      setCurrentFolder(parentFolder)
      setFolderPath(folderPath.slice(0, -1))

      // Set documents and subfolders of the parent folder
      setFilteredDocuments(parentFolder.documents || [])
      setFilteredFolders(parentFolder.subFolders || [])
    } else {
      // Go to root
      handleBackToRoot()
    }
  }

  const handleBackToRoot = () => {
    setCurrentFolder(null)
    setFolderPath([])

    // Reset to root documents and folders
    setFilteredDocuments(documents)
    setFilteredFolders(folders)
  }

  const navigateToPathIndex = (index: number) => {
    if (index === -1) {
      // Navigate to root
      handleBackToRoot()
      return
    }

    const targetFolder = folderPath[index]
    setCurrentFolder(targetFolder)
    setFolderPath(folderPath.slice(0, index))

    // Set documents and subfolders of the target folder
    setFilteredDocuments(targetFolder.documents || [])
    setFilteredFolders(targetFolder.subFolders || [])
  }

  const handleDownload = async (doc: DocumentDTO) => {
  try {
    const blob = await download(doc.id, userUuid as string);
    const url = window.URL.createObjectURL(blob);
    
    // Create a temporary link element
    const link = document.createElement("a");
    link.href = url;
    link.download = doc.name; // Use the document name as filename
    link.target = "_blank";
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // Clean up the blob URL
    window.URL.revokeObjectURL(url);
    
  } catch (error) {
    console.error("Download failed:", error);
  }
};

const handleShareDocument = async (doc: DocumentDTO, targetUserUuid: string) => {
  try {
    await share(doc.id, targetUserUuid);
  } catch (error) {
    console.error("Share failed:", error);
  }
};

const handleRenameDocument = async (doc: DocumentDTO, newName: string) => {
  try {
    await rename(doc.id, newName, userUuid as string);
    
    const updatedDocs = docs.map(d => 
      d.id === doc.id ? { ...d, name: newName } : d
    );
    setDocs(updatedDocs);
    setFilteredDocuments(updatedDocs);
  } catch (error) {
    console.error("Rename failed:", error);
  }
};

const handleDelete = async (doc: DocumentDTO) => {
  try {
    await useDocumentStore.getState().delete(doc.id, userUuid as string);
    
    // Remove from local state
    const updatedDocs = docs.filter(d => d.id !== doc.id);
    setDocs(updatedDocs);
    setFilteredDocuments(updatedDocs);
    
    // Refresh storage quota
    fetchStorageQuota(userUuid as string);
  } catch (error) {
    console.error("Delete failed:", error);
  }
};

const handleToggleDocumentFavorite = async (doc: DocumentDTO) => {
  try {
    if (doc.favorite) {
      await unmarkFavorite(doc.id, userUuid as string);
    } else {
      await markFavorite(doc.id, userUuid as string);
    }

    // Update local state
    const updatedDocs = docs.map(d => 
      d.id === doc.id ? { ...d, favorite: !d.favorite } : d
    );
    setDocs(updatedDocs);
    setFilteredDocuments(updatedDocs);
  } catch (error) {
    console.error("Toggle favorite failed:", error);
  }
};

const handleShowDocumentDetails = async (doc: DocumentDTO) => {
  try {
    // Get full document details from backend
    const fullDocumentDetails = await useDocumentStore.getState().getDetails(doc.id, userUuid as string);
    setSelectedDocument(fullDocumentDetails);
    setDocumentDetailsDialogOpen(true);
  } catch (error) {
    console.error("Failed to load document details:", error);
  }
};

const handleMoveDocument = async (folderId: number) => {
  if (!selectedDocument) return;

  try {
    const movedDocument = await useDocumentStore.getState().move(selectedDocument.id, userUuid as string, folderId);
    
    // Helper function to find folder by ID recursively
    const findFolderById = (folders: FolderDTO[], id: number): FolderDTO | null => {
      for (const f of folders) {
        if (f.id === id) return f;
        if (f.subFolders) {
          const found = findFolderById(f.subFolders, id);
          if (found) return found;
        }
      }
      return null;
    };

    // Helper function to update folder recursively
    const updateFolderRecursively = (folders: FolderDTO[], folderId: number, updater: (f: FolderDTO) => FolderDTO): FolderDTO[] => {
      return folders.map(folder => {
        if (folder.id === folderId) return updater(folder);
        if (folder.subFolders) {
          return {
            ...folder,
            subFolders: updateFolderRecursively(folder.subFolders, folderId, updater),
          };
        }
        return folder;
      });
    };

    // STEP 1: Remove document from its current location
    let updatedFolders = [...folders];
    let updatedDocs = [...docs];

    // Determine where the document currently is
    const documentCurrentFolderId = selectedDocument.folder?.id;

    if (documentCurrentFolderId) {
      // Document is currently in a folder - remove it from that folder
      updatedFolders = updateFolderRecursively(updatedFolders, documentCurrentFolderId, (folder) => ({
        ...folder,
        documents: (folder.documents || []).filter(doc => doc.id !== selectedDocument.id)
      }));

      // If we're currently viewing the folder the document was in, update current folder
      if (currentFolder && currentFolder.id === documentCurrentFolderId) {
        const updatedCurrentFolder = {
          ...currentFolder,
          documents: (currentFolder.documents || []).filter(doc => doc.id !== selectedDocument.id)
        };
        setCurrentFolder(updatedCurrentFolder);
      }
    } else {
      // Document is currently in root - remove it from root
      updatedDocs = docs.filter(doc => doc.id !== selectedDocument.id);
      setDocs(updatedDocs);
    }

    // STEP 2: Add document to target location
    if (folderId === null) {
      // Moving to root
      updatedDocs = [...updatedDocs, movedDocument];
      setDocs(updatedDocs);
    } else {
      // Moving to a specific folder
      updatedFolders = updateFolderRecursively(updatedFolders, folderId, (folder) => ({
        ...folder,
        documents: [...(folder.documents || []), movedDocument]
      }));

      // If the target folder is the current folder, update current folder state
      if (currentFolder && currentFolder.id === folderId) {
        const updatedCurrentFolder = {
          ...currentFolder,
          documents: [...(currentFolder.documents || []).filter(doc => doc.id !== selectedDocument.id), movedDocument]
        };
        setCurrentFolder(updatedCurrentFolder);
      }
    }

    // STEP 3: Update all states
    setFolders(updatedFolders);

    // Update filtered documents based on current context
    if (currentFolder) {
      const refreshedCurrentFolder = findFolderById(updatedFolders, currentFolder.id);
      if (refreshedCurrentFolder) {
        setFilteredDocuments(refreshedCurrentFolder.documents || []);
      }
    } else {
      setFilteredDocuments(updatedDocs);
    }
  } catch (error) {
    console.error("Move failed:", error);
  } finally {
    setSelectedDocument(null);
    setMoveDocumentDialogOpen(false);
  }
};

const handleOpenMoveDocumentDialog = (doc: DocumentDTO) => {
  setSelectedDocument(doc);
  setMoveDocumentDialogOpen(true);
};

const handleOpenPreviewDocumentDialog = (doc: DocumentDTO) => {
  setSelectedDocument(doc);
  setPreviewDocumentDialogOpen(true);
};
  // Applique le filtre favoris sur les listes déjà filtrées par recherche/navigation
  const displayedFolders = showOnlyFavorites ? filteredFolders.filter((folder) => folder.favorite) : filteredFolders

  const displayedDocuments = showOnlyFavorites ? filteredDocuments.filter((doc) => doc.favorite) : filteredDocuments

  return (
    <ScrollBox sx={{ height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }}>
      <Container maxWidth={false}>
        <Box sx={{ display: "flex", justifyContent: "flex-end", alignItems: "center", mb: 1 }}>
          <Button variant="contained" onClick={onShowDemandes} sx={{ textTransform: "none" }}>
            Mes Demandes
          </Button>
        </Box>
        <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 1 }}>
          <Paper component="form" sx={{ p: "2px userUuid as stringpx", display: "flex", alignItems: "center", width: 400 }}>
            <IconButton sx={{ p: "10px" }} aria-label="search">
              <SearchIcon />
            </IconButton>
            <InputBase
              sx={{ ml: 1, flex: 1 }}
              placeholder="Rechercher des documents"
              inputProps={{ "aria-label": "rechercher des documents" }}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
            <Divider sx={{ height: 28, m: 0.5 }} orientation="vertical" />
            <FileTypeFilter
              fileTypes={fileTypes}
              selectedFileTypes={selectedFileTypes}
              onChange={handleFileTypeFilterChange}
            />
          </Paper>
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
              <Box
                sx={{
                  display: "flex",
                  border: "1px solid",
                  borderColor: "divider",
                  borderRadius: 1,
                  overflow: "hidden",
                }}
              >
                <IconButton
                  onClick={() => handleViewModeChange("grid")}
                  color={viewMode === "grid" ? "primary" : "default"}
                  size="small"
                  sx={{ borderRadius: 0 }}
                >
                  <GridViewIcon />
                </IconButton>
                <IconButton
                  onClick={() => handleViewModeChange("list")}
                  color={viewMode === "list" ? "primary" : "default"}
                  size="small"
                  sx={{ borderRadius: 0 }}
                >
                  <ViewListIcon />
                </IconButton>
              </Box>
            </Box>
            <IconButton
              sx={{
                backgroundColor: showOnlyFavorites ? "rgba(255, 215, 0, 0.2)" : "transparent",
                color: showOnlyFavorites ? "gold" : "grey",
                fontSize: "1.5rem",
                padding: 1,
                borderRadius: "8px",
                "&:hover": {
                  backgroundColor: "rgba(255, 215, 0, 0.userUuid as string)",
                },
              }}
              onClick={() => setShowOnlyFavorites((prev) => !prev)}
            >
              <FontAwesomeIcon
                icon={faStar}
                style={{
                  fontSize: "1.2rem",
                  color: showOnlyFavorites ? "gold" : "grey",
                }}
              />
            </IconButton>
          </Box>
        </Box>

        <Box sx={{ my: 2 }}>
          <ConditionalComponent
            isValid={!loading && !!quota && !error}
            defaultComponent={
              <LinearProgress color="primary" sx={{ width: '100%', height: 8 }} />
            }
          >
            <StorageUsage
              usedBytes={quota?.usedStorageBytes || 0}
              totalBytes={quota?.storageQuotaBytes || 0}
              usedFormatted={quota?.usedStorageFormatted || "0 B"}
              totalFormatted={quota?.storageQuotaFormatted || "1.0 GB"}
            />
          </ConditionalComponent>
        </Box>

        {/* Folder navigation */}
        <Box sx={{ display: "flex", alignItems: "center", mb: 2 }}>
          <ConditionalComponent isValid={!!currentFolder}>
            <IconButton onClick={handleBackToParent} sx={{ mr: 1 }}>
              <ArrowBackIcon />
            </IconButton>
          </ConditionalComponent>

          <Breadcrumbs separator={<NavigateNextIcon fontSize="small" />} aria-label="breadcrumb">
            <Link
              underline="hover"
              sx={{ display: "flex", alignItems: "center", cursor: "pointer" }}
              color="inherit"
              onClick={() => navigateToPathIndex(-1)}
            >
              <HomeIcon sx={{ mr: 0.5 }} fontSize="inherit" />
              Accueil
            </Link>

            {folderPath.map((folder, index) => (
              <Link
                key={folder.id}
                underline="hover"
                sx={{ display: "flex", alignItems: "center", cursor: "pointer" }}
                color="inherit"
                onClick={() => navigateToPathIndex(index)}
              >
                {folder.name}
              </Link>
            ))}

            <ConditionalComponent isValid={!!currentFolder}>
              <Typography color="text.primary" sx={{ display: "flex", alignItems: "center" }}>
                {currentFolder?.name}
              </Typography>
            </ConditionalComponent>
          </Breadcrumbs>
        </Box>
          <>
            <DocumentManagerPanel
              title="Dossiers"
              subTitle={`${displayedFolders.length} dossier${displayedFolders.length !== 1 ? "s" : ""}`}
              onOpen={handleCreateFolder}
              isAddIconVisible={true}
              collapse={foldersCollapsed}
              onCollapse={() => setFoldersCollapsed((prev) => !prev)}
            />

            <ConditionalComponent isValid={!foldersCollapsed}>
              <ConditionalComponent
                isValid={displayedFolders.length > 0}
                defaultComponent={
                  <EmptyContent
                    filled
                    title="Aucun Dossier trouvé"
                    sx={{
                      gridColumn: "span 4",
                      height: "auto",
                      minHeight: "300px",
                    }}
                  />
                }
              >
                <ConditionalComponent
                  isValid={viewMode === "grid"}
                  defaultComponent={
                    <Box sx={{ mb: 4}}>
                      {displayedFolders.map((folder) => (
                        <Box
                          key={folder.id}
                          sx={{
                            display: "flex",
                            alignItems: "center",
                            p: 1,
                            borderBottom: "1px solid",
                            borderColor: "divider",
                            "&:hover": {
                              bgcolor: "action.hover",
                            },
                            cursor: "pointer",
                          }}
                          onClick={() => handleFolderClick(folder)}
                        >
                          <Box sx={{ mr: 2 }}>
                            <FileThumbnail file={"folder"} sx={{ width: 26, height: 26 }} />
                          </Box>
                          <Box sx={{ flexGrow: 1 }}>
                            <Typography variant="body1">{folder.name}</Typography>
                            <Typography variant="caption" color="text.secondary">
                              {folder.documents?.length || 0} fichier{(folder.documents?.length || 0) !== 1 ? "s" : ""}
                            </Typography>
                          </Box>
                          <IconButton
                            size="small"
                            onClick={(e) => {
                              e.stopPropagation()
                            }}
                          >
                            <MoreVertIcon fontSize="small" />
                          </IconButton>
                        </Box>
                      ))}
                    </Box>
                  }
                >
                  <Grid container spacing={2}>
                    {displayedFolders.map((folder) => (
                      <Grid item xs={12} sm={6} md={4} lg={3} xl={2} key={folder.id}>
                        <FolderCard
                          folder={folder} 
                          onClick={() => handleFolderClick(folder)} 
                          onRename={(folder) => {
                            setFolderToRename(folder);
                            setRenameDialogOpen(true);
                          }}
                          onMove={() => handleOpenMoveDialog(folder)} 
                          onDelete={handleDeleteFolder}
                          onShowDetails={handleShowDetails}
                          onMarkAsFavorite={handleToggleFavorite}
                          onUnmarkAsFavorite={handleToggleFavorite}/>
                          
                      </Grid>
                    ))}
                  </Grid>
                </ConditionalComponent>
              </ConditionalComponent>
            </ConditionalComponent>
          </>
        <DocumentManagerPanel
          title="Fichiers"
          subTitle={`${displayedDocuments.length} fichier${displayedDocuments.length !== 1 ? "s" : ""}`}
          onOpen={handleUploadFile}
          isAddIconVisible={true}
          collapse={filesCollapsed}
          onCollapse={() => setFilesCollapsed((prev) => !prev)}
        />

        <ConditionalComponent isValid={!filesCollapsed}>
          <ConditionalComponent
            isValid={displayedDocuments.length > 0}
            defaultComponent={
              <EmptyContent
                filled
                title="Aucun fichier trouvé"
                sx={{
                  gridColumn: "span userUuid as string",
                  height: "auto",
                  minHeight: "300px",
                }}
              />
            }
          >
            <ConditionalComponent
              isValid={viewMode === "grid"}
              defaultComponent={
                <Box sx={{ mb: userUuid as string }}>
                  {displayedDocuments.map((document) => (
                    <Box
                      key={document.id}
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        p: 1,
                        borderBottom: "1px solid",
                        borderColor: "divider",
                        "&:hover": {
                          bgcolor: "action.hover",
                        },
                      }}
                    >
                      <Box sx={{ mr: 2 }}>
                        <FileThumbnail file={document.contentType || "PDF"} sx={{ width: 26, height: 26 }} />
                      </Box>
                      <Box sx={{ flexGrow: 1 }}>
                        <Typography variant="body1">{document.name}</Typography>
                        <Typography variant="caption" color="text.secondary">
                          {document.documentType} • Taille: {(document.size / 1024).toFixed(2)} KB
                        </Typography>
                      </Box>
                      <IconButton size="small">
                        <MoreVertIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  ))}
                </Box>
              }
            >
              <Grid container spacing={2}>
                {displayedDocuments.map((document) => (
                  <Grid item xs={12} sm={6} md={4} lg={3} xl={2} key={document.id}>
                    <DocumentCard 
                      document={document} 
                      onClick={() => handleOpenPreviewDocumentDialog(document)}
                      onDownload={() => handleDownload(document)}
                      onShare={(targetUserUuid : string) => handleShareDocument(document, targetUserUuid)}
                      onRename={(newName : string) => handleRenameDocument(document, newName)}
                      onDelete={() => handleDelete(document)}
                      onMarkAsFavorite={() => handleToggleDocumentFavorite(document)}
                      onUnmarkAsFavorite={() => handleToggleDocumentFavorite(document)}
                      onShowDetails={() => handleShowDocumentDetails(document)}
                      onMove={() => handleOpenMoveDocumentDialog(document)}/>
                  </Grid>
                ))}
              </Grid>
            </ConditionalComponent>
          </ConditionalComponent>
        </ConditionalComponent>

        <UploadFileDialog
          open={isUploadDialogOpen}
          onClose={() => setIsUploadDialogOpen(false)}
          onUpload={handleAddDocument}
          folder={currentFolder}
        />

        <CreateFolderDialog
          open={isCreateFolderDialogOpen}
          onClose={() => setIsCreateFolderDialogOpen(false)}
          onCreateFolder={handleAddFolder}
        />

        <RenameFolderDialog
          open={renameDialogOpen}
          onClose={() => setRenameDialogOpen(false)}
          onRename={handleRenameFolder}
          initialName={folderToRename?.name || ""}
        />
        <ConditionalComponent isValid={!!folderToMove}>
           <MoveFolderDialog
            open={moveDialogOpen}
            onClose={() => {
              setMoveDialogOpen(false)
              setFolderToMove(null)
            }}
            onConfirm={handleMoveFolder}
            folders={folders.filter(f => f.id !== folderToMove?.id)} // exclude moved folder
            currentFolderId={Number(folderToMove?.id)}
          />
        </ConditionalComponent>
        <ConfirmDeleteDialog
          open={isDeleteDialogOpen}
          onClose={() => setIsDeleteDialogOpen(false)}
          onConfirm={confirmDeleteFolder}
          itemName={selectedFolderToDelete?.name || ""}
        />
        <FolderDetailsDialog
          open={detailsDialogOpen}
          onClose={() => setDetailsDialogOpen(false)}
          details={selectedFolderDetails}
        />
        <DocumentPreviewDialog
          open={previewDocumentDialogOpen}
          onClose={() => setSelectedDocument(null)}
          document={selectedDocument}
        />
        <DocumentDetailsDialog
          open={documentDetailsDialogOpen}
          onClose={() => {
            setDocumentDetailsDialogOpen(false);
            setSelectedDocument(null);
          }}
          document={selectedDocument}
        />
        <MoveDocumentDialog
          open={moveDocumentDialogOpen}
          onClose={() => {
            setMoveDocumentDialogOpen(false);
            setSelectedDocument(null);
          }}
          onConfirm={handleMoveDocument}
          folders={folders}
          document={selectedDocument}
          currentFolderId={currentFolder?.id || null}
        />
      </Container>
    </ScrollBox>
  )
}
