// components/WindowsFileManager.js
import React, { useState, useEffect, useRef } from "react";
import {
  Box,
  IconButton,
  Button,
  Grid,
  Paper,
  Snackbar,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Tooltip,
  Typography,
  CircularProgress,
  Menu,
} from "@mui/material";
import {
  Folder as FolderIcon,
  InsertDriveFile as FileIcon,
  Delete as DeleteIcon,
  CreateNewFolder as CreateNewFolderIcon,
  FileCopy as FileCopyIcon,
  ViewModule as ViewModuleIcon,
  ViewList as ViewListIcon,
  ArrowBack as ArrowBackIcon,
  MoreVert as MoreVertIcon,
  Refresh as RefreshIcon,
} from "@mui/icons-material";
import axios from "axios";

const WindowsFileManager = () => {
  // State variables
  const [currentDir, setCurrentDir] = useState("/"); // Current directory path
  const [items, setItems] = useState([]); // Files and folders in current directory
  const [viewMode, setViewMode] = useState("grid"); // 'grid' or 'list'
  const [selectedItems, setSelectedItems] = useState([]); // Currently selected items
  const [lastSelectedIndex, setLastSelectedIndex] = useState(null); // For Shift-click selection
  const [openCreateDialog, setOpenCreateDialog] = useState(false);
  const [createName, setCreateName] = useState("");
  const [createType, setCreateType] = useState("folder"); // 'folder' or 'file'
  const [openCopyDialog, setOpenCopyDialog] = useState(false);
  const [copyDestination, setCopyDestination] = useState("");
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: "",
    severity: "success",
  });
  const [breadcrumb, setBreadcrumb] = useState(["/"]);
  const [loading, setLoading] = useState(false);

  // Context Menu State
  const [contextMenu, setContextMenu] = useState(null);
  const [contextItem, setContextItem] = useState(null);

  // State to track which breadcrumb segment is being hovered for visual feedback
  const [dragOverBreadcrumbIndex, setDragOverBreadcrumbIndex] = useState(null);

  // Ref for tracking the list items
  const itemsRef = useRef([]);

  // Fetch directory contents
  const fetchDirectory = async (dir = "/") => {
    setLoading(true);
    try {
      const res = await axios.get("/api/filesystem/list", { params: { dir } });
      setCurrentDir(res.data.path);
      setItems(res.data.items);
      setSelectedItems([]);
      // Update breadcrumb based on the new directory
      if (res.data.path === "/") {
        setBreadcrumb(["/"]);
      } else {
        const pathSegments = res.data.path.split("/").filter(Boolean);
        setBreadcrumb(["/", ...pathSegments]);
      }
      itemsRef.current = res.data.items;
    } catch (error) {
      console.error(error);
      showSnackbar(
        error.response?.data?.error || "Error fetching directory",
        "error"
      );
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDirectory();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Handle navigation to a directory
  const navigateTo = (dir) => {
    fetchDirectory(dir);
  };

  // Handle navigation back
  const navigateBack = () => {
    if (breadcrumb.length <= 1) return; // Already at root

    const newBreadcrumb = [...breadcrumb];
    newBreadcrumb.pop(); // Remove the last segment

    const previousPath =
      newBreadcrumb.length === 1 ? "/" : `/${newBreadcrumb.slice(1).join("/")}`;
    setBreadcrumb(newBreadcrumb);
    fetchDirectory(previousPath);
  };

  // Handle item selection with Shift and Ctrl/Cmd
  const handleSelect = (event, item, index) => {
    const isSelected = selectedItems.includes(item.name);

    if (event.shiftKey && lastSelectedIndex !== null) {
      // Shift+Click: Select range
      const start = Math.min(lastSelectedIndex, index);
      const end = Math.max(lastSelectedIndex, index);
      const range = items.slice(start, end + 1).map((i) => i.name);
      setSelectedItems((prev) => Array.from(new Set([...prev, ...range])));
    } else if (event.ctrlKey || event.metaKey) {
      // Ctrl/Cmd+Click: Toggle selection
      if (isSelected) {
        setSelectedItems((prev) => prev.filter((name) => name !== item.name));
      } else {
        setSelectedItems((prev) => [...prev, item.name]);
      }
      setLastSelectedIndex(index);
    } else {
      // Regular Click: Select or Deselect
      if (isSelected && selectedItems.length === 1) {
        // If the item is already the only selected, deselect it
        setSelectedItems([]);
        setLastSelectedIndex(null);
      } else if (isSelected) {
        // If multiple items are selected and clicked item is one of them, deselect it
        setSelectedItems((prev) => prev.filter((name) => name !== item.name));
        setLastSelectedIndex(index);
      } else {
        // Select only the clicked item
        setSelectedItems([item.name]);
        setLastSelectedIndex(index);
      }
    }
  };

  // Handle creating new folder/file
  const handleCreate = async () => {
    if (!createName.trim()) {
      showSnackbar("Name cannot be empty", "error");
      return;
    }

    try {
      await axios.post("/api/filesystem/create", {
        dir: currentDir,
        name: createName.trim(),
        type: createType,
      });
      showSnackbar(
        `${createType === "folder" ? "Folder" : "File"} created successfully`,
        "success"
      );
      setOpenCreateDialog(false);
      setCreateName("");
      setCreateType("folder");
      fetchDirectory(currentDir);
    } catch (error) {
      console.error(error);
      showSnackbar(
        error.response?.data?.error || "Error creating item",
        "error"
      );
    }
  };

  // Handle deleting selected items
  const handleDelete = async () => {
    if (selectedItems.length === 0) {
      showSnackbar("No items selected for deletion", "error");
      return;
    }

    if (!window.confirm("Are you sure you want to delete the selected items?"))
      return;

    try {
      await Promise.all(
        selectedItems.map((name) =>
          axios.delete("/api/filesystem/delete", {
            data: { path: `${currentDir}/${name}` },
          })
        )
      );
      showSnackbar("Selected items deleted successfully", "success");
      fetchDirectory(currentDir);
    } catch (error) {
      console.error(error);
      showSnackbar(
        error.response?.data?.error || "Error deleting items",
        "error"
      );
    }
  };

  // Handle copying selected items
  const handleCopy = async () => {
    if (selectedItems.length === 0) {
      showSnackbar("No items selected for copying", "error");
      return;
    }

    if (!copyDestination.trim()) {
      showSnackbar("Destination path cannot be empty", "error");
      return;
    }

    try {
      await Promise.all(
        selectedItems.map((name) =>
          axios.post("/api/filesystem/copy", {
            source: `${currentDir}/${name}`,
            destination: copyDestination.trim(),
          })
        )
      );
      showSnackbar("Selected items copied successfully", "success");
      setOpenCopyDialog(false);
      setCopyDestination("");
      fetchDirectory(currentDir);
    } catch (error) {
      console.error(error);
      showSnackbar(
        error.response?.data?.error || "Error copying items",
        "error"
      );
    }
  };

  // Handle right-click context menu
  const handleContextMenu = (event, item, index) => {
    event.preventDefault();
    setContextItem(item);
    setContextMenu(
      contextMenu === null
        ? {
            mouseX: event.clientX - 2,
            mouseY: event.clientY - 4,
            index: index,
          }
        : null
    );
  };

  const handleCloseContextMenu = () => {
    setContextMenu(null);
    setContextItem(null);
  };

  // Handle actions from context menu
  const handleContextAction = (action) => {
    switch (action) {
      case "open":
        if (contextItem.isDirectory) {
          navigateTo(`${currentDir}/${contextItem.name}`);
        } else {
          // Implement file opening logic if needed
          showSnackbar(`Opening file: ${contextItem.name}`, "info");
        }
        break;
      case "delete":
        setSelectedItems([contextItem.name]);
        handleDelete();
        break;
      case "copy":
        setSelectedItems([contextItem.name]);
        setOpenCopyDialog(true);
        break;
      case "rename":
        // Implement rename functionality
        showSnackbar("Rename functionality not implemented yet.", "info");
        break;
      default:
        break;
    }
    handleCloseContextMenu();
  };

  // Show snackbar notification
  const showSnackbar = (message, severity = "success") => {
    setSnackbar({ open: true, message, severity });
  };

  // Handle item double-click (navigate into directory or open file)
  const handleItemDoubleClick = (item) => {
    if (item.isDirectory) {
      navigateTo(`${currentDir}/${item.name}`);
    } else {
      // Implement file opening logic if needed
      showSnackbar(`Opening file: ${item.name}`, "info");
    }
  };

  // Handle keyboard shortcuts (e.g., Delete key)
  const handleKeyDown = (event) => {
    if (event.key === "Delete") {
      handleDelete();
    }
  };

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);

    return () => window.removeEventListener("keydown", handleKeyDown);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedItems]);

  /**
   * Helper function to get the basename of a path
   * @param {string} pathStr - The path string
   * @returns {string} - The basename of the path
   */
  const getBaseName = (pathStr) => {
    if (pathStr === "/") return "/";
    const segments = pathStr.split("/").filter(Boolean);
    return segments.length > 0 ? segments[segments.length - 1] : "/";
  };

  // Drag and Drop Handlers
  const handleDragStart = (event, item, index) => {
    let draggedItems = [];
    if (selectedItems.includes(item.name)) {
      // If the dragged item is selected, drag all selected items
      draggedItems = selectedItems;
    } else {
      // Else, drag only the current item
      draggedItems = [item.name];
      setSelectedItems([item.name]); // Select the dragged item
    }
    event.dataTransfer.setData(
      "application/json",
      JSON.stringify(draggedItems)
    );
    event.dataTransfer.effectAllowed = "move";
  };

  const handleDragOver = (event) => {
    event.preventDefault();
    event.dataTransfer.dropEffect = "move";
  };

  /**
   * Handles the drop event for both folder items and breadcrumb segments.
   * @param {Event} event - The drop event.
   * @param {string} destinationPath - The path where items are to be moved.
   */
  const handleDrop = async (event, destinationPath) => {
    event.preventDefault();
    try {
      const data = event.dataTransfer.getData("application/json");
      if (!data) {
        showSnackbar("No items were dragged.", "error");
        return;
      }
      const draggedItems = JSON.parse(data);

      // Get the basename of the destination path
      const baseName = getBaseName(destinationPath);

      // Prevent moving a folder into itself or its subdirectories
      if (draggedItems.includes(baseName)) {
        showSnackbar(
          "Cannot move a folder into itself or its subdirectories.",
          "error"
        );
        return;
      }

      // Perform the move operation for each dragged item
      await Promise.all(
        draggedItems.map((name) =>
          axios.post("/api/filesystem/move", {
            source: `${currentDir}/${name}`,
            destination: destinationPath, // Correct destination path
          })
        )
      );

      showSnackbar("Items moved successfully", "success");
      fetchDirectory(currentDir);
    } catch (error) {
      console.error(error);
      showSnackbar(
        error.response?.data?.error || "Error moving items",
        "error"
      );
    } finally {
      // Reset drag over state
      setDragOverBreadcrumbIndex(null);
    }
  };

  return (
    <Box sx={{ display: "flex", height: "76vh" }}>
      {/* Main Content */}
      <Box
        sx={{
          flexGrow: 1,
          bgcolor: "background.default",
          p: 3,
          overflow: "auto",
        }}
      >
        {/* Top Bar */}
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            marginBottom: 2,
          }}
        >
          <Tooltip title="Go Back">
            <span>
              <IconButton
                edge="start"
                color="inherit"
                onClick={navigateBack}
                disabled={breadcrumb.length <= 1}
              >
                <ArrowBackIcon />
              </IconButton>
            </span>
          </Tooltip>
          <Box
            sx={{
              padding: 2,
              display: "flex",
              alignItems: "center",
              flexWrap: "wrap",
            }}
          >
            {breadcrumb.map((dir, index) => {
              const pathSegments = breadcrumb.slice(0, index + 1);
              const path =
                pathSegments.length === 1
                  ? "/"
                  : "/" + pathSegments.slice(1).join("/");
              const displayName = dir === "/" ? "C:" : dir;
              const isLast = index === breadcrumb.length - 1;

              return (
                <React.Fragment key={index}>
                  <Button
                    variant="text"
                    onClick={() => fetchDirectory(path)}
                    disabled={isLast}
                    onDragEnter={() => setDragOverBreadcrumbIndex(index)}
                    onDragLeave={() => setDragOverBreadcrumbIndex(null)}
                    onDragOver={(e) => handleDragOver(e)}
                    onDrop={(e) => handleDrop(e, path)}
                    sx={{
                      backgroundColor:
                        dragOverBreadcrumbIndex === index
                          ? "grey.300"
                          : "transparent",
                    }}
                  >
                    {displayName}
                  </Button>
                  {!isLast && <Typography>/</Typography>}
                </React.Fragment>
              );
            })}
          </Box>
          <Box sx={{ display: "flex", alignItems: "center", ml: "auto" }}>
            <Tooltip title="Refresh">
              <IconButton
                color="inherit"
                onClick={() => fetchDirectory(currentDir)}
              >
                <RefreshIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Create New">
              <IconButton
                color="inherit"
                onClick={() => setOpenCreateDialog(true)}
              >
                <CreateNewFolderIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Copy" placement="bottom">
              <span>
                <IconButton
                  color="inherit"
                  onClick={() => setOpenCopyDialog(true)}
                  disabled={selectedItems.length === 0}
                >
                  <FileCopyIcon />
                </IconButton>
              </span>
            </Tooltip>
            <Tooltip
              title={
                viewMode === "grid"
                  ? "Switch to List View"
                  : "Switch to Grid View"
              }
            >
              <IconButton
                color="inherit"
                onClick={() =>
                  setViewMode(viewMode === "grid" ? "list" : "grid")
                }
              >
                {viewMode === "grid" ? <ViewListIcon /> : <ViewModuleIcon />}
              </IconButton>
            </Tooltip>
            <Tooltip title="Delete" placement="bottom">
              <span>
                <IconButton
                  color="inherit"
                  onClick={handleDelete}
                  disabled={selectedItems.length === 0}
                >
                  <DeleteIcon />
                </IconButton>
              </span>
            </Tooltip>
          </Box>
        </Box>

        {/* Breadcrumb Navigation */}

        {/* File/Folder Listing */}
        <Box sx={{ padding: 2 }}>
          {loading ? (
            <Box sx={{ display: "flex", justifyContent: "center", mt: 4 }}>
              <CircularProgress />
            </Box>
          ) : viewMode === "grid" ? (
            <Grid container spacing={2}>
              {items.map((item, index) => (
                <Grid item xs={6} sm={4} md={3} key={item.name}>
                  <Paper
                    elevation={selectedItems.includes(item.name) ? 4 : 1}
                    sx={{
                      padding: 2,
                      textAlign: "center",
                      cursor: "pointer",
                      backgroundColor: selectedItems.includes(item.name)
                        ? "primary.light"
                        : "background.paper",
                      position: "relative",
                      height: "120px",
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                      alignItems: "center",
                      color: "text.primary",
                      border: selectedItems.includes(item.name)
                        ? "2px solid #1976d2"
                        : "none",
                      "&:hover": {
                        backgroundColor: "grey.100",
                      },
                    }}
                    onClick={(e) => handleSelect(e, item, index)}
                    onDoubleClick={() => handleItemDoubleClick(item)}
                    onContextMenu={(e) => handleContextMenu(e, item, index)}
                    draggable
                    onDragStart={(e) => handleDragStart(e, item, index)}
                    onDragOver={
                      item.isDirectory ? (e) => handleDragOver(e) : null
                    }
                    onDrop={
                      item.isDirectory
                        ? (e) => handleDrop(e, `${currentDir}/${item.name}`)
                        : null
                    }
                  >
                    {item.isDirectory ? (
                      <FolderIcon sx={{ fontSize: 50, color: "#FFD700" }} />
                    ) : (
                      <FileIcon sx={{ fontSize: 50 }} />
                    )}
                    <Typography variant="subtitle1" noWrap>
                      {item.name}
                    </Typography>
                  </Paper>
                </Grid>
              ))}
              {items.length === 0 && (
                <Typography variant="body1">This folder is empty.</Typography>
              )}
            </Grid>
          ) : (
            <Box>
              {/* List Header */}
              <Box
                sx={{
                  display: "flex",
                  padding: "8px 16px",
                  backgroundColor: "grey.200",
                  alignItems: "center",
                  fontWeight: "bold",
                }}
              >
                <Typography sx={{ flex: 2 }}>Name</Typography>
                <Typography sx={{ flex: 2 }}>Size</Typography>
                <Typography sx={{ flex: 2 }}>Type</Typography>
                <Typography sx={{ flex: 3 }}>Last Modified</Typography>
              </Box>
              {/* List Items */}
              {items.map((item, index) => (
                <Box
                  key={item.name}
                  sx={{
                    display: "flex",
                    padding: "8px 16px",
                    backgroundColor: selectedItems.includes(item.name)
                      ? "primary.light"
                      : "background.paper",
                    alignItems: "center",
                    cursor: "pointer",
                    borderBottom: "1px solid #e0e0e0",
                    "&:hover": {
                      backgroundColor: "grey.100",
                    },
                  }}
                  onClick={(e) => handleSelect(e, item, index)}
                  onDoubleClick={() => handleItemDoubleClick(item)}
                  onContextMenu={(e) => handleContextMenu(e, item, index)}
                  draggable
                  onDragStart={(e) => handleDragStart(e, item, index)}
                  onDragOver={
                    item.isDirectory ? (e) => handleDragOver(e) : null
                  }
                  onDrop={
                    item.isDirectory
                      ? (e) => handleDrop(e, `${currentDir}/${item.name}`)
                      : null
                  }
                >
                  <Box sx={{ flex: 2, display: "flex", alignItems: "center" }}>
                    {item.isDirectory ? (
                      <FolderIcon sx={{ marginRight: 1 }} />
                    ) : (
                      <FileIcon sx={{ marginRight: 1 }} />
                    )}
                    <Typography noWrap>{item.name}</Typography>
                  </Box>
                  <Box sx={{ flex: 2 }}>
                    <Typography>
                      {item.size ? `${item.size} KB` : "--"}
                    </Typography>
                  </Box>
                  <Box sx={{ flex: 2 }}>
                    <Typography>
                      {item.isDirectory ? "Folder" : "File"}
                    </Typography>
                  </Box>
                  <Box sx={{ flex: 3 }}>
                    <Typography>{item.modified || "--"}</Typography>
                  </Box>
                </Box>
              ))}
              {items.length === 0 && (
                <Typography variant="body1" sx={{ padding: 2 }}>
                  This folder is empty.
                </Typography>
              )}
            </Box>
          )}
        </Box>
      </Box>

      {/* Create Dialog */}
      <Dialog
        open={openCreateDialog}
        onClose={() => setOpenCreateDialog(false)}
      >
        <DialogTitle>
          Create New {createType === "folder" ? "Folder" : "File"}
        </DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="Name"
            fullWidth
            value={createName}
            onChange={(e) => setCreateName(e.target.value)}
          />
          <FormControl fullWidth sx={{ marginTop: 2 }}>
            <InputLabel>Type</InputLabel>
            <Select
              value={createType}
              label="Type"
              onChange={(e) => setCreateType(e.target.value)}
            >
              <MenuItem value="folder">Folder</MenuItem>
              <MenuItem value="file">File</MenuItem>
            </Select>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenCreateDialog(false)}>Cancel</Button>
          <Button onClick={handleCreate} variant="contained" color="primary">
            Create
          </Button>
        </DialogActions>
      </Dialog>

      {/* Copy Dialog */}
      <Dialog open={openCopyDialog} onClose={() => setOpenCopyDialog(false)}>
        <DialogTitle>Copy Selected Items</DialogTitle>
        <DialogContent>
          <Typography variant="body2" gutterBottom>
            Destination Path:
          </Typography>
          <TextField
            autoFocus
            margin="dense"
            label="Destination"
            fullWidth
            value={copyDestination}
            onChange={(e) => setCopyDestination(e.target.value)}
            helperText="Enter the destination path where the items will be copied."
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenCopyDialog(false)}>Cancel</Button>
          <Button onClick={handleCopy} variant="contained" color="primary">
            Copy
          </Button>
        </DialogActions>
      </Dialog>

      {/* Snackbar Notification */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={4000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
        message={snackbar.message}
        anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
      />

      {/* Context Menu */}
      <Menu
        open={contextMenu !== null}
        onClose={handleCloseContextMenu}
        anchorReference="anchorPosition"
        anchorPosition={
          contextMenu !== null
            ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
            : undefined
        }
      >
        <MenuItem onClick={() => handleContextAction("open")}>
          <FolderIcon fontSize="small" style={{ marginRight: 8 }} />
          <Typography variant="inherit">Open</Typography>
        </MenuItem>
        <MenuItem onClick={() => handleContextAction("copy")}>
          <FileCopyIcon fontSize="small" style={{ marginRight: 8 }} />
          <Typography variant="inherit">Copy</Typography>
        </MenuItem>
        <MenuItem onClick={() => handleContextAction("delete")}>
          <DeleteIcon fontSize="small" style={{ marginRight: 8 }} />
          <Typography variant="inherit">Delete</Typography>
        </MenuItem>
        <MenuItem onClick={() => handleContextAction("rename")}>
          <MoreVertIcon fontSize="small" style={{ marginRight: 8 }} />
          <Typography variant="inherit">Rename</Typography>
        </MenuItem>
      </Menu>
    </Box>
  );
};

export default WindowsFileManager;


separate creating folders and files by being 2 buttons.. secondly make an upload button to upload content to the current folder, make the api too

here's the move api to help you
// pages/api/filesystem/move.js
import { getSafePath } from "../../../utils/filesystem";
import fs from "fs";
import path from "path";

/**
 * Handler for moving files and folders.
 * Supported Methods: POST
 */
export default function handler(req, res) {
  if (req.method !== "POST") {
    return res.status(405).json({ error: "Method Not Allowed" });
  }

  const { source, destination } = req.body;

  if (!source || !destination) {
    return res
      .status(400)
      .json({ error: "Source and destination are required" });
  }

  try {
    const safeSource = getSafePath(source);
    const safeDestination = getSafePath(destination);

    if (!fs.existsSync(safeSource)) {
      return res.status(404).json({ error: "Source does not exist" });
    }

    const stats = fs.lstatSync(safeSource);
    const baseName = path.basename(safeSource);
    const targetPath = path.join(safeDestination, baseName);

    // Prevent moving a directory into itself or its subdirectories
    if (safeSource.startsWith(targetPath)) {
      return res.status(400).json({
        error: "Cannot move a directory into itself or its subdirectories",
      });
    }

    // Perform the move operation
    fs.renameSync(safeSource, targetPath);

    res.status(200).json({ message: "Moved successfully" });
  } catch (error) {
    // Handle cases where fs.renameSync might fail (e.g., cross-device move)
    if (error.code === "EXDEV") {
      try {
        const safeSource = getSafePath(source);
        const safeDestination = getSafePath(destination);
        const baseName = path.basename(safeSource);
        const targetPath = path.join(safeDestination, baseName);

        if (fs.lstatSync(safeSource).isDirectory()) {
          fs.cpSync(safeSource, targetPath, { recursive: true });
          fs.rmSync(safeSource, { recursive: true, force: true });
        } else {
          fs.copyFileSync(safeSource, targetPath);
          fs.unlinkSync(safeSource);
        }

        return res.status(200).json({ message: "Moved successfully" });
      } catch (copyError) {
        console.error(copyError);
        return res
          .status(500)
          .json({ error: "Error moving items across devices" });
      }
    }

    console.error(error);
    res.status(400).json({ error: error.message });
  }
}