import React, { useState, useEffect } from "react";
import {
  Box,
  Button,
  Container,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  IconButton,
  Tooltip,
  Menu,
  MenuItem,
  Checkbox,
  Pagination,
  Select,
  FormControl,
  InputLabel,
  Modal,
  FormGroup,
  FormControlLabel,
  Switch,
  CircularProgress,
  Chip,
  Grid,
  InputAdornment
} from "@mui/material";
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Menu as MenuIcon,
  ArrowBack as ArrowBackIcon,
  Close as CloseIcon,
  Download as DownloadIcon,
  Upload as UploadIcon,
  InsertDriveFile as ExcelIcon,
  Search as SearchIcon,
  CheckCircle as CheckCircleIcon
} from "@mui/icons-material";
import { toast } from "react-toastify";
import { useNavigate } from "react-router-dom";
import * as XLSX from "xlsx";
import {
  fetchMenuItems,
  addMenuItem,
  updateMenuItem,
  deleteMenuItem,
  getSubmenuItems,
  addSubmenuItem,
  updateSubmenuItem,
  deleteSubmenuItem
} from "../../../ApiServices/menumaintananceapi";

function MenuMaintenance() {
  const [menuItems, setMenuItems] = useState([]);
  const [subMenuItems, setSubMenuItems] = useState([]);
  const [showAddEditPopup, setShowAddEditPopup] = useState(false);
  const [currentMenuItem, setCurrentMenuItem] = useState({
    menuItemDesc: "",
    menuId: 0,
    itemSeq: "",
    moduleName: "",
    main_menu_action_name: "",
    main_menu_icon_name: "",
    status: "true"
  });
  const [isEditing, setIsEditing] = useState(false);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [visibleColumns, setVisibleColumns] = useState({
    menuItemDesc: true,
    menu_id: true,
    itemSeq: true,
    moduleName: true,
    main_menu_action_name: true,
    main_menu_icon_name: true,
    status: true,
  });
  const [isSubMenu, setIsSubMenu] = useState(false);
  const [parentMenuItemId, setParentMenuItemId] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [error, setError] = useState(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const [pageAnchorEl, setPageAnchorEl] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 3000);
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        console.log("Fetching Menu Items...");
        const data = await fetchMenuItems();
        setMenuItems(data);
        console.log("Fetched Menu Items:", data);
        toast.success("Menu items fetched successfully!");
      } catch (error) {
        console.error("Fetching error:", error);
        setError(error.message);
        toast.error("Error fetching menu items.");
      }
    };

    fetchData();
  }, []);

  const toggleColumn = (column) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [column]: !prev[column],
    }));
  };

  const openAddEditPopup = (menuItem = {}) => {
    setIsEditing(!!menuItem.menuItemId);
    setCurrentMenuItem(menuItem);
    setParentMenuItemId(isSubMenu ? menuItem.menuItemId : null);
    setShowAddEditPopup(true);
  };

  const handleOpenModal = () => setShowModal(true);
  const handleCloseModal = () => setShowModal(false);

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      console.log("Selected file:", file.name);
    }
  };

  const exportToExcel = () => {
    const worksheet = XLSX.utils.json_to_sheet([]);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "UserDetails");
    XLSX.writeFile(workbook, "MenuMaintenance.xlsx");
  };

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    const processedValue = name === "status" ? value === "true" : value;
    setCurrentMenuItem((prev) => ({ ...prev, [name]: processedValue }));
  };

  const handleSearch = (query) => {
    setSearchQuery(query);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      if (isEditing) {
        const updatedItem = await updateMenuItem(currentMenuItem.menuItemId, currentMenuItem);
        setMenuItems(menuItems.map(item => 
          item.menuItemId === currentMenuItem.menuItemId ? updatedItem : item
        ));
        toast.success("Menu item updated successfully!");
      } else {
        const addedItem = await addMenuItem(currentMenuItem);
        setMenuItems([...menuItems, addedItem]);
        toast.success("Menu item added successfully!");
      }
      setShowAddEditPopup(false);
    } catch (error) {
      toast.error(`Operation failed: ${error.message}`);
      console.error("Submit error:", error);
    }
  };

  const handleDelete = async (menuItemId) => {
    if (isSubMenu) {
      setSubMenuItems(
        subMenuItems.filter((item) => item.menuItemId !== menuItemId)
      );
    } else {
      await deleteMenuItem(menuItemId);
      setMenuItems(menuItems.filter((item) => item.menuItemId !== menuItemId));
    }
    toast.success("Menu item deleted successfully!");
  };

  const handleRecordsPerPageChange = (number) => {
    setRecordsPerPage(number);
    setPageAnchorEl(null);
  };

  const handleSubMenuClick = (menuItemId) => {
    navigate(`/dashboard/setup/sub-menu-maintenance/${menuItemId}`);
    fetchSubMenuItems(menuItemId);
  };

  const fetchSubMenuItems = async (menuItemId) => {
    try {
      const data = await getSubmenuItems(menuItemId);
      console.log("Fetched Sub-Menu Items:", data);
      setSubMenuItems(data);
      setIsSubMenu(true);
      setParentMenuItemId(menuItemId);
      toast.success("Sub-menu items fetched successfully!");
    } catch (error) {
      console.error("Error fetching sub-menu items:", error);
      toast.error("Failed to fetch sub-menu items.");
    }
  };

  const handleMainMenuClick = (menuId) => {
    console.log("Selected Menu ID:", menuId);
  };

  const handleBackToMainMenu = () => {
    setIsSubMenu(false);
    setSubMenuItems([]);
    setParentMenuItemId(null);
  };

  const totalPages = Math.ceil(menuItems.length / recordsPerPage);
  const handlePageChange = (event, pageNumber) => {
    setCurrentPage(pageNumber);
  };

  const handleClose = () => {
    setShowAddEditPopup(false);
  };

  const slicedMenus = (isSubMenu ? subMenuItems : menuItems)
    .filter(
      (menuItem) =>
        menuItem.menuItemDesc &&
        menuItem.menuItemDesc.toLowerCase().includes(searchQuery.toLowerCase())
    )
    .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage);

  const handleMenuOpen = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  const handlePageMenuOpen = (event) => {
    setPageAnchorEl(event.currentTarget);
  };

  const handlePageMenuClose = () => {
    setPageAnchorEl(null);
  };

  return (
    <Box sx={{ mt: -2 }}>
      {loading ? (
        <Box display="flex" justifyContent="center" alignItems="center" height="80vh">
          <CircularProgress />
        </Box>
      ) : (
        <Container maxWidth="xl" sx={{ mt: 5 }}>
          <Box display="flex" justifyContent="space-between" alignItems="center" mb={4}>
            <Typography variant="h4" component="h1" sx={{ fontWeight: 'bold' }}>
              Menu Maintenance
            </Typography>
          </Box>

          <Grid container spacing={2} alignItems="center" my={3}>
            <Grid item xs={12} md={8} lg={6}>
              <TextField
                fullWidth
                placeholder="Search"
                value={searchQuery}
                onChange={(e) => handleSearch(e.target.value)}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <SearchIcon sx={{ color: '#fff' }} />
                    </InputAdornment>
                  ),
                  sx: {
                    backgroundColor: '#fff',
                    borderRadius: '10px',
                    boxShadow: '0px 4px 12px rgba(0, 0, 0, 0.1)',
                    '& .MuiOutlinedInput-notchedOutline': {
                      border: 'none'
                    }
                  }
                }}
                sx={{
                  maxWidth: 528
                }}
              />
            </Grid>

            <Grid item xs={12} md={4} lg={6} sx={{ display: 'flex', justifyContent: 'flex-end' }}>
              {isSubMenu && (
                <IconButton onClick={handleBackToMainMenu} sx={{ mr: 2 }}>
                  <ArrowBackIcon sx={{ color: '#747264', fontSize: '1.5rem' }} />
                </IconButton>
              )}

              <Tooltip title="Add Menu">
                <IconButton onClick={() => openAddEditPopup()} sx={{ mr: 2 }}>
                  <AddIcon sx={{ color: '#747264', fontSize: '1.5rem' }} />
                </IconButton>
              </Tooltip>

              <Tooltip title="Download template">
                <IconButton sx={{ mr: 2 }}>
                  <DownloadIcon sx={{ color: '#747264', fontSize: '1.5rem' }} />
                </IconButton>
              </Tooltip>

              <Tooltip title="Import">
                <IconButton onClick={handleOpenModal} sx={{ mr: 2 }}>
                  <UploadIcon sx={{ color: '#747264', fontSize: '1.5rem' }} />
                </IconButton>
              </Tooltip>

              <Tooltip title="XLSX">
                <IconButton onClick={exportToExcel} sx={{ mr: 2 }}>
                  <ExcelIcon sx={{ color: '#747264', fontSize: '1.5rem' }} />
                </IconButton>
              </Tooltip>
            </Grid>
          </Grid>

          <Modal open={showModal} onClose={handleCloseModal}>
            <Box sx={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 400,
              bgcolor: 'background.paper',
              boxShadow: 24,
              p: 4,
              borderRadius: 1
            }}>
              <Typography variant="h6" component="h2" mb={2}>
                Import File
              </Typography>
              <FormControl fullWidth>
                <InputLabel>Select a file to import:</InputLabel>
                <input
                  type="file"
                  accept=".xlsx, .xls, .csv"
                  onChange={handleFileChange}
                  style={{ marginBottom: 16 }}
                />
              </FormControl>
              <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
                <Button onClick={handleCloseModal} sx={{ mr: 2 }}>Cancel</Button>
                <Button variant="contained" onClick={handleCloseModal}>Upload</Button>
              </Box>
            </Box>
          </Modal>

          <TableContainer component={Paper} sx={{ boxShadow: 3 }}>
            <Table>
              <TableHead sx={{ backgroundColor: '#f8f9fa' }}>
                <TableRow>
                  <TableCell>No</TableCell>
                  {Object.entries(visibleColumns).map(
                    ([key, visible]) =>
                      visible && (
                        <TableCell key={key}>
                          {key.charAt(0).toUpperCase() + key.slice(1)}
                        </TableCell>
                      )
                  )}
                  <TableCell>Actions</TableCell>
                  {!isSubMenu && <TableCell>Sub-Menu</TableCell>}
                </TableRow>
              </TableHead>

              <TableBody>
                {slicedMenus.length === 0 ? (
                  <TableRow>
                    <TableCell
                      colSpan={
                        1 +
                        Object.keys(visibleColumns).filter(
                          (key) => visibleColumns[key]
                        ).length +
                        (isSubMenu ? 1 : 2)
                      }
                      align="center"
                    >
                      No menu items found. Please add new items.
                    </TableCell>
                  </TableRow>
                ) : (
                  slicedMenus.map((menuItem, index) => (
                    <TableRow
                      key={`${menuItem.menuItemId}-${index}`}
                      hover
                      onClick={() => handleMainMenuClick(menuItem.menuItemId)}
                    >
                      <TableCell>{index + 1}</TableCell>
                      {Object.keys(visibleColumns).map(
                        (key) =>
                          visibleColumns[key] && (
                            <TableCell key={key}>
                              {key === "status" ? (
                                <Chip
                                  label={menuItem.status ? "Enabled" : "Disabled"}
                                  color={menuItem.status ? "success" : "error"}
                                  size="small"
                                />
                              ) : (
                                menuItem[key]
                              )}
                            </TableCell>
                          )
                      )}
                      <TableCell align="center">
                        <IconButton
                          onClick={() => openAddEditPopup(menuItem)}
                          sx={{ color: 'green' }}
                        >
                          <EditIcon />
                        </IconButton>
                        <IconButton
                          onClick={() => handleDelete(menuItem.menuItemId)}
                          sx={{ color: 'error.main' }}
                        >
                          <DeleteIcon />
                        </IconButton>
                      </TableCell>
                      {!isSubMenu && (
                        <TableCell align="center">
                          <IconButton
                            onClick={() => handleSubMenuClick(menuItem.menuItemId)}
                            sx={{ color: '#0B4C6A' }}
                          >
                            <MenuIcon />
                          </IconButton>
                        </TableCell>
                      )}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>

          <Grid container spacing={2} mt={4}>
            <Grid item xs={12} md={6}>
              <Button
                variant="outlined"
                onClick={handleMenuOpen}
                sx={{ textTransform: 'none' }}
              >
                Manage Columns
              </Button>
              <Menu
                anchorEl={anchorEl}
                open={Boolean(anchorEl)}
                onClose={handleMenuClose}
              >
                {Object.keys(visibleColumns).map((column) => (
                  <MenuItem key={column} onClick={() => toggleColumn(column)}>
                    <Checkbox checked={visibleColumns[column]} />
                    {column.charAt(0).toUpperCase() + column.slice(1).toLowerCase()}
                  </MenuItem>
                ))}
              </Menu>
            </Grid>

            <Grid item xs={12} md={6} sx={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button
                variant="outlined"
                onClick={handlePageMenuOpen}
                sx={{ textTransform: 'none' }}
              >
                <ExcelIcon />
              </Button>
              <Menu
                anchorEl={pageAnchorEl}
                open={Boolean(pageAnchorEl)}
                onClose={handlePageMenuClose}
              >
                {[1, 5, 10, 20, 50].map((number) => (
                  <MenuItem
                    key={number}
                    onClick={() => handleRecordsPerPageChange(number)}
                  >
                    <Box sx={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                      <span>{number}</span>
                      {recordsPerPage === number && (
                        <CheckCircleIcon sx={{ ml: 'auto', color: 'success.main' }} />
                      )}
                    </Box>
                  </MenuItem>
                ))}
              </Menu>
            </Grid>
          </Grid>

          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
            <Pagination
              count={totalPages}
              page={currentPage}
              onChange={handlePageChange}
              color="primary"
            />
          </Box>

          <Modal
            open={showAddEditPopup}
            onClose={handleClose}
            aria-labelledby="modal-modal-title"
            aria-describedby="modal-modal-description"
          >
            <Box sx={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: '80%',
              maxWidth: 800,
              bgcolor: 'background.paper',
              boxShadow: 24,
              p: 4,
              borderRadius: 1
            }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                <Typography id="modal-modal-title" variant="h6" component="h2">
                  {isEditing ? "Edit Menu Item" : "Add New Menu Item"}
                </Typography>
                <IconButton onClick={handleClose}>
                  <CloseIcon />
                </IconButton>
              </Box>

              <Box component="form" onSubmit={handleSubmit}>
                <Grid container spacing={2}>
                  <Grid item xs={6}>
                    <TextField
                      fullWidth
                      label="Menu ID*"
                      name="menuId"
                      value={0}
                      InputProps={{
                        readOnly: true,
                      }}
                      variant="standard"
                    />
                  </Grid>
                  
                  <Grid item xs={6}>
                    <TextField
                      fullWidth
                      label="Menu Item Name*"
                      name="menuItemDesc"
                      value={currentMenuItem.menuItemDesc || ""}
                      onChange={handleInputChange}
                      required
                    />
                  </Grid>

                  <Grid item xs={6}>
                    <TextField
                      fullWidth
                      label="Sequence"
                      name="itemSeq"
                      type="number"
                      value={currentMenuItem.itemSeq || ""}
                      onChange={handleInputChange}
                    />
                  </Grid>
                  
                  <Grid item xs={6}>
                    <TextField
                      fullWidth
                      label="Module Name"
                      name="moduleName"
                      value={currentMenuItem.moduleName || ""}
                      onChange={handleInputChange}
                    />
                  </Grid>

                  <Grid item xs={6}>
                    <TextField
                      fullWidth
                      label="Menu Action Link"
                      name="main_menu_action_name"
                      value={currentMenuItem.main_menu_action_name || ""}
                      onChange={handleInputChange}
                    />
                  </Grid>
                  
                  <Grid item xs={6}>
                    <TextField
                      fullWidth
                      label="Menu Icon Name"
                      name="main_menu_icon_name"
                      value={currentMenuItem.main_menu_icon_name || ""}
                      onChange={handleInputChange}
                      placeholder="e.g., fa-home"
                    />
                  </Grid>

                  <Grid item xs={12}>
                    <FormControl fullWidth>
                      <InputLabel>Status</InputLabel>
                      <Select
                        name="status"
                        value={currentMenuItem.status ? "true" : "false"}
                        onChange={handleInputChange}
                        label="Status"
                      >
                        <MenuItem value="true">Enable</MenuItem>
                        <MenuItem value="false">Disable</MenuItem>
                      </Select>
                    </FormControl>
                  </Grid>
                </Grid>

                <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 3 }}>
                  <Button onClick={handleClose} sx={{ mr: 2 }}>Cancel</Button>
                  <Button type="submit" variant="contained">
                    {isEditing ? "UPDATE" : "ADD"}
                  </Button>
                </Box>
              </Box>
            </Box>
          </Modal>
        </Container>
      )}
    </Box>
  );
}

export default MenuMaintenance;