// 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]);

  // 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");
      const draggedItems = JSON.parse(data);

      // Prevent moving a folder into itself or its subdirectories
      if (draggedItems.includes(path.basename(destinationPath))) {
        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>
          <Typography variant="h6" sx={{ flexGrow: 1, marginLeft: 1 }}>
            {currentDir}
          </Typography>
          <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>

        {/* Breadcrumb Navigation */}
        <Box
          sx={{
            padding: 2,
            display: "flex",
            alignItems: "center",
            flexWrap: "wrap",
          }}
        >
          {breadcrumb.map((dir, index) => {
            const path = breadcrumb.slice(0, index + 1).join("/");
            const displayName = dir === "/" ? "/" : dir;
            const isLast = index === breadcrumb.length - 1;

            return (
              <React.Fragment key={index}>
                <Button
                  variant="text"
                  onClick={() => fetchDirectory(path === "" ? "/" : `/${path}`)}
                  disabled={isLast}
                  onDragEnter={() => setDragOverBreadcrumbIndex(index)}
                  onDragLeave={() => setDragOverBreadcrumbIndex(null)}
                  onDragOver={(e) => handleDragOver(e)}
                  onDrop={(e) => handleDrop(e, path === "" ? "/" : `/${path}`)}
                  sx={{
                    backgroundColor:
                      dragOverBreadcrumbIndex === index
                        ? "grey.300"
                        : "transparent",
                  }}
                >
                  {displayName}
                </Button>
                {!isLast && <Typography>/</Typography>}
              </React.Fragment>
            );
          })}
        </Box>

        {/* 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;


ReferenceError: path is not defined
    handleDrop Documents.js:360
    onDrop Documents.js:562
    React 23
    renderReactElement index.tsx:582
    doRender index.tsx:795
    render index.tsx:824
    hydrate index.tsx:993
    pageBootrap page-bootstrap.ts:22
    <anonymous> next-dev.ts:21
    promise callback* next-dev.ts:20
    NextJS 7
hydration-error-info.ts:72:9
    error hydration-error-info.ts:72
    error setup-hydration-warning.ts:21
    handleDrop Documents.js:381
    onDrop Documents.js:562
    React 23
    renderReactElement index.tsx:582
    doRender index.tsx:795
    render index.tsx:824
    hydrate index.tsx:993
    pageBootrap page-bootstrap.ts:22
    <anonymous> next-dev.ts:21
    (Async: promise callback)
    <anonymous> next-dev.ts:20
    NextJS 7
fix