// components/WindowsFileManager.js
import React, { useState, useEffect } from "react";
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Drawer,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Button,
  Grid,
  Paper,
  Snackbar,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Tooltip,
  Divider,
  ListItemSecondaryAction,
  Checkbox,
  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 drawerWidth = 240;

const WindowsFileManager = () => {
  // State variables
  const [directories, setDirectories] = useState(["/"]); // Example root directories
  const [currentDir, setCurrentDir] = useState("/");
  const [items, setItems] = useState([]);
  const [viewMode, setViewMode] = useState("grid"); // 'grid' or 'list'
  const [selectedItems, setSelectedItems] = useState([]);
  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);

  // 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([]);
    } 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) => {
    setBreadcrumb((prev) => [...prev, dir]);
    fetchDirectory(dir);
  };

  // Handle navigation back
  const navigateBack = () => {
    if (breadcrumb.length <= 1) return;
    const newBreadcrumb = [...breadcrumb];
    newBreadcrumb.pop();
    const previousPath = newBreadcrumb[newBreadcrumb.length - 1];
    setBreadcrumb(newBreadcrumb);
    fetchDirectory(previousPath);
  };

  // Handle item selection
  const handleSelect = (itemName) => {
    setSelectedItems((prev) =>
      prev.includes(itemName)
        ? prev.filter((name) => name !== itemName)
        : [...prev, itemName]
    );
  };

  // Handle select all in list view
  const handleSelectAll = (event) => {
    if (event.target.checked) {
      const allNames = items.map((item) => item.name);
      setSelectedItems(allNames);
    } else {
      setSelectedItems([]);
    }
  };

  // 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) => {
    event.preventDefault();
    setContextItem(item);
    setContextMenu(
      contextMenu === null
        ? {
            mouseX: event.clientX - 2,
            mouseY: event.clientY - 4,
          }
        : // repeated contextmenu when it is already open closes it with Chrome 84 on Ubuntu
          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]);

  return (
    <Box sx={{ display: "flex", height: "76vh" }}>
      {/* Main Content */}
      <Box
        sx={{
          flexGrow: 1,
          bgcolor: "background.default",
          p: 3,
          overflow: "auto",
        }}
      >
        {/* Top Bar */}
        <AppBar position="static" color="default" elevation={1}>
          <Toolbar>
            <IconButton
              edge="start"
              color="inherit"
              onClick={navigateBack}
              disabled={breadcrumb.length <= 1}
            >
              <ArrowBackIcon />
            </IconButton>
            <Typography variant="h6" sx={{ flexGrow: 1 }}>
              {currentDir}
            </Typography>
            <Tooltip title="Refresh">
              <IconButton
                color="inherit"
                onClick={() => fetchDirectory(currentDir)}
              >
                <RefreshIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="New Folder/File">
              <IconButton
                color="inherit"
                onClick={() => setOpenCreateDialog(true)}
              >
                <CreateNewFolderIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Delete">
              <IconButton color="inherit" onClick={handleDelete}>
                <DeleteIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Copy">
              <IconButton
                color="inherit"
                onClick={() => setOpenCopyDialog(true)}
              >
                <FileCopyIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Toggle View">
              <IconButton
                color="inherit"
                onClick={() =>
                  setViewMode(viewMode === "grid" ? "list" : "grid")
                }
              >
                {viewMode === "grid" ? <ViewListIcon /> : <ViewModuleIcon />}
              </IconButton>
            </Tooltip>
          </Toolbar>
        </AppBar>

        {/* Breadcrumb Navigation */}
        <Box sx={{ padding: 2 }}>
          {breadcrumb.map((dir, index) => (
            <Button
              key={index}
              variant="text"
              onClick={() => fetchDirectory(dir)}
              disabled={index === breadcrumb.length - 1}
            >
              {dir}
            </Button>
          ))}
        </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) => (
                <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"
                        : "primary",
                      position: "relative",
                      height: "120px",
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                      alignItems: "center",
                      color: "text.primary",
                    }}
                    onClick={() => handleSelect(item.name)}
                    onDoubleClick={() => handleItemDoubleClick(item)}
                    onContextMenu={(e) => handleContextMenu(e, item)}
                  >
                    {item.isDirectory ? (
                      <FolderIcon sx={{ fontSize: 50, color: "#FFD700" }} />
                    ) : (
                      <FileIcon sx={{ fontSize: 50 }} />
                    )}
                    <Typography variant="subtitle1" noWrap>
                      {item.name}
                    </Typography>
                    <Checkbox
                      checked={selectedItems.includes(item.name)}
                      onChange={() => handleSelect(item.name)}
                      sx={{ position: "absolute", top: 0, left: 0 }}
                    />
                  </Paper>
                </Grid>
              ))}
            </Grid>
          ) : (
            <List>
              <ListItem>
                <Checkbox
                  checked={
                    selectedItems.length === items.length && items.length > 0
                  }
                  indeterminate={
                    selectedItems.length > 0 &&
                    selectedItems.length < items.length
                  }
                  onChange={handleSelectAll}
                />
                <ListItemText primary="Name" />
                <ListItemText primary="Size" />
                <ListItemText primary="Type" />
                <ListItemText primary="Last Modified" />
                <ListItemSecondaryAction>
                  <MoreVertIcon />
                </ListItemSecondaryAction>
              </ListItem>
              {items.map((item) => (
                <ListItem
                  key={item.name}
                  button
                  selected={selectedItems.includes(item.name)}
                  onClick={() => handleSelect(item.name)}
                  onDoubleClick={() => handleItemDoubleClick(item)}
                  onContextMenu={(e) => handleContextMenu(e, item)}
                >
                  <Checkbox
                    edge="start"
                    checked={selectedItems.includes(item.name)}
                    tabIndex={-1}
                    disableRipple
                    onChange={() => handleSelect(item.name)}
                  />
                  <ListItemIcon>
                    {item.isDirectory ? <FolderIcon /> : <FileIcon />}
                  </ListItemIcon>
                  <ListItemText primary={item.name} />
                  <ListItemText
                    primary={item.size ? `${item.size} KB` : "--"}
                    sx={{ textAlign: "right" }}
                  />
                  <ListItemText
                    primary={item.isDirectory ? "Folder" : "File"}
                    sx={{ textAlign: "right" }}
                  />
                  <ListItemText
                    primary={item.modified || "--"}
                    sx={{ textAlign: "right" }}
                  />
                </ListItem>
              ))}
              {items.length === 0 && (
                <Typography variant="body1">This folder is empty.</Typography>
              )}
            </List>
          )}
        </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>

      {/* Confirmation Dialog for Deletion */}
      {/* Optional: Implement a separate confirmation dialog if you want more control */}

      {/* 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")}>
          <ListItemIcon>
            <FolderIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Open</ListItemText>
        </MenuItem>
        <MenuItem onClick={() => handleContextAction("copy")}>
          <ListItemIcon>
            <FileCopyIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Copy</ListItemText>
        </MenuItem>
        <MenuItem onClick={() => handleContextAction("delete")}>
          <ListItemIcon>
            <DeleteIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Delete</ListItemText>
        </MenuItem>
        <MenuItem onClick={() => handleContextAction("rename")}>
          <ListItemIcon>
            <MoreVertIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Rename</ListItemText>
        </MenuItem>
      </Menu>
    </Box>
  );
};

export default WindowsFileManager;

make it so that there are no checkboxes, and use shift to select in a group and ctrl to select individually, enable drag and drop to folders, and fix the metadata system not being properly aligned