import React, { useContext, useEffect, useState } from "react";
import {
  Grid,
  Card,
  Chip,
  Divider,
  Box,
  Typography,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  Button,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Skeleton,
} 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 { getUserRoleInfo } from "../features/authentication/services/getUserRoleInfo";
import { AppContext } from "../contexts/AppContext";
import { getLiveStockItems } from "../utils/getLivestock";
import {
  getBarSquareRoles,
  getLiveStockRoles,
  getPoultryRoles,
  getUserTypeOfActivity,
} from "../utils/getUserTypeOfActivity";

import {
  SET_SELECTED_ROLE,
  SET_SELECTED_SUB_USER,
  SET_SUB_USERS,
} 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 FolderOffIcon from "@mui/icons-material/FolderOff";
import { SlaughterBalanceStatusButton } from "../features/slaughter-house/components/slaughter-balance-status-button/SlaughterBalanceStatusButton";

const AccessDashboardV2 = () => {
  const [openNotif] = useContext(AppContext);
  const navigate = useNavigate();
  const userRoles = useSelector((state) => state.userSlice.role);
  const {
    typeActivitySelected,
    selectedRole,
    userProfile,
    loginUserProfile,
    subUsers: reduxSubUsers,
    selectedSubUser: reduxSelectedSubUser,
  } = useSelector((state) => state.userSlice);
  const dispatch = useDispatch();

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

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

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

  const [roleSelectionModalOpen, setRoleSelectionModalOpen] = useState(false);
  const [selectedRoleLocal, setSelectedRoleLocal] = useState(selectedRole);
  const [subUsers, setSubUsers] = useState([]);
  const [selectedSubUser, setSelectedSubUser] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

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

  useEffect(() => {
    if (userRoles && userRoles.length > 0 && !selectedRole) {
      if (userRoles.length === 1) {
        const role = userRoles[0];
        dispatch(SET_SELECTED_ROLE(role));
        setSelectedRoleLocal(role);
        setRoleSelectionModalOpen(false);

        const rolesNeedingSubUsers = ["Steward", "KillHouse", "Guilds"];
        if (rolesNeedingSubUsers.includes(role)) {
          const userKey = userProfile?.key || loginUserProfile?.key;
          if (userKey && role) {
            dispatch(getUserRoleInfo({ userKey, role })).catch((error) => {
              console.error("Error fetching user role info:", error);
            });
          }
        }
      } else {
        setRoleSelectionModalOpen(true);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userRoles, selectedRole]);

  useEffect(() => {
    if (selectedRole) {
      const rolesNeedingSubUsers = ["Steward", "KillHouse", "Guilds"];
      if (rolesNeedingSubUsers.includes(selectedRole)) {
        if (reduxSubUsers && reduxSubUsers.length > 0) {
          const subUsersKeys = subUsers.map((u) => u?.key).join(",");
          const reduxSubUsersKeys = reduxSubUsers.map((u) => u?.key).join(",");
          if (subUsersKeys !== reduxSubUsersKeys) {
            setSubUsers(reduxSubUsers);
          }

          if (reduxSelectedSubUser) {
            if (selectedSubUser?.key !== reduxSelectedSubUser?.key) {
              setSelectedSubUser(reduxSelectedSubUser);
            }
          } else if (reduxSubUsers.length > 0) {
            const firstSubUser = reduxSubUsers[0];
            if (selectedSubUser?.key !== firstSubUser?.key) {
              setSelectedSubUser(firstSubUser);
              dispatch(SET_SELECTED_SUB_USER(firstSubUser));
            }
          }
          setIsLoading(false);
        } else {
          if (subUsers.length > 0 || selectedSubUser) {
            setSubUsers([]);
            setSelectedSubUser(null);
          }
          setIsLoading(true);
        }
      } else {
        if (subUsers.length > 0 || selectedSubUser) {
          setSubUsers([]);
          setSelectedSubUser(null);
          dispatch(SET_SUB_USERS([]));
        }
        setIsLoading(false);
      }
    } else {
      if (subUsers.length > 0 || selectedSubUser) {
        setSubUsers([]);
        setSelectedSubUser(null);
        dispatch(SET_SUB_USERS([]));
      }
      setIsLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedRole, reduxSubUsers, reduxSelectedSubUser]);

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

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

  const handleRoleSelection = async (role) => {
    setSelectedRoleLocal(role);
    dispatch(SET_SELECTED_ROLE(role));
    setRoleSelectionModalOpen(false);

    setSubUsers([]);
    setSelectedSubUser(null);
    dispatch(SET_SUB_USERS([]));

    const rolesNeedingSubUsers = ["Steward", "KillHouse", "Guilds"];
    if (rolesNeedingSubUsers.includes(role)) {
      setIsLoading(true);
      const userKey = userProfile?.key || loginUserProfile?.key;
      if (userKey && role) {
        try {
          await dispatch(getUserRoleInfo({ userKey, role })).unwrap();
        } catch (error) {
          console.error("Error fetching user role info:", error);
          setIsLoading(false);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "خطا در دریافت اطلاعات نقش کاربر",
            severity: "error",
          });
        }
      } else {
        setIsLoading(false);
      }
    }
  };

  const handleSubUserChange = (event) => {
    const subUserKey = event.target.value;
    const subUser = subUsers.find((u) => u.key === subUserKey);
    setSelectedSubUser(subUser);
    dispatch(SET_SELECTED_SUB_USER(subUser));

    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
    }, 1000);
  };

  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);
  };

  function renderSkeletonCards(count = 6) {
    return (
      <Grid container spacing={{ xs: 1, sm: 3 }} justifyContent="center">
        {Array.from({ length: count }).map((_, i) => (
          <Grid item key={i} xs={12} lg={10}>
            <Card
              elevation={2}
              sx={{
                p: { xs: 1, sm: 2 },
                borderRadius: "12px",
                backgroundColor: "#fff",
                boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
              }}
            >
              <Skeleton variant="rectangular" height={40} sx={{ mb: 2 }} />
              <Grid
                container
                spacing={{ xs: 2, sm: 2 }}
                justifyContent="center"
                pt={1}
              >
                {Array.from({ length: 6 }).map((_, idx) => (
                  <Grid item key={idx} xs={4} sm={3} md={3} lg={4}>
                    <Skeleton
                      variant="rectangular"
                      sx={{
                        width: "100%",
                        aspectRatio: "1/1",
                        borderRadius: "8px",
                      }}
                    />
                  </Grid>
                ))}
              </Grid>
            </Card>
          </Grid>
        ))}
      </Grid>
    );
  }

  const renderContent = () => {
    if (!selectedRole) {
      return null;
    }

    const filteredRoles =
      userRoles?.filter((role) => role === selectedRole) || [];

    if (selected === "Poultry") {
      return renderPoultrySection(filteredRoles);
    }
    if (selected === "Livestock") {
      return renderLivestockSection(filteredRoles);
    }
    return renderBarSquareSection(filteredRoles);
  };

  const sortRolesByPriority = (roles) => {
    const priorityOrder = [
      "SuperAdmin",
      "AdminX",
      "Admin",
      "ProvinceOperator",
      "ProvincialGovernment",
      "Jahad",
      "LiveStockProvinceJahad",
      "CityJahad",
      "ProvinceFinancial",
      "Commerce",
      "CityCommerce",
      "KillHouse",
      "Guilds",
      "Steward",
      "ColdHouseSteward",
      "GuildRoom",
      "CityGuild",
      "VetSupervisor",
      "KillHouseVet",
      "VetFarm",
      "CityVet",
      "ParentCompany",
      "ChainCompany",
      "PosCompany",
      "ProvinceSupervisor",
      "ProvinceInspector",
      "Observatory",
      "CityOperator",
      "CityPoultry",
      "UnitWindow",
      "Union",
      "Cooperative",
      "Rancher",
      "LiveStockSupport",
      "Poultry",
      "PoultryScience",
      "Dispenser",
      "Supporter",
      "Driver",
    ];

    return [...roles].sort((a, b) => {
      const aIndex = priorityOrder.indexOf(a);
      const bIndex = priorityOrder.indexOf(b);
      if (aIndex !== -1 && bIndex !== -1) {
        return aIndex - bIndex;
      }
      if (aIndex !== -1) return -1;
      if (bIndex !== -1) return 1;
      return a.localeCompare(b);
    });
  };

  const getRolePageCount = (role) => {
    const roleItems = getRoleItems(role) || [];
    const liveStockItems = getLiveStockItems(role) || [];
    return roleItems.length + liveStockItems.length;
  };

  const availableRoles = userRoles ? sortRolesByPriority(userRoles) : [];

  return (
    <>
      {availableRoles.length > 1 && (
        <Dialog
          open={roleSelectionModalOpen}
          onClose={() => {}}
          disableEscapeKeyDown
          PaperProps={{
            sx: {
              width: "670px",
              maxWidth: "90vw",
            },
          }}
        >
          <DialogTitle>انتخاب نقش کاربر</DialogTitle>
          <DialogContent>
            <Typography variant="body2" sx={{ mb: 3, textAlign: "center" }}>
              لطفاً نقش خود را انتخاب کنید:
            </Typography>
            <Grid container spacing={2} sx={{ minHeight: "200px" }}>
              {availableRoles.map((role) => (
                <Grid item xs={6} sm={4} md={3} key={role}>
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "center",
                      alignItems: "center",
                    }}
                  >
                    <Button
                      variant={
                        selectedRoleLocal === role ? "contained" : "outlined"
                      }
                      onClick={() => handleRoleSelection(role)}
                      sx={{
                        width: { xs: "100px", sm: "120px", md: "140px" },
                        height: { xs: "100px", sm: "120px", md: "140px" },
                        borderRadius: "16px",
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                        justifyContent: "center",
                        fontSize: {
                          xs: "0.7rem",
                          sm: "0.75rem",
                          md: "0.85rem",
                        },
                        fontWeight: "bold",
                        textTransform: "none",
                        borderWidth: selectedRoleLocal === role ? 0 : 2,
                        "&:hover": {
                          transform: "scale(1.05)",
                          transition: "transform 0.2s ease-in-out",
                        },
                      }}
                      size="small"
                    >
                      {getFaUserRole(role)}
                    </Button>
                  </Box>
                </Grid>
              ))}
            </Grid>
          </DialogContent>
        </Dialog>
      )}

      <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
          justifyContent="space-between"
          alignItems="center"
          mb={2}
          mt={2}
          gap={1}
          px={1}
        >
          <Box display="flex" alignItems="center" gap={1} flexDirection="row">
            {availableRoles.length > 1 && (
              <FormControl
                size="small"
                sx={{
                  width: { xs: 150, sm: 200 },
                  backgroundColor: "white",
                  borderRadius: 1,
                  "& .MuiOutlinedInput-root": {
                    height: {
                      xs: "38px",
                      lg: "48px",
                    },
                    backgroundColor: "white",
                  },
                }}
              >
                <InputLabel>نقش</InputLabel>
                <Select
                  value={selectedRole || ""}
                  label="نقش"
                  onChange={async (e) => {
                    const role = e.target.value;
                    setSelectedRoleLocal(role);
                    dispatch(SET_SELECTED_ROLE(role));

                    setSubUsers([]);
                    setSelectedSubUser(null);
                    dispatch(SET_SUB_USERS([]));

                    const rolesNeedingSubUsers = [
                      "Steward",
                      "KillHouse",
                      "Guilds",
                    ];
                    if (rolesNeedingSubUsers.includes(role)) {
                      setIsLoading(true);
                      const userKey = userProfile?.key || loginUserProfile?.key;
                      if (userKey && role) {
                        try {
                          await dispatch(
                            getUserRoleInfo({ userKey, role })
                          ).unwrap();
                        } catch (error) {
                          console.error(
                            "Error fetching user role info:",
                            error
                          );
                          setIsLoading(false);
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "خطا در دریافت اطلاعات نقش کاربر",
                            severity: "error",
                          });
                        }
                      } else {
                        setIsLoading(false);
                      }
                    }
                  }}
                  renderValue={(value) => getFaUserRole(value)}
                >
                  {availableRoles.map((role) => {
                    const pageCount = getRolePageCount(role);
                    return (
                      <MenuItem key={role} value={role}>
                        <Box
                          sx={{
                            display: "flex",
                            justifyContent: "space-between",
                            alignItems: "center",
                            width: "100%",
                          }}
                        >
                          <Typography>{getFaUserRole(role)}</Typography>
                          <Typography
                            variant="caption"
                            sx={{
                              color: "text.secondary",
                              ml: 1,
                            }}
                          >
                            ({pageCount})
                          </Typography>
                        </Box>
                      </MenuItem>
                    );
                  })}
                </Select>
              </FormControl>
            )}

            {subUsers.length > 1 && (
              <FormControl
                size="small"
                sx={{
                  width: { xs: 150, sm: 200 },
                  backgroundColor: "white",
                  borderRadius: 1,
                  "& .MuiOutlinedInput-root": {
                    height: {
                      xs: "38px",
                      lg: "48px",
                    },
                    backgroundColor: "white",
                  },
                }}
              >
                <InputLabel>
                  {selectedRole === "Steward"
                    ? "مباشر"
                    : selectedRole === "Guilds"
                    ? "صنف"
                    : "کشتارگاه"}
                </InputLabel>
                <Select
                  value={selectedSubUser?.key || ""}
                  label="کاربر فرعی"
                  onChange={handleSubUserChange}
                >
                  {subUsers.map((user) => (
                    <MenuItem key={user.key} value={user.key}>
                      {user.unit}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            )}
          </Box>
          {userRoles && userRoles.includes("KillHouse") && (
            <SlaughterBalanceStatusButton />
          )}
        </Grid>
        <Grid container justifyContent="center" alignItems="center">
          {renderContent()}
        </Grid>
      </Box>
    </>
  );

  function renderPoultrySection(filteredRoles = userRoles) {
    const poultryRoles = getPoultryRoles(filteredRoles);
    if (isLoading) {
      return renderSkeletonCards(poultryRoles?.length || 1);
    }

    if (!poultryRoles || poultryRoles.length === 0) {
      return (
        <Grid container justifyContent="center" alignItems="center">
          <Card
            elevation={2}
            sx={{
              p: { xs: 4, sm: 6 },
              borderRadius: "12px",
              backgroundColor: "#fff",
              boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
              width: "100%",
              minHeight: { xs: "300px", sm: "400px" },
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
              gap: 2,
            }}
          >
            <FolderOffIcon
              sx={{
                fontSize: { xs: "4rem", sm: "5rem" },
                color: "text.secondary",
              }}
            />
            <Typography variant="h6" color="text.secondary">
              هیچ دسترسی برای این نقش وجود ندارد
            </Typography>
          </Card>
        </Grid>
      );
    }

    return (
      <Grid container spacing={{ xs: 1, sm: 3 }} justifyContent="center">
        {sortRoles(poultryRoles)?.map((item, i) => (
          <Grid item xs={12} lg={poultryRoles?.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={poultryRoles?.length === 1 ? 1.7 : 4}
                      nlg={poultryRoles?.length === 1 ? 1.3 : 3}
                      xl={poultryRoles?.length === 1 ? 1.2 : 3}
                      nxl={poultryRoles?.length === 1 ? 1 : 2.3}
                      xxl={poultryRoles?.length === 1 ? 1.15 : 2.3}
                      xxxl={poultryRoles?.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(filteredRoles = userRoles) {
    const livestockRoles = getLiveStockRoles(filteredRoles);
    if (isLoading) {
      return renderSkeletonCards(livestockRoles?.length || 1);
    }

    if (!livestockRoles || livestockRoles.length === 0) {
      return (
        <Grid container justifyContent="center" alignItems="center">
          <Card
            elevation={2}
            sx={{
              p: { xs: 4, sm: 6 },
              borderRadius: "12px",
              backgroundColor: "#fff",
              boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
              width: "100%",
              minHeight: { xs: "300px", sm: "400px" },
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
              gap: 2,
            }}
          >
            <FolderOffIcon
              sx={{
                fontSize: { xs: "4rem", sm: "5rem" },
                color: "text.secondary",
              }}
            />
            <Typography variant="h6" color="text.secondary">
              هیچ صفحه‌ای برای این نقش وجود ندارد
            </Typography>
          </Card>
        </Grid>
      );
    }

    return (
      <Grid container spacing={{ xs: 1, sm: 3 }} justifyContent="center">
        {sortRoles(livestockRoles)?.map((item, i) => (
          <Grid
            item
            xs={12}
            sm={12}
            lg={livestockRoles?.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={livestockRoles?.length === 1 ? 1.7 : 4}
                      nlg={livestockRoles?.length === 1 ? 1.3 : 3}
                      xl={livestockRoles?.length === 1 ? 1.2 : 3}
                      nxl={livestockRoles?.length === 1 ? 1 : 2.3}
                      xxl={livestockRoles?.length === 1 ? 1.15 : 2.3}
                      xxxl={livestockRoles?.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(filteredRoles = userRoles) {
    const barSquareRoles = getBarSquareRoles(filteredRoles);
    if (isLoading) {
      return renderSkeletonCards(barSquareRoles?.length || 1);
    }

    if (!barSquareRoles || barSquareRoles.length === 0) {
      return (
        <Grid container justifyContent="center" alignItems="center">
          <Card
            elevation={2}
            sx={{
              p: { xs: 4, sm: 6 },
              borderRadius: "12px",
              backgroundColor: "#fff",
              boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
              width: "100%",
              minHeight: { xs: "300px", sm: "400px" },
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
              gap: 2,
            }}
          >
            <FolderOffIcon
              sx={{
                fontSize: { xs: "4rem", sm: "5rem" },
                color: "text.secondary",
              }}
            />
            <Typography variant="h6" color="text.secondary">
              هیچ صفحه‌ای برای این نقش وجود ندارد
            </Typography>
          </Card>
        </Grid>
      );
    }

    return (
      <Grid container spacing={{ xs: 1, sm: 3 }} justifyContent="center">
        {sortRoles(barSquareRoles)?.map((item, i) => (
          <Grid item xs={12} lg={barSquareRoles?.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 AccessDashboardV2;
