"use client"

import { useState, useEffect } from "react"
import {
  Box,
  Container,
  Typography,
  Grid,
  Paper,
  InputBase,
  IconButton,
  Button,
  Divider,
  Breadcrumbs,
  Link,
} 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"


interface DocumentDriveProps {
  onShowDemandes: () => void
}

export default function DocumentDrive({ onShowDemandes }: DocumentDriveProps) {
  const [documents, setDocuments] = 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 [usedStorageQuota, setUsedStorageQuota] = useState<number>(7.18)
  const [storageQuota, setStorageQuota] = useState<number>(15)
  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 { createFolder, getRootFolders, renameFolder, moveFolder, searchFolders } = useFolderStore()

  useEffect(() => {
    // Load real folders from backend
    const loadRootFolders = async () => {
      try {
        const rootFolders = await getRootFolders(4) // Using owner ID 4
        setFolders(rootFolders)
        setFilteredFolders(rootFolders)

        // Extract documents from all root folders
        const allDocuments = rootFolders.flatMap((folder : FolderDTO) => folder.documents || [])
        setDocuments(allDocuments)
        setFilteredDocuments(allDocuments)
      } catch (error) {
        console.error("Failed to load root folders:", error)
        // Fallback to empty arrays if API fails
        setFolders([])
        setFilteredFolders([])
        setDocuments([])
        setFilteredDocuments([])
      }
    }

    loadRootFolders()
  }, [])

  useEffect(() => {
  const runSearch = async () => {
    if (!searchQuery) {
      setFilteredFolders(currentFolder ? currentFolder.subFolders || [] : folders)
      return
    }
     const result = await searchFolders(searchQuery, 4)
     setFilteredFolders(result)
    
  }

  runSearch()
}, [searchQuery, currentFolder, folders])

  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,
        parentId: currentFolder?.id || null, // null for root folders
        ownerId: 4, // Using owner ID 4
      })

      // Reload folders and documents after creation
      const updatedFolders = await getRootFolders(4)
      setFolders(updatedFolders)
      setFilteredFolders(updatedFolders)

      // Update documents from folders
      const allDocuments = updatedFolders.flatMap((folder : FolderDTO) => folder.documents || [])
      setDocuments(allDocuments)
      setFilteredDocuments(allDocuments)

      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);
    setSelectedFolderDetails(details);
    setDetailsDialogOpen(true);
  };

  const handleAddDocument = (document: DocumentDTO) => {
    if (currentFolder) {
      // Add document to current folder
      const updatedFolders = [...folders]

      const updateFolderRecursively = (foldersList: FolderDTO[], targetId: number): boolean => {
        for (let i = 0; i < foldersList.length; i++) {
          if (foldersList[i].id === targetId) {
            foldersList[i].documents = [...(foldersList[i].documents || []), document]
            return true
          }

          const subFolders = foldersList[i].subFolders
          if (subFolders && subFolders.length > 0) {
            if (updateFolderRecursively(subFolders, targetId)) {
              return true
            }
          }
        }
        return false
      }
      updateFolderRecursively(updatedFolders, currentFolder.id)
      setFolders(updatedFolders)

      // Update current folder
      setCurrentFolder({
        ...currentFolder,
        documents: [...(currentFolder.documents || []), document],
      })

      // Update filtered documents
      setFilteredDocuments([...filteredDocuments, document])
    } else {
      // Add to root documents
      setDocuments([...documents, document])
      setFilteredDocuments([...filteredDocuments, document])
    }

    setIsUploadDialogOpen(false)
  }

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

  }
};
  const handleRenameFolder = async (newName: string) => {
  if (folderToRename) {
    try {
      await renameFolder(folderToRename.id, newName, 4);
      const updatedFolders = await getRootFolders(4);
      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, 4)

    // 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 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("")
  }

  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 || [])
  }

  // 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 4px", 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.4)",
                },
              }}
              onClick={() => setShowOnlyFavorites((prev) => !prev)}
            >
              <FontAwesomeIcon
                icon={faStar}
                style={{
                  fontSize: "1.2rem",
                  color: showOnlyFavorites ? "gold" : "grey",
                }}
              />
            </IconButton>
          </Box>
        </Box>

        <Box sx={{ my: 2 }}>
          <StorageUsage usedSpace={usedStorageQuota} totalSpace={storageQuota} />
        </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>

        <ConditionalComponent isValid={displayedFolders.length > 0}>
          <>
            <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}/>

                      </Grid>
                    ))}
                  </Grid>
                </ConditionalComponent>
              </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 4",
                  height: "auto",
                  minHeight: "300px",
                }}
              />
            }
          >
            <ConditionalComponent
              isValid={viewMode === "grid"}
              defaultComponent={
                <Box sx={{ mb: 4 }}>
                  {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} />
                  </Grid>
                ))}
              </Grid>
            </ConditionalComponent>
          </ConditionalComponent>
        </ConditionalComponent>

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

        <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}
        />
      </Container>
    </ScrollBox>
  )
}
