// import React, { useState, useEffect } from 'react';
// import {
//   Box,
//   Button,
//   Container,
//   Typography,
//   TextField,
//   Select,
//   MenuItem,
//   FormControl,
//   InputLabel,
//   Switch,
//   FormControlLabel,
//   Checkbox,
//   IconButton,
//   Table,
//   TableBody,
//   TableCell,
//   TableContainer,
//   TableHead,
//   TableRow,
//   Pagination,
//   Dialog,
//   DialogTitle,
//   DialogContent,
//   DialogActions,
//   Tooltip,
//   Badge,
//   Grid,
//   InputAdornment,
//   Popover,
//   Divider,
//   CircularProgress,
//   Paper
// } from '@mui/material';
// import {
//   Sync as SyncIcon,
//   Add as AddIcon,
//   Menu as MenuIcon,
//   Search as SearchIcon,
//   Close as CloseIcon,
//   Edit as EditIcon,
//   Delete as DeleteIcon,
//   ViewColumn as ViewColumnIcon,
//   FilterList as FilterListIcon,
//   MoreVert as MoreVertIcon
// } from '@mui/icons-material';
// import { styled } from '@mui/material/styles';
// import { getByUsrGrpId } from "../../../ApiServices/MenuAccessControlAPI";
// import { getToken } from "../../../utils/tokenService";
// import { toast } from "react-toastify";

// // Styled components
// const StyledBadge = styled(Badge)(({ theme }) => ({
//   '& .MuiBadge-badge': {
//     backgroundColor: theme.palette.info.main,
//     color: theme.palette.info.contrastText,
//     fontSize: '0.7rem',
//     padding: '5px 10px',
//     borderRadius: '10px'
//   }
// }));

// const StyledTableHead = styled(TableHead)(({ theme }) => ({
//   backgroundColor: theme.palette.primary.main,
//   '& .MuiTableCell-root': {
//     color: theme.palette.primary.contrastText,
//     fontWeight: 'bold'
//   }
// }));

// const StyledTableCell = styled(TableCell)(({ theme }) => ({
//   '&.MuiTableCell-head': {
//     fontWeight: 'bold'
//   }
// }));

// function MenuAccessControl() {
//   // State management
//   const [loading, setLoading] = useState(true);
//   const [menuItems, setMenuItems] = useState([]);
//   const [userGroups, setUserGroups] = useState([]);
//   const [selectedUserGroup, setSelectedUserGroup] = useState(1);
//   const [toggle, setToggle] = useState(false);
//   const [searchQuery, setSearchQuery] = useState('');
//   const [currentPage, setCurrentPage] = useState(1);
//   const [recordsPerPage, setRecordsPerPage] = useState(10);
//   const [editMode, setEditMode] = useState(false);
//   const [selectedMenuItem, setSelectedMenuItem] = useState(null);
//   const [anchorEl, setAnchorEl] = useState(null);
//   const [showAddEditModal, setShowAddEditModal] = useState(false);
//   const [isEditing, setIsEditing] = useState(false);
//   const [columnVisibility, setColumnVisibility] = useState({
//     No: true,
//     MENUID: true,
//     MENUITEMNAME: true,
//     VIEW: true,
//     CREATE: true,
//     EDIT: true,
//     DELETE: true,
//     QUERY: true,
//     EXPORT: true,
//     ISACTIVE: true,
//     ACTIONS: true
//   });
//   const [syncLoading, setSyncLoading] = useState(false);

//   // Fetch user groups
//   useEffect(() => {
//     const fetchUserGroups = async () => {
//       try {
//         const token = getToken();
//         const response = await fetch(`${process.env.REACT_APP_API_URL}api/getAllUsrGrp`, {
//           method: "GET",
//           headers: {
//             "Content-Type": "application/json",
//             Authorization: `Bearer ${token}`,
//           },
//         });

//         if (!response.ok) {
//           throw new Error(`HTTP error! status: ${response.status}`);
//         }

//         const data = await response.json();
//         setUserGroups(data);
//       } catch (error) {
//         console.error("Error fetching user groups:", error);
//         toast.error("Failed to fetch user groups");
//       }
//     };

//     fetchUserGroups();
//   }, []);

//   // Fetch menu items when user group changes
//   useEffect(() => {
//     if (selectedUserGroup) {
//       fetchData();
//     }
//   }, [selectedUserGroup]);

//   const fetchData = async () => {
//     try {
//       setLoading(true);
//       const data = await getByUsrGrpId(selectedUserGroup);
      
//       const transformedData = data.map((item, index) => ({
//         id: index + 1,
//         menuId: item.menuItemId?.menuItemId || 0,
//         menuItemName: item.menuItemDesc || '',
//         view: item.mvisible === "true",
//         create: item.mcreate === "true",
//         edit: item.medit === "true",
//         delete: item.mdelete === "true",
//         query: item.mquery === "true",
//         export: item.mexport === "true",
//         isActive: item.status === "Enable"
//       }));

//       setMenuItems(transformedData);
//       setLoading(false);
//       toast.success("Data fetched successfully!");
//     } catch (error) {
//       console.error("Fetch failed:", error);
//       setLoading(false);
//       toast.error("Failed to fetch data");
//     }
//   };

//   const handleSync = async () => {
//     setSyncLoading(true);
//     await fetchData();
//     setSyncLoading(false);
//   };

//   // Handle menu item selection for edit
//   const handleMenuItemClick = (event, menuItem) => {
//     setAnchorEl(event.currentTarget);
//     setSelectedMenuItem(menuItem);
//   };

//   const handleCloseMenu = () => {
//     setAnchorEl(null);
//   };

//   // Handle input changes for checkboxes
//   const handleInputChange = (event, menuId) => {
//     const { name, checked } = event.target;
    
//     setMenuItems(prevItems => 
//       prevItems.map(item => 
//         item.menuId === menuId ? { ...item, [name]: checked } : item
//       )
//     );
//   };

//   // Handle user group change
//   const handleUserGroupChange = (event) => {
//     setSelectedUserGroup(event.target.value);
//   };

//   // Handle toggle switch
//   const handleToggleChange = () => {
//     setToggle(!toggle);
//   };

//   // Handle search
//   const handleSearch = (event) => {
//     setSearchQuery(event.target.value);
//     setCurrentPage(1);
//   };

//   // Handle column visibility toggle
//   const toggleColumnVisibility = (column) => {
//     setColumnVisibility(prev => ({
//       ...prev,
//       [column]: !prev[column]
//     }));
//   };

//   // Handle pagination
//   const handlePageChange = (event, value) => {
//     setCurrentPage(value);
//   };

//   // Handle records per page change
//   const handleRecordsPerPageChange = (event) => {
//     setRecordsPerPage(parseInt(event.target.value, 10));
//     setCurrentPage(1);
//   };

//   // Handle add new menu item
//   const handleAddItem = () => {
//     setIsEditing(false);
//     setSelectedMenuItem({
//       menuId: '',
//       menuItemName: '',
//       view: false,
//       create: false,
//       edit: false,
//       delete: false,
//       query: false,
//       export: false,
//       isActive: true
//     });
//     setShowAddEditModal(true);
//   };

//   // Handle edit menu item
//   const handleEditItem = (item) => {
//     setIsEditing(true);
//     setSelectedMenuItem(item);
//     setShowAddEditModal(true);
//     handleCloseMenu();
//   };

//   // Handle delete menu item
//   const handleDeleteItem = () => {
//     setMenuItems(prevItems => 
//       prevItems.filter(item => item.menuId !== selectedMenuItem.menuId)
//     );
//     handleCloseMenu();
//   };

//   // Handle form submit
//   const handleSubmit = (event) => {
//     event.preventDefault();
//     if (isEditing) {
//       setMenuItems(prevItems => 
//         prevItems.map(item => 
//           item.menuId === selectedMenuItem.menuId ? selectedMenuItem : item
//         )
//       );
//     } else {
//       const newId = Math.max(...menuItems.map(item => item.menuId)) + 1;
//       setMenuItems([...menuItems, { ...selectedMenuItem, menuId: newId }]);
//     }
//     setShowAddEditModal(false);
//   };

//   // Filter and paginate data
//   const filteredItems = menuItems.filter(item =>
//     item.menuItemName.toLowerCase().includes(searchQuery.toLowerCase())
//   ).filter(item => !toggle || item.menuId >= 10);

//   const totalPages = Math.ceil(filteredItems.length / recordsPerPage);
//   const paginatedItems = filteredItems.slice(
//     (currentPage - 1) * recordsPerPage,
//     currentPage * recordsPerPage
//   );

//   // Column definitions
//   const columns = [
//     { id: 'SYNC', label: 'SYNC', visible: true },
//     { id: 'NO', label: 'NO', visible: columnVisibility.No },
//     { id: 'MENUID', label: 'MENUID', visible: columnVisibility.MENUID },
//     { id: 'MENUITEMNAME', label: 'MENUITEMNAME', visible: columnVisibility.MENUITEMNAME },
//     { id: 'VIEW', label: 'VIEW', visible: columnVisibility.VIEW },
//     { id: 'CREATE', label: 'CREATE', visible: columnVisibility.CREATE },
//     { id: 'EDIT', label: 'EDIT', visible: columnVisibility.EDIT },
//     { id: 'DELETE', label: 'DELETE', visible: columnVisibility.DELETE },
//     { id: 'QUERY', label: 'QUERY', visible: columnVisibility.QUERY },
//     { id: 'EXPORT', label: 'EXPORT', visible: columnVisibility.EXPORT },
//     { id: 'ISACTIVE', label: 'ISACTIVE', visible: columnVisibility.ISACTIVE },
//     { id: 'ACTIONS', label: 'ACTIONS', visible: columnVisibility.ACTIONS }
//   ];

//   return (
//     <Container maxWidth="xl" sx={{ mt: 8 }}>
//       {/* Header section */}
//       <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
//         <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
//           <Typography variant="h4" component="h1" sx={{ fontWeight: 'bold' }}>
//             Menu Access Control
//           </Typography>
//           <StyledBadge badgeContent="EDIT MODE" sx={{margin : '20px' ,padding : '3px'}} />
//         </Box>
        
//         <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
//           <Typography>For</Typography>
//           <FormControl size="small" sx={{ minWidth: 150 }}>
//             <InputLabel id="user-group-label">User Group</InputLabel>
//             <Select
//               labelId="user-group-label"
//               value={selectedUserGroup}
//               label="User Group"
//               onChange={handleUserGroupChange}
//             >
//               {userGroups.map((group) => (
//                 <MenuItem key={group.usrGrp} value={group.usrGrp}>
//                   {group.groupName}
//                 </MenuItem>
//               ))}
//             </Select>
//           </FormControl>
//           <Button
//             variant="contained"
//             onClick={fetchData}
//             startIcon={<SyncIcon />}
//           >
//             Reload
//           </Button>
//           <Typography>{toggle ? "Only Main Menu" : "Show All"}</Typography>
//           <FormControlLabel
//             control={<Switch checked={toggle} onChange={handleToggleChange} />}
//             label="Toggle"
//           />
//         </Box>
//       </Box>

//       {/* Search and action buttons */}
//       <Grid container spacing={2} sx={{ mb: 3 }}>
//         <Grid item xs={12} md={8}>
//           <TextField
//             fullWidth
//             placeholder="Search"
//             variant="outlined"
//             size="small"
//             value={searchQuery}
//             onChange={handleSearch}
//             InputProps={{
//               startAdornment: (
//                 <InputAdornment position="start">
//                   <SearchIcon />
//                 </InputAdornment>
//               ),
//             }}
//           />
//         </Grid>
//         <Grid item xs={12} md={4} sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
//           <IconButton onClick={handleAddItem}>
//             <AddIcon />
//           </IconButton>
//           <IconButton>
//             <MenuIcon />
//           </IconButton>
//         </Grid>
//       </Grid>

//       {/* Main table */}
//       {loading ? (
//         <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
//           <CircularProgress />
//         </Box>
//       ) : (
//         <>
//           <TableContainer component={Paper} sx={{ mb: 2 }}>
//             <Table>
//               <StyledTableHead>
//                 <TableRow>
//                   {columns.map((column) => (
//                     column.visible && (
//                       <StyledTableCell key={column.id}>
//                         {column.label}
//                       </StyledTableCell>
//                     )
//                   ))}
//                 </TableRow>
//               </StyledTableHead>
//               <TableBody>
//                 {paginatedItems.length === 0 ? (
//                   <TableRow>
//                     <TableCell colSpan={columns.length} align="center">
//                       No items found
//                     </TableCell>
//                   </TableRow>
//                 ) : (
//                   paginatedItems.map((item, index) => (
//                     <TableRow key={item.menuId}>
//                       {/* Sync column */}
//                       <TableCell>
//                         <Tooltip title="Sync">
//                           <IconButton 
//                             onClick={() => handleSync(item.menuId)}
//                             disabled={syncLoading}
//                           >
//                             {syncLoading ? <CircularProgress size={24} /> : <SyncIcon />}
//                           </IconButton>
//                         </Tooltip>
//                       </TableCell>
                      
//                       {/* Other columns */}
//                       {columnVisibility.No && <TableCell>{index + 1}</TableCell>}
//                       {columnVisibility.MENUID && <TableCell>{item.menuId}</TableCell>}
//                       {columnVisibility.MENUITEMNAME && <TableCell>{item.menuItemName}</TableCell>}
//                       {columnVisibility.VIEW && (
//                         <TableCell>
//                           <Checkbox
//                             checked={item.view || false}
//                             onChange={(e) => handleInputChange(e, item.menuId)}
//                             name="view"
//                           />
//                         </TableCell>
//                       )}
//                       {columnVisibility.CREATE && (
//                         <TableCell>
//                           <Checkbox
//                             checked={item.create || false}
//                             onChange={(e) => handleInputChange(e, item.menuId)}
//                             name="create"
//                           />
//                         </TableCell>
//                       )}
//                       {columnVisibility.EDIT && (
//                         <TableCell>
//                           <Checkbox
//                             checked={item.edit || false}
//                             onChange={(e) => handleInputChange(e, item.menuId)}
//                             name="edit"
//                           />
//                         </TableCell>
//                       )}
//                       {columnVisibility.DELETE && (
//                         <TableCell>
//                           <Checkbox
//                             checked={item.delete || false}
//                             onChange={(e) => handleInputChange(e, item.menuId)}
//                             name="delete"
//                           />
//                         </TableCell>
//                       )}
//                       {columnVisibility.QUERY && (
//                         <TableCell>
//                           <Checkbox
//                             checked={item.query || false}
//                             onChange={(e) => handleInputChange(e, item.menuId)}
//                             name="query"
//                           />
//                         </TableCell>
//                       )}
//                       {columnVisibility.EXPORT && (
//                         <TableCell>
//                           <Checkbox
//                             checked={item.export || false}
//                             onChange={(e) => handleInputChange(e, item.menuId)}
//                             name="export"
//                           />
//                         </TableCell>
//                       )}
//                       {columnVisibility.ISACTIVE && (
//                         <TableCell>
//                           <Checkbox
//                             checked={item.isActive || false}
//                             onChange={(e) => handleInputChange(e, item.menuId)}
//                             name="isActive"
//                           />
//                         </TableCell>
//                       )}
//                       {columnVisibility.ACTIONS && (
//                         <TableCell>
//                           <IconButton onClick={(e) => handleMenuItemClick(e, item)}>
//                             <MoreVertIcon />
//                           </IconButton>
//                         </TableCell>
//                       )}
//                     </TableRow>
//                   ))
//                 )}
//               </TableBody>
//             </Table>
//           </TableContainer>

//           {/* Pagination and controls */}
//           <Grid container spacing={2} sx={{ mt: 2 }}>
//             <Grid item xs={12} md={6}>
//               <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
//                 <FormControl size="small" variant="outlined">
//                   <InputLabel>Records</InputLabel>
//                   <Select
//                     value={recordsPerPage}
//                     onChange={handleRecordsPerPageChange}
//                     label="Records"
//                   >
//                     <MenuItem value={5}>5</MenuItem>
//                     <MenuItem value={10}>10</MenuItem>
//                     <MenuItem value={20}>20</MenuItem>
//                     <MenuItem value={50}>50</MenuItem>
//                   </Select>
//                 </FormControl>
//                 <Typography>
//                   Showing {paginatedItems.length} of {filteredItems.length} items
//                 </Typography>
//               </Box>
//             </Grid>
//             <Grid item xs={12} md={6} sx={{ display: 'flex', justifyContent: 'flex-end' }}>
//               <Pagination
//                 count={totalPages}
//                 page={currentPage}
//                 onChange={handlePageChange}
//                 color="primary"
//                 showFirstButton
//                 showLastButton
//               />
//             </Grid>
//           </Grid>
//         </>
//       )}

//       {/* Column visibility popover */}
//       <Popover
//         open={Boolean(anchorEl)}
//         anchorEl={anchorEl}
//         onClose={handleCloseMenu}
//         anchorOrigin={{
//           vertical: 'bottom',
//           horizontal: 'right',
//         }}
//         transformOrigin={{
//           vertical: 'top',
//           horizontal: 'right',
//         }}
//       >
//         <Box sx={{ p: 2 }}>
//           <Typography variant="subtitle1" sx={{ mb: 1 }}>Manage Columns</Typography>
//           <Divider sx={{ mb: 1 }} />
//           {Object.keys(columnVisibility).map((column) => (
//             <FormControlLabel
//               key={column}
//               control={
//                 <Checkbox
//                   checked={columnVisibility[column]}
//                   onChange={() => toggleColumnVisibility(column)}
//                   name={column}
//                 />
//               }
//               label={column}
//             />
//           ))}
//         </Box>
//       </Popover>

//       {/* Edit/Add modal */}
//       <Dialog open={showAddEditModal} onClose={() => setShowAddEditModal(false)}>
//         <DialogTitle>
//           {isEditing ? "Edit Menu Item" : "Add Menu Item"}
//           <IconButton
//             aria-label="close"
//             onClick={() => setShowAddEditModal(false)}
//             sx={{
//               position: 'absolute',
//               right: 8,
//               top: 8,
//               color: (theme) => theme.palette.grey[500],
//             }}
//           >
//             <CloseIcon />
//           </IconButton>
//         </DialogTitle>
//         <DialogContent>
//           <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
//             <TextField
//               margin="normal"
//               required
//               fullWidth
//               label="Menu Item Name"
//               name="menuItemName"
//               value={selectedMenuItem?.menuItemName || ''}
//               onChange={(e) => setSelectedMenuItem({
//                 ...selectedMenuItem,
//                 menuItemName: e.target.value
//               })}
//             />
//             <FormControlLabel
//               control={
//                 <Checkbox
//                   checked={selectedMenuItem?.isActive || false}
//                   onChange={(e) => setSelectedMenuItem({
//                     ...selectedMenuItem,
//                     isActive: e.target.checked
//                   })}
//                   name="isActive"
//                 />
//               }
//               label="Active"
//             />
//           </Box>
//         </DialogContent>
//         <DialogActions>
//           <Button onClick={() => setShowAddEditModal(false)}>Cancel</Button>
//           <Button type="submit" variant="contained" onClick={handleSubmit}>
//             {isEditing ? "Update" : "Add"}
//           </Button>
//         </DialogActions>
//       </Dialog>
//     </Container>
//   );
// }

// export default MenuAccessControl;



import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Container,
  Typography,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Switch,
  FormControlLabel,
  Checkbox,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Pagination,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Tooltip,
  Badge,
  Grid,
  InputAdornment,
  Popover,
  Divider,
  CircularProgress,
  Paper
} from '@mui/material';
import {
  Sync as SyncIcon,
  Add as AddIcon,
  Menu as MenuIcon,
  Search as SearchIcon,
  Close as CloseIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  ViewColumn as ViewColumnIcon,
  FilterList as FilterListIcon,
  MoreVert as MoreVertIcon
} from '@mui/icons-material';
import { styled } from '@mui/material/styles';
import { getByUsrGrpId } from "../../../ApiServices/MenuAccessControlAPI";
import { getToken } from "../../../utils/tokenService";
import { toast } from "react-toastify";

// Styled components
const StyledBadge = styled(Badge)(({ theme }) => ({
  '& .MuiBadge-badge': {
    backgroundColor: theme.palette.info.main,
    color: theme.palette.info.contrastText,
    fontSize: '0.7rem',
    padding: '5px 10px',
    borderRadius: '10px'
  }
}));

const StyledTableHead = styled(TableHead)(({ theme }) => ({
  backgroundColor: theme.palette.primary.main,
  '& .MuiTableCell-root': {
    color: theme.palette.primary.contrastText,
    fontWeight: 'bold'
  }
}));

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  '&.MuiTableCell-head': {
    fontWeight: 'bold'
  }
}));

function MenuAccessControl() {
  // State management
  const [loading, setLoading] = useState(true);
  const [menuItems, setMenuItems] = useState([]);
  const [userGroups, setUserGroups] = useState([]);
  const [selectedUserGroup, setSelectedUserGroup] = useState(1);
  const [toggle, setToggle] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [editMode, setEditMode] = useState(false);
  const [selectedMenuItem, setSelectedMenuItem] = useState(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const [showAddEditModal, setShowAddEditModal] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [columnVisibility, setColumnVisibility] = useState({
    No: true,
    MENUID: true,
    MENUITEMNAME: true,
    VIEW: true,
    CREATE: true,
    EDIT: true,
    DELETE: true,
    QUERY: true,
    EXPORT: true,
    ISACTIVE: true,
    ACTIONS: true
  });
  const [syncLoading, setSyncLoading] = useState(false);

  // Fetch user groups
  useEffect(() => {
    const fetchUserGroups = async () => {
      try {
        const token = getToken();
        const response = await fetch(`${process.env.REACT_APP_API_URL}api/getAllUsrGrp`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        setUserGroups(data);
      } catch (error) {
        console.error("Error fetching user groups:", error);
        toast.error("Failed to fetch user groups");
      }
    };

    fetchUserGroups();
  }, []);

  // Fetch menu items when user group changes
  useEffect(() => {
    if (selectedUserGroup) {
      fetchData();
    }
  }, [selectedUserGroup]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const data = await getByUsrGrpId(selectedUserGroup);
      
      const transformedData = data.map((item, index) => ({
        id: index + 1,
        menuId: item.menuItemId?.menuItemId || 0,
        menuItemName: item.menuItemDesc || '',
        view: item.mvisible === "true",
        create: item.mcreate === "true",
        edit: item.medit === "true",
        delete: item.mdelete === "true",
        query: item.mquery === "true",
        export: item.mexport === "true",
        isActive: item.status === "Enable"
      }));

      setMenuItems(transformedData);
      setLoading(false);
      toast.success("Data fetched successfully!");
    } catch (error) {
      console.error("Fetch failed:", error);
      setLoading(false);
      toast.error("Failed to fetch data");
    }
  };

  const handleSync = async () => {
    setSyncLoading(true);
    await fetchData();
    setSyncLoading(false);
  };

  // Handle menu item selection for edit
  const handleMenuItemClick = (event, menuItem) => {
    setAnchorEl(event.currentTarget);
    setSelectedMenuItem(menuItem);
  };

  const handleCloseMenu = () => {
    setAnchorEl(null);
  };

  // Handle input changes for checkboxes
  const handleInputChange = (event, menuId) => {
    const { name, checked } = event.target;
    
    setMenuItems(prevItems => 
      prevItems.map(item => 
        item.menuId === menuId ? { ...item, [name]: checked } : item
      )
    );
  };

  // Handle user group change
  const handleUserGroupChange = (event) => {
    setSelectedUserGroup(event.target.value);
  };

  // Handle toggle switch
  const handleToggleChange = () => {
    setToggle(!toggle);
    console.log("Filtered items:", filteredItems);
  };

  // Handle search
  const handleSearch = (event) => {
    setSearchQuery(event.target.value);
    setCurrentPage(1);
  };

  // Handle column visibility toggle
  const toggleColumnVisibility = (column) => {
    setColumnVisibility(prev => ({
      ...prev,
      [column]: !prev[column]
    }));
  };

  // Handle pagination
  const handlePageChange = (event, value) => {
    setCurrentPage(value);
  };

  // Handle records per page change
  const handleRecordsPerPageChange = (event) => {
    setRecordsPerPage(parseInt(event.target.value, 10));
    setCurrentPage(1);
  };

  // Handle add new menu item
  const handleAddItem = () => {
    setIsEditing(false);
    setSelectedMenuItem({
      menuId: '',
      menuItemName: '',
      view: false,
      create: false,
      edit: false,
      delete: false,
      query: false,
      export: false,
      isActive: true
    });
    setShowAddEditModal(true);
  };

  // Handle edit menu item
  const handleEditItem = (item) => {
    setIsEditing(true);
    setSelectedMenuItem(item);
    setShowAddEditModal(true);
    handleCloseMenu();
  };

  // Handle delete menu item
  const handleDeleteItem = () => {
    setMenuItems(prevItems => 
      prevItems.filter(item => item.menuId !== selectedMenuItem.menuId)
    );
    handleCloseMenu();
  };

  // Handle form submit
  const handleSubmit = (event) => {
    event.preventDefault();
    if (isEditing) {
      setMenuItems(prevItems => 
        prevItems.map(item => 
          item.menuId === selectedMenuItem.menuId ? selectedMenuItem : item
        )
      );
    } else {
      const newId = Math.max(...menuItems.map(item => item.menuId)) + 1;
      setMenuItems([...menuItems, { ...selectedMenuItem, menuId: newId }]);
    }
    setShowAddEditModal(false);
  };

  // Filter and paginate data
  const filteredItems = menuItems.filter(item =>
    item.menuItemName.toLowerCase().includes(searchQuery.toLowerCase())
  ).filter(item => !toggle || item.menuId === 1577 || item.menuId === 1601 ); // Only show items with menuId 0 when toggle is on

  const totalPages = Math.ceil(filteredItems.length / recordsPerPage);
  const paginatedItems = filteredItems.slice(
    (currentPage - 1) * recordsPerPage,
    currentPage * recordsPerPage
  );

  // Column definitions
  const columns = [
    { id: 'SYNC', label: 'SYNC', visible: true },
    { id: 'NO', label: 'NO', visible: columnVisibility.No },
    { id: 'MENUID', label: 'MENUID', visible: columnVisibility.MENUID },
    { id: 'MENUITEMNAME', label: 'MENUITEMNAME', visible: columnVisibility.MENUITEMNAME },
    { id: 'VIEW', label: 'VIEW', visible: columnVisibility.VIEW },
    { id: 'CREATE', label: 'CREATE', visible: columnVisibility.CREATE },
    { id: 'EDIT', label: 'EDIT', visible: columnVisibility.EDIT },
    { id: 'DELETE', label: 'DELETE', visible: columnVisibility.DELETE },
    { id: 'QUERY', label: 'QUERY', visible: columnVisibility.QUERY },
    { id: 'EXPORT', label: 'EXPORT', visible: columnVisibility.EXPORT },
    { id: 'ISACTIVE', label: 'ISACTIVE', visible: columnVisibility.ISACTIVE },
    { id: 'ACTIONS', label: 'ACTIONS', visible: columnVisibility.ACTIONS }
  ];

  return (
    <Container maxWidth="xl" sx={{ mt: 8 }}>
      {/* Header section */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Typography variant="h4" component="h1" sx={{ fontWeight: 'bold' }}>
            Menu Access Control
          </Typography>
          <StyledBadge badgeContent="EDIT MODE" sx={{margin : '20px' ,padding : '3px'}} />
        </Box>
        
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Typography>For</Typography>
          <FormControl size="small" sx={{ minWidth: 150 }}>
            <InputLabel id="user-group-label">User Group</InputLabel>
            <Select
              labelId="user-group-label"
              value={selectedUserGroup}
              label="User Group"
              onChange={handleUserGroupChange}
            >
              {userGroups.map((group) => (
                <MenuItem key={group.usrGrp} value={group.usrGrp}>
                  {group.groupName}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <Button
            variant="contained"
            onClick={fetchData}
            startIcon={<SyncIcon />}
          >
            Reload
          </Button>
          <Typography>{toggle ? "Only Main Menu" : "Show All"}</Typography>
          <FormControlLabel
            control={<Switch checked={toggle} onChange={handleToggleChange} />}
            label="Toggle"
          />
        </Box>
      </Box>

      {/* Search and action buttons */}
      <Grid container spacing={2} sx={{ mb: 3 }}>
        <Grid item xs={12} md={8}>
          <TextField
            fullWidth
            placeholder="Search"
            variant="outlined"
            size="small"
            value={searchQuery}
            onChange={handleSearch}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
            }}
          />
        </Grid>
        <Grid item xs={12} md={4} sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
          <IconButton onClick={handleAddItem}>
            <AddIcon />
          </IconButton>
          <IconButton>
            <MenuIcon />
          </IconButton>
        </Grid>
      </Grid>

      {/* Main table */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <CircularProgress />
        </Box>
      ) : (
        <>
          <TableContainer component={Paper} sx={{ mb: 2 }}>
            <Table>
              <StyledTableHead>
                <TableRow>
                  {columns.map((column) => (
                    column.visible && (
                      <StyledTableCell key={column.id}>
                        {column.label}
                      </StyledTableCell>
                    )
                  ))}
                </TableRow>
              </StyledTableHead>
              <TableBody>
                {paginatedItems.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={columns.length} align="center">
                      No items found
                    </TableCell>
                  </TableRow>
                ) : (
                  paginatedItems.map((item, index) => (
                    <TableRow key={item.menuId}>
                      {/* Sync column - only show for items with menuId 0 */}
                      <TableCell>
                        {(item.menuId === 1577 || item.menuId === 1601) && (
                          <Tooltip title="Sync">
                            <IconButton 
                              onClick={() => handleSync(item.menuId)}
                              disabled={syncLoading}
                            >
                              {syncLoading ? <CircularProgress size={24} /> : <SyncIcon />}
                            </IconButton>
                          </Tooltip>
                        )}
                      </TableCell>
                      
                      {/* Other columns */}
                      {columnVisibility.No && <TableCell>{index + 1}</TableCell>}
                      {columnVisibility.MENUID && <TableCell>{item.menuId}</TableCell>}
                      {columnVisibility.MENUITEMNAME && <TableCell>{item.menuItemName}</TableCell>}
                      {columnVisibility.VIEW && (
                        <TableCell>
                          <Checkbox
                            checked={item.view || false}
                            onChange={(e) => handleInputChange(e, item.menuId)}
                            name="view"
                          />
                        </TableCell>
                      )}
                      {columnVisibility.CREATE && (
                        <TableCell>
                          <Checkbox
                            checked={item.create || false}
                            onChange={(e) => handleInputChange(e, item.menuId)}
                            name="create"
                          />
                        </TableCell>
                      )}
                      {columnVisibility.EDIT && (
                        <TableCell>
                          <Checkbox
                            checked={item.edit || false}
                            onChange={(e) => handleInputChange(e, item.menuId)}
                            name="edit"
                          />
                        </TableCell>
                      )}
                      {columnVisibility.DELETE && (
                        <TableCell>
                          <Checkbox
                            checked={item.delete || false}
                            onChange={(e) => handleInputChange(e, item.menuId)}
                            name="delete"
                          />
                        </TableCell>
                      )}
                      {columnVisibility.QUERY && (
                        <TableCell>
                          <Checkbox
                            checked={item.query || false}
                            onChange={(e) => handleInputChange(e, item.menuId)}
                            name="query"
                          />
                        </TableCell>
                      )}
                      {columnVisibility.EXPORT && (
                        <TableCell>
                          <Checkbox
                            checked={item.export || false}
                            onChange={(e) => handleInputChange(e, item.menuId)}
                            name="export"
                          />
                        </TableCell>
                      )}
                      {columnVisibility.ISACTIVE && (
                        <TableCell>
                          <Checkbox
                            checked={item.isActive || false}
                            onChange={(e) => handleInputChange(e, item.menuId)}
                            name="isActive"
                          />
                        </TableCell>
                      )}
                      {columnVisibility.ACTIONS && (
                        <TableCell>
                          <IconButton onClick={(e) => handleMenuItemClick(e, item)}>
                            <MoreVertIcon />
                          </IconButton>
                        </TableCell>
                      )}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>

          {/* Pagination and controls */}
          <Grid container spacing={2} sx={{ mt: 2 }}>
            <Grid item xs={12} md={6}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                <FormControl size="small" variant="outlined">
                  <InputLabel>Records</InputLabel>
                  <Select
                    value={recordsPerPage}
                    onChange={handleRecordsPerPageChange}
                    label="Records"
                  >
                    <MenuItem value={5}>5</MenuItem>
                    <MenuItem value={10}>10</MenuItem>
                    <MenuItem value={20}>20</MenuItem>
                    <MenuItem value={50}>50</MenuItem>
                  </Select>
                </FormControl>
                <Typography>
                  Showing {paginatedItems.length} of {filteredItems.length} items
                </Typography>
              </Box>
            </Grid>
            <Grid item xs={12} md={6} sx={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Pagination
                count={totalPages}
                page={currentPage}
                onChange={handlePageChange}
                color="primary"
                showFirstButton
                showLastButton
              />
            </Grid>
          </Grid>
        </>
      )}

      {/* Column visibility popover */}
      <Popover
        open={Boolean(anchorEl)}
        anchorEl={anchorEl}
        onClose={handleCloseMenu}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
      >
        <Box sx={{ p: 2 }}>
          <Typography variant="subtitle1" sx={{ mb: 1 }}>Manage Columns</Typography>
          <Divider sx={{ mb: 1 }} />
          {Object.keys(columnVisibility).map((column) => (
            <FormControlLabel
              key={column}
              control={
                <Checkbox
                  checked={columnVisibility[column]}
                  onChange={() => toggleColumnVisibility(column)}
                  name={column}
                />
              }
              label={column}
            />
          ))}
        </Box>
      </Popover>

      {/* Edit/Add modal */}
      <Dialog open={showAddEditModal} onClose={() => setShowAddEditModal(false)}>
        <DialogTitle>
          {isEditing ? "Edit Menu Item" : "Add Menu Item"}
          <IconButton
            aria-label="close"
            onClick={() => setShowAddEditModal(false)}
            sx={{
              position: 'absolute',
              right: 8,
              top: 8,
              color: (theme) => theme.palette.grey[500],
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
            <TextField
              margin="normal"
              required
              fullWidth
              label="Menu Item Name"
              name="menuItemName"
              value={selectedMenuItem?.menuItemName || ''}
              onChange={(e) => setSelectedMenuItem({
                ...selectedMenuItem,
                menuItemName: e.target.value
              })}
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={selectedMenuItem?.isActive || false}
                  onChange={(e) => setSelectedMenuItem({
                    ...selectedMenuItem,
                    isActive: e.target.checked
                  })}
                  name="isActive"
                />
              }
              label="Active"
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowAddEditModal(false)}>Cancel</Button>
          <Button type="submit" variant="contained" onClick={handleSubmit}>
            {isEditing ? "Update" : "Add"}
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
}

export default MenuAccessControl;