import React, { useContext, useEffect, useState } from "react";
import {
  Grid,
  Card,
  Chip,
  Divider,
  Box,
  Typography,
  Autocomplete,
  TextField,
  IconButton,
  Tooltip,
  // ToggleButton,
  // ToggleButtonGroup,
} from "@mui/material";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { getRoleItems } from "../utils/getRolesItems";
import { getFaUserRole } from "../utils/getFaUserRole";
import { sortRoles } from "../utils/sortRoles";
import { getUserProfile } from "../features/authentication/services/getUserProfile";
import { AppContext } from "../contexts/AppContext";
import { getLiveStockItems } from "../utils/getLivestock";
import {
  getBarSquareRoles,
  getLiveStockRoles,
  getPoultryRoles,
  getUserTypeOfActivity,
} from "../utils/getUserTypeOfActivity";
// import poultry from "../assets/images/poultry.png";
// import livestock from "../assets/images/livestock.png";
// import livestockColor from "../assets/images/livestockColor.png";
// import poultryColor from "../assets/images/poultryColor.png";
// import barSquare from "../assets/images/barSquare.png";
// import barSquareColor from "../assets/images/barSquareColor.png";

// import { SET_TYPE_ACTIVITY_SELECTED } from "../lib/redux/slices/userSlice";
import { getBarSquareItems } from "../utils/getBarSquareItems";
import { trackItemClick } from "../utils/usageTracker";
import {
  applyCustomOrder,
  saveRoleCustomOrder,
  reorderArray,
} from "../utils/dashboardCustomization";
import EditIcon from "@mui/icons-material/Edit";
import SaveIcon from "@mui/icons-material/Save";
import { Check, OpenWith } from "@mui/icons-material";
import { SlaughterBalanceStatusButton } from "../features/slaughter-house/components/slaughter-balance-status-button/SlaughterBalanceStatusButton";

// Function to convert numbers to Persian numerals

const AccessDashboard = () => {
  const [openNotif] = useContext(AppContext);
  const navigate = useNavigate();
  const userRoles = useSelector((state) => state.userSlice.role);
  // const userInfo = useSelector(
  //   (state) => state.userSlice.loginUserProfile.mobile
  // );
  const { typeActivitySelected } = useSelector((state) => state.userSlice);
  const dispatch = useDispatch();
  const [autocompleteValue, setAutocompleteValue] = React.useState(null);

  const [editModes, setEditModes] = useState({});

  const [draggedItems, setDraggedItems] = useState({});

  const [draggingCardIndex, setDraggingCardIndex] = useState(null);

  useEffect(() => {
    dispatch(getUserProfile());
  }, []);

  const getInitialSelection = () => {
    if (typeActivitySelected) {
      return typeActivitySelected;
    }
    if (getUserTypeOfActivity(userRoles) === "LiveStock") {
      return "Livestock";
    }
    return "Poultry";
  };

  const [selected] = useState(getInitialSelection());

  // const handleSelection = (event, newSelection) => {
  //   if (newSelection !== null) {
  //     setSelected(newSelection);
  //     dispatch(SET_TYPE_ACTIVITY_SELECTED(newSelection));
  //   }
  // };

  const autocompleteItems = [];
  if (userRoles) {
    for (const role of userRoles) {
      const items = getRoleItems(role);
      items.forEach((item) => {
        autocompleteItems.push({ ...item, role });
      });

      const liveStockItems = getLiveStockItems(role);
      liveStockItems.forEach((item) => {
        autocompleteItems.push({ ...item, role });
      });
    }
  }

  const handleAutocompleteChange = (event, value) => {
    setAutocompleteValue(null);
    if (value?.route) {
      trackItemClick(value.role, value.route);
      setTimeout(() => navigate(value.route), 0);
    }
  };

  const handleCardClick = (roleItem, role) => {
    if (editModes[role]) return;

    if (roleItem?.disabled) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: roleItem.disabledText || "این بخش در دست توسعه است !",
        severity: "error",
      });
    } else {
      trackItemClick(role, roleItem.route);
      navigate(roleItem.route);
    }
  };

  const toggleEditMode = (role, items) => {
    const isEnteringEditMode = !editModes[role];

    if (isEnteringEditMode) {
      setEditModes({ ...editModes, [role]: true });
      setDraggedItems({ ...draggedItems, [role]: items });
    } else {
      saveRoleCustomOrder(role, draggedItems[role]);
      setEditModes({ ...editModes, [role]: false });
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "ترتیب کارت‌ها ذخیره شد",
        severity: "success",
      });
    }
  };

  const handleCardMouseDown = (index) => {
    setDraggingCardIndex(index);
  };

  const handleCardMouseUp = () => {
    setDraggingCardIndex(null);
  };

  const handleDragStart = (e, index) => {
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/html", index);
    setDraggingCardIndex(index);
  };

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

  const handleDrop = (e, role, dropIndex) => {
    e.preventDefault();
    const dragIndex = parseInt(e.dataTransfer.getData("text/html"));

    if (dragIndex === dropIndex) return;

    const currentItems = draggedItems[role] || [];
    const reorderedItems = reorderArray(currentItems, dragIndex, dropIndex);

    setDraggedItems({ ...draggedItems, [role]: reorderedItems });
  };

  const handleDragEnd = () => {
    setDraggingCardIndex(null);
  };

  const getItemsForRole = (items, role) => {
    if (editModes[role] && draggedItems[role]) {
      return draggedItems[role];
    }

    return applyCustomOrder(items, role);
  };

  const renderContent = () => {
    if (selected === "Poultry") {
      return renderPoultrySection();
    }
    if (selected === "Livestock") {
      return renderLivestockSection();
    }
    return renderBarSquareSection();
  };

  return (
    <>
      {}
      <style>
        {`
          @keyframes wiggle {
            0% { transform: rotate(0deg); }
            25% { transform: rotate(-1deg); }
            50% { transform: rotate(1.5deg); }
            75% { transform: rotate(-1.5deg); }
            100% { transform: rotate(0deg); }
          }
          
          .wiggle-animation {
            animation: wiggle 0.25s ease-in-out infinite;
          }
          
          .no-wiggle {
            animation: none !important;
          }
        `}
      </style>
      <Box
        sx={{
          backgroundColor: "#f9f9f9",
          minHeight: "auto",
          p: { xs: 2, sm: 3 },
          borderRadius: "20px",
          width: "100%",
          maxWidth: { xs: "100%", sm: "100%" },
          overflowX: "hidden",
          position: "relative",
        }}
      >
        <Grid
          container
          xs={12}
          justifyContent="space-between"
          alignItems="center"
          mb={2}
          mt={2}
          gap={1}
          px={1}
        >
          <Autocomplete
            sx={{
              width: { xs: 180, sm: 260 },
              "& .MuiOutlinedInput-root": {
                height: {
                  xs: "38px",
                  lg: "48px",
                },
              },
            }}
            size="small"
            options={autocompleteItems.map((item, index) => ({
              label: item.text,
              route: item.route,
              role: item.role,
              disabled: item.disabled || false,
              index,
            }))}
            groupBy={(option) =>
              userRoles?.length !== 1 ? getFaUserRole(option.role) : false
            }
            getOptionDisabled={(option) => option.disabled}
            getOptionLabel={(option) => option.label || ""}
            value={autocompleteValue}
            onChange={handleAutocompleteChange}
            onClose={() => setAutocompleteValue(null)}
            renderInput={(params) => (
              <TextField {...params} placeholder="جستجو ..." />
            )}
            renderOption={(props, option) => (
              <Typography
                color="primary"
                {...props}
                sx={{
                  fontSize: 14,
                  fontWeight: "700",
                }}
              >
                {option.label}
              </Typography>
            )}
            style={{
              backgroundColor: "white",
              borderRadius: 4,
            }}
          />
          {userRoles && userRoles.includes("KillHouse") && (
            <SlaughterBalanceStatusButton />
          )}
          {/* <Grid container xs={12} justifyContent="center">
          {getUserTypeOfActivity(userRoles) === "Both" && (
            <Grid gap={1} alignItems="center" container justifyContent="center">
              <ToggleButtonGroup
                value={selected}
                exclusive
                onChange={handleSelection}
                aria-label="Animal selection"
                sx={{
                  display: "flex",
                  justifyContent: "center",
                  flexDirection: { xs: "row" },
                  "& .MuiToggleButton-root": {
                    borderRadius: "8px",
                    fontWeight: "bold",
                    fontSize: { xs: "14px", sm: "18px" },
                    color: "gray",
                    backgroundColor: "#EAEFFF",
                    transition: "all 0.3s ease",
                    "&.Mui-selected": {
                      backgroundColor: "#2D5FFF",
                      color: "#FFFFFF",
                      boxShadow: "0 4px 6px rgba(0,0,0,0.1)",
                      "&:hover": {
                        backgroundColor: "#2D5FFF",
                        color: "#FFFFFF",
                      },
                    },
                    "&:hover": {
                      backgroundColor: "#1446E5",
                      color: "#fff",
                    },
                  },
                }}
              >
                <ToggleButton
                  value="Poultry"
                  aria-label="Poultry"
                  sx={{
                    width: { xs: "110px", sm: "222px" },
                    border: "2px",
                    outline: "none",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: "8px",
                  }}
                >
                  <img
                    style={{ width: "24px" }}
                    src={selected === "Poultry" ? livestock : livestockColor}
                    alt="poultry"
                  />
                  طیور
                </ToggleButton>

                <ToggleButton
                  value="Livestock"
                  aria-label="Livestock"
                  sx={{
                    width: { xs: "110px", sm: "222px" },
                    border: "2px",
                    outline: "none",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: "8px",
                  }}
                >
                  <img
                    style={{ width: "24px" }}
                    src={selected === "Livestock" ? poultryColor : poultry}
                    alt="livestock"
                  />
                  دام
                </ToggleButton>
                {userInfo === "09011110911" && (
                  <ToggleButton
                    value="barSquare"
                    aria-label="Livestock"
                    sx={{
                      width: { xs: "110px", sm: "222px" },
                      border: "2px",
                      outline: "none",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: "8px",
                    }}
                  >
                    <img
                      style={{ width: "24px" }}
                      src={
                        selected === "barSquare" ? barSquare : barSquareColor
                      }
                      alt="barSquare"
                    />
                    میدان بار
                  </ToggleButton>
                )}
              </ToggleButtonGroup>
            </Grid>
          )}
        </Grid> */}
        </Grid>
        <Grid container xs={12} justifyContent="center" alignItems="center">
          {renderContent()}
        </Grid>
      </Box>
    </>
  );

  function renderPoultrySection() {
    return (
      <Grid
        container
        spacing={{ xs: 1, sm: 3 }}
        justifyContent="center"
        xs={12}
      >
        {sortRoles(getPoultryRoles(userRoles))?.map((item, i) => (
          <Grid
            item
            xs={12}
            sm={12}
            lg={getPoultryRoles(userRoles)?.length === 1 ? 12 : 6}
            key={i}
          >
            <Card
              elevation={2}
              sx={{
                p: { xs: 1, sm: 2 },
                borderRadius: "12px",
                backgroundColor: "#fff",
                boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
                position: "relative",
              }}
            >
              <Box sx={{ position: "relative" }}>
                <Tooltip
                  title={
                    editModes[item]
                      ? "ذخیره ترتیب"
                      : "ویرایش و تغییر ترتیب کارت‌ها"
                  }
                >
                  <IconButton
                    onClick={() =>
                      toggleEditMode(
                        item,
                        getItemsForRole(getRoleItems(item), item)
                      )
                    }
                    sx={{
                      position: "absolute",
                      top: 2,
                      right: 0,
                      zIndex: 10,
                      backgroundColor: editModes[item]
                        ? "success.main"
                        : "primary.main",
                      color: "white",
                      "&:hover": {
                        backgroundColor: editModes[item]
                          ? "success.dark"
                          : "primary.dark",
                      },
                      width: 24,
                      height: 24,
                    }}
                    size="small"
                  >
                    {editModes[item] ? (
                      <Check sx={{ fontSize: "14px" }} />
                    ) : (
                      <EditIcon sx={{ fontSize: "14px" }} />
                    )}
                  </IconButton>
                </Tooltip>
              </Box>

              <Divider sx={{ mb: 1.5 }}>
                <Chip
                  label={getFaUserRole(item)}
                  color="primary"
                  sx={{
                    fontSize: "0.85rem",
                    fontWeight: "bold",
                    backgroundColor: "primary",
                  }}
                />
              </Divider>

              <Grid
                container
                spacing={{ xs: 2, sm: 2 }}
                justifyContent="center"
                pt={1}
              >
                {getItemsForRole(getRoleItems(item), item)?.map(
                  (roleItem, index) => (
                    <Grid
                      item
                      key={index}
                      xs={4}
                      sm={3}
                      md={3}
                      lg={getPoultryRoles(userRoles)?.length === 1 ? 1.7 : 4}
                      nlg={getPoultryRoles(userRoles)?.length === 1 ? 1.3 : 3}
                      xl={getPoultryRoles(userRoles)?.length === 1 ? 1.2 : 3}
                      nxl={getPoultryRoles(userRoles)?.length === 1 ? 1 : 2.3}
                      xxl={
                        getPoultryRoles(userRoles)?.length === 1 ? 1.15 : 2.3
                      }
                      xxxl={getPoultryRoles(userRoles)?.length === 1 ? 1 : 2.3}
                      sx={{
                        display: "flex",
                        justifyContent: "center",
                      }}
                      gap={5}
                    >
                      <Card
                        elevation={2}
                        draggable={editModes[item]}
                        className={
                          editModes[item] && draggingCardIndex !== index
                            ? "wiggle-animation"
                            : ""
                        }
                        onDragStart={(e) =>
                          editModes[item] && handleDragStart(e, index)
                        }
                        onDragEnd={handleDragEnd}
                        onDragOver={(e) => editModes[item] && handleDragOver(e)}
                        onDrop={(e) =>
                          editModes[item] && handleDrop(e, item, index)
                        }
                        onMouseDown={() =>
                          editModes[item] && handleCardMouseDown(index)
                        }
                        onMouseUp={handleCardMouseUp}
                        onTouchStart={() =>
                          editModes[item] && handleCardMouseDown(index)
                        }
                        onTouchEnd={handleCardMouseUp}
                        sx={{
                          width: "100%",
                          aspectRatio: "1/1",
                          borderRadius: "8px",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          textAlign: "center",
                          cursor: editModes[item] ? "move" : "pointer",
                          transition:
                            "transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out",
                          position: "relative",
                          backgroundSize: "cover",
                          backgroundPosition: "center",
                          color: (theme) => theme.palette.primary.main,
                          borderStyle: "solid",
                          borderWidth: "1px",
                          borderColor: (theme) => theme.palette.primary.main,
                          opacity: editModes[item] ? 0.9 : 1,
                          "&:hover": {
                            transform: editModes[item]
                              ? "scale(1.02)"
                              : "scale(1.05)",
                            boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
                            backgroundColor: (theme) =>
                              theme.palette.primary.light,
                          },
                        }}
                        onClick={() => handleCardClick(roleItem, item)}
                      >
                        {}
                        {editModes[item] && (
                          <Box
                            sx={{
                              position: "absolute",
                              top: 2,
                              right: 2,
                              backgroundColor: "rgba(0, 0, 0, 0.5)",
                              borderRadius: "50%",
                              width: 18,
                              height: 18,
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              zIndex: 1,
                            }}
                          >
                            <OpenWith
                              sx={{
                                fontSize: 12,
                                color: "white",
                              }}
                            />
                          </Box>
                        )}
                        <Box>
                          {roleItem.icon && (
                            <Box sx={{ mb: 0.5 }}>
                              {React.cloneElement(roleItem.icon, {
                                sx: {
                                  fontSize: {
                                    xs: "2rem",
                                    sm: "2.5rem",
                                    xxl: "2.8rem",
                                    xxxl: "3.2rem",
                                  },
                                },
                              })}
                            </Box>
                          )}
                          <Typography
                            variant="caption"
                            fontWeight="bold"
                            sx={{
                              fontSize: {
                                xs: "0.55rem",
                                sm: "0.65rem",
                                xxl: "0.80rem",
                                xxxl: "0.95rem",
                              },
                              color: (theme) => theme.palette.primary.dark,
                            }}
                          >
                            {roleItem.text}
                          </Typography>
                        </Box>
                      </Card>
                    </Grid>
                  )
                )}
              </Grid>
            </Card>
          </Grid>
        ))}
      </Grid>
    );
  }

  function renderLivestockSection() {
    return (
      <Grid
        container
        spacing={{ xs: 1, sm: 3 }}
        justifyContent="center"
        xs={12}
      >
        {sortRoles(getLiveStockRoles(userRoles))?.map((item, i) => (
          <Grid
            item
            xs={12}
            sm={12}
            lg={getLiveStockRoles(userRoles)?.length === 1 ? 12 : 6}
            key={i}
          >
            <Card
              elevation={2}
              sx={{
                p: { xs: 1, sm: 2 },
                borderRadius: "12px",
                backgroundColor: "#fff",
                boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
                position: "relative",
              }}
            >
              <Box sx={{ position: "relative" }}>
                <Tooltip
                  title={
                    editModes[item]
                      ? "ذخیره ترتیب"
                      : "ویرایش و تغییر ترتیب کارت‌ها"
                  }
                >
                  <IconButton
                    onClick={() =>
                      toggleEditMode(
                        item,
                        getItemsForRole(getLiveStockItems(item), item)
                      )
                    }
                    sx={{
                      position: "absolute",
                      top: -8,
                      right: 8,
                      zIndex: 10,
                      backgroundColor: editModes[item]
                        ? "success.main"
                        : "primary.main",
                      color: "white",
                      "&:hover": {
                        backgroundColor: editModes[item]
                          ? "success.dark"
                          : "primary.dark",
                      },
                      width: 32,
                      height: 32,
                    }}
                    size="small"
                  >
                    {editModes[item] ? (
                      <SaveIcon fontSize="small" />
                    ) : (
                      <EditIcon fontSize="small" />
                    )}
                  </IconButton>
                </Tooltip>
              </Box>

              <Divider sx={{ mb: 1.5 }}>
                <Chip
                  label={getFaUserRole(item)}
                  color="primary"
                  sx={{
                    fontSize: "0.85rem",
                    fontWeight: "bold",
                    backgroundColor: "primary",
                  }}
                />
              </Divider>

              <Grid
                container
                spacing={{ xs: 2, sm: 2 }}
                justifyContent="center"
                pt={1}
              >
                {getItemsForRole(getLiveStockItems(item), item)?.map(
                  (roleItem, index) => (
                    <Grid
                      item
                      key={index}
                      xs={4}
                      sm={3}
                      md={3}
                      lg={getLiveStockRoles(userRoles)?.length === 1 ? 1.7 : 4}
                      nlg={getLiveStockRoles(userRoles)?.length === 1 ? 1.3 : 3}
                      xl={getLiveStockRoles(userRoles)?.length === 1 ? 1.2 : 3}
                      nxl={getLiveStockRoles(userRoles)?.length === 1 ? 1 : 2.3}
                      xxl={
                        getLiveStockRoles(userRoles)?.length === 1 ? 1.15 : 2.3
                      }
                      xxxl={
                        getLiveStockRoles(userRoles)?.length === 1 ? 1 : 2.3
                      }
                      sx={{
                        display: "flex",
                        justifyContent: "center",
                      }}
                      gap={5}
                    >
                      <Card
                        elevation={2}
                        draggable={editModes[item]}
                        className={
                          editModes[item] && draggingCardIndex !== index
                            ? "wiggle-animation"
                            : ""
                        }
                        onDragStart={(e) =>
                          editModes[item] && handleDragStart(e, index)
                        }
                        onDragEnd={handleDragEnd}
                        onDragOver={(e) => editModes[item] && handleDragOver(e)}
                        onDrop={(e) =>
                          editModes[item] && handleDrop(e, item, index)
                        }
                        onMouseDown={() =>
                          editModes[item] && handleCardMouseDown(index)
                        }
                        onMouseUp={handleCardMouseUp}
                        onTouchStart={() =>
                          editModes[item] && handleCardMouseDown(index)
                        }
                        onTouchEnd={handleCardMouseUp}
                        sx={{
                          width: "100%",
                          aspectRatio: "1/1",
                          borderRadius: "8px",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          textAlign: "center",
                          cursor: editModes[item] ? "move" : "pointer",
                          transition:
                            "transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out",
                          position: "relative",
                          backgroundSize: "cover",
                          backgroundPosition: "center",
                          color: (theme) => theme.palette.info.main,
                          borderStyle: "solid",
                          borderWidth: "1px",
                          borderColor: (theme) => theme.palette.primary.main,
                          opacity: editModes[item] ? 0.9 : 1,
                          "&:hover": {
                            transform: editModes[item]
                              ? "scale(1.02)"
                              : "scale(1.05)",
                            boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
                            backgroundColor: (theme) =>
                              theme.palette.primary.light,
                          },
                        }}
                        onClick={() => handleCardClick(roleItem, item)}
                      >
                        {}
                        {editModes[item] && (
                          <Box
                            sx={{
                              position: "absolute",
                              top: 2,
                              right: 2,
                              backgroundColor: "rgba(0, 0, 0, 0.5)",
                              borderRadius: "50%",
                              width: 18,
                              height: 18,
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              zIndex: 1,
                            }}
                          >
                            <OpenWith
                              sx={{
                                fontSize: 12,
                                color: "white",
                              }}
                            />
                          </Box>
                        )}
                        <Box>
                          {roleItem.icon && (
                            <Box sx={{ mb: 0.5 }}>
                              {React.cloneElement(roleItem.icon, {
                                sx: {
                                  fontSize: {
                                    xs: "2rem",
                                    sm: "2.5rem",
                                  },
                                },
                              })}
                            </Box>
                          )}
                          <Typography
                            variant="caption"
                            fontWeight="bold"
                            sx={{
                              fontSize: {
                                xs: "0.65rem",
                                sm: "0.65rem",
                                lg: "0.75rem",
                              },
                              color: (theme) => theme.palette.primary.dark,
                            }}
                          >
                            {roleItem.text}
                          </Typography>
                        </Box>
                      </Card>
                    </Grid>
                  )
                )}
              </Grid>
            </Card>
          </Grid>
        ))}
      </Grid>
    );
  }

  function renderBarSquareSection() {
    return (
      <Grid
        container
        spacing={{ xs: 1, sm: 3 }}
        justifyContent="center"
        xs={12}
      >
        {sortRoles(getBarSquareRoles(["BarSquareProvinceJahad"]))?.map(
          (item, i) => (
            <Grid
              item
              xs={12}
              sm={12}
              lg={
                getBarSquareRoles(["BarSquareProvinceJahad"])?.length === 1
                  ? 12
                  : 6
              }
              key={i}
            >
              <Card
                elevation={2}
                sx={{
                  p: { xs: 1, sm: 2 },
                  borderRadius: "12px",
                  backgroundColor: "#fff",
                  boxShadow: "0 2px 6px rgba(238, 25, 25, 0.1)",
                  position: "relative",
                }}
              >
                <Box sx={{ position: "relative" }}>
                  <Tooltip
                    title={
                      editModes[item]
                        ? "ذخیره ترتیب"
                        : "ویرایش و تغییر ترتیب کارت‌ها"
                    }
                  >
                    <IconButton
                      onClick={() =>
                        toggleEditMode(
                          item,
                          getItemsForRole(getBarSquareItems(item), item)
                        )
                      }
                      sx={{
                        position: "absolute",
                        top: -8,
                        right: 8,
                        zIndex: 10,
                        backgroundColor: editModes[item]
                          ? "success.main"
                          : "primary.main",
                        color: "white",
                        "&:hover": {
                          backgroundColor: editModes[item]
                            ? "success.dark"
                            : "primary.dark",
                        },
                        width: 32,
                        height: 32,
                      }}
                      size="small"
                    >
                      {editModes[item] ? (
                        <SaveIcon fontSize="small" />
                      ) : (
                        <EditIcon fontSize="small" />
                      )}
                    </IconButton>
                  </Tooltip>
                </Box>

                <Divider sx={{ mb: 1.5 }}>
                  <Chip
                    label={getFaUserRole(item)}
                    color="primary"
                    sx={{
                      fontSize: "0.85rem",
                      fontWeight: "bold",
                      backgroundColor: "primary",
                    }}
                  />
                </Divider>

                <Grid
                  container
                  spacing={{ xs: 2, sm: 2 }}
                  justifyContent="center"
                  pt={1}
                >
                  {getItemsForRole(getBarSquareItems(item), item)?.map(
                    (roleItem, index) => (
                      <Grid
                        item
                        key={index}
                        xs={4}
                        sm={3}
                        md={3}
                        lg={2}
                        xl={1.4}
                        xxxl={1}
                        sx={{
                          display: "flex",
                          justifyContent: "center",
                        }}
                        gap={5}
                      >
                        <Card
                          elevation={2}
                          draggable={editModes[item]}
                          className={
                            editModes[item] && draggingCardIndex !== index
                              ? "wiggle-animation"
                              : ""
                          }
                          onDragStart={(e) =>
                            editModes[item] && handleDragStart(e, index)
                          }
                          onDragEnd={handleDragEnd}
                          onDragOver={(e) =>
                            editModes[item] && handleDragOver(e)
                          }
                          onDrop={(e) =>
                            editModes[item] && handleDrop(e, item, index)
                          }
                          onMouseDown={() =>
                            editModes[item] && handleCardMouseDown(index)
                          }
                          onMouseUp={handleCardMouseUp}
                          onTouchStart={() =>
                            editModes[item] && handleCardMouseDown(index)
                          }
                          onTouchEnd={handleCardMouseUp}
                          onClick={() => handleCardClick(roleItem, item)}
                          sx={{
                            width: "100%",
                            aspectRatio: "1/1",
                            borderRadius: "8px",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            textAlign: "center",
                            cursor: editModes[item] ? "move" : "pointer",
                            transition:
                              "transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out",
                            position: "relative",
                            backgroundSize: "cover",
                            backgroundPosition: "center",
                            color: "orange",
                            borderStyle: "solid",
                            borderWidth: "1px",
                            borderColor: (theme) => theme.palette.primary.main,
                            opacity: editModes[item] ? 0.9 : 1,
                            "&:hover": {
                              transform: editModes[item]
                                ? "scale(1.02)"
                                : "scale(1.05)",
                              boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
                              backgroundColor: (theme) =>
                                theme.palette.primary.light,
                            },
                          }}
                        >
                          <Box>
                            {roleItem.icon && (
                              <Box sx={{ mb: 0.5 }}>
                                {React.cloneElement(roleItem.icon, {
                                  sx: {
                                    fontSize: {
                                      xs: "2rem",
                                      sm: "2.5rem",
                                      lg: "3rem",
                                    },
                                  },
                                })}
                              </Box>
                            )}
                            <Typography
                              variant="caption"
                              fontWeight="bold"
                              sx={{
                                fontSize: {
                                  xs: "0.65rem",
                                  sm: "0.65rem",
                                  lg: "0.75rem",
                                },
                                color: (theme) => theme.palette.primary.dark,
                              }}
                            >
                              {roleItem.text}
                            </Typography>
                          </Box>
                        </Card>
                      </Grid>
                    )
                  )}
                </Grid>
              </Card>
            </Grid>
          )
        )}
      </Grid>
    );
  }
};

export default AccessDashboard;
