import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { 
  getSubmenuItems, 
  addSubmenuItem,
  updateSubmenuItem,
  deleteSubmenuItem
} from '../../../ApiServices/menumaintananceapi';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow, 
  Paper,
  Button,
  TextField,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  MenuItem,
  Select,
  IconButton,
  Typography,
  Box,
  CircularProgress
} from "@mui/material";
import { 
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  MoreVert as MoreVertIcon
} from "@mui/icons-material";
import { toast } from "react-toastify";

const SubMenuMaintenance = () => {
  const { menuItemId } = useParams();
  const [subMenus, setSubMenus] = useState([]);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [currentItem, setCurrentItem] = useState({ 
    menuItemId: "",
    menuItemDesc: "",
    itemSeq: "",
    moduleName: "",
    main_menu_action_name: "#",
    status: "Enable",
    main_menu_icon_name: "fa-circle"
  });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    fetchSubMenus();
  }, [menuItemId]);

  const fetchSubMenus = async () => {
    setIsLoading(true);
    try {
      const data = await getSubmenuItems(menuItemId);
      setSubMenus(data);
    } catch (err) {
      toast.error("Failed to fetch submenu items");
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleAdd = async () => {
    try {
      const addedItem = await addSubmenuItem(menuItemId, currentItem);
      setSubMenus([...subMenus, addedItem]);
      resetForm();
      setShowAddModal(false);
      toast.success("Submenu added successfully!");
    } catch (err) {
      toast.error(err.message || "Failed to add submenu");
    }
  };

  const handleEdit = (item) => {
    setCurrentItem({
      ...item,
      status: item.status ? "Enable" : "Disable"
    });
    setShowEditModal(true);
  };

  const handleUpdate = async () => {
    try {
      const updatedItem = await updateSubmenuItem(currentItem.menuItemId, currentItem);
      setSubMenus(subMenus.map(item => 
        item.menuItemId === updatedItem.menuItemId ? updatedItem : item
      ));
      resetForm();
      setShowEditModal(false);
      toast.success("Submenu updated successfully!");
    } catch (err) {
      toast.error(err.message || "Failed to update submenu");
    }
  };

  const handleDelete = async (id) => {
    if (window.confirm("Are you sure you want to delete this submenu?")) {
      try {
        await deleteSubmenuItem(id);
        setSubMenus(subMenus.filter(item => item.menuItemId !== id));
        toast.success("Submenu deleted successfully!");
      } catch (err) {
        toast.error(err.message || "Failed to delete submenu");
      }
    }
  };

  const resetForm = () => {
    setCurrentItem({ 
      menuItemId: "",
      menuItemDesc: "",
      itemSeq: "",
      moduleName: "",
      main_menu_action_name: "#",
      status: "Enable",
      main_menu_icon_name: "fa-circle"
    });
  };

  return (
    <Box sx={{ p: 4 }}>
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        mb: 4 
      }}>
        <Typography variant="h4" component="h2">
          Sub-Menus for Menu ID: {menuItemId}
        </Typography>
        <Button 
          variant="contained" 
          startIcon={<AddIcon />}
          onClick={() => setShowAddModal(true)}
        >
          ADD NEW
        </Button>
      </Box>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>No.</TableCell>
              <TableCell>Sub-Menu Item Name</TableCell>
              <TableCell>ID</TableCell>
              <TableCell>Sequence</TableCell>
              <TableCell>Module Name</TableCell>
              <TableCell>Menu Action Link</TableCell>
              <TableCell>Status</TableCell>
              <TableCell>Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {isLoading ? (
              <TableRow>
                <TableCell colSpan={8} align="center">
                  <CircularProgress />
                </TableCell>
              </TableRow>
            ) : subMenus.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} align="center">
                  No submenus found
                </TableCell>
              </TableRow>
            ) : (
              subMenus.map((item, index) => (
                <TableRow key={item.menuItemId}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>{item.menuItemDesc}</TableCell>
                  <TableCell>{item.menuItemId}</TableCell>
                  <TableCell>{item.itemSeq}</TableCell>
                  <TableCell>{item.moduleName}</TableCell>
                  <TableCell>{item.main_menu_action_name}</TableCell>
                  <TableCell>{item.status ? "Enable" : "Disable"}</TableCell>
                  <TableCell>
                    <IconButton onClick={() => handleEdit(item)}>
                      <EditIcon />
                    </IconButton>
                    <IconButton onClick={() => handleDelete(item.menuItemId)}>
                      <DeleteIcon color="error" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Add Submenu Modal */}
      <Dialog open={showAddModal} onClose={() => setShowAddModal(false)}>
        <DialogTitle>Add Submenu</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
            <TextField
              label="Sub-Menu Item Name"
              value={currentItem.menuItemDesc}
              onChange={(e) => setCurrentItem({...currentItem, menuItemDesc: e.target.value})}
              required
              fullWidth
              margin="normal"
            />
            <TextField
              label="Sequence"
              type="number"
              value={currentItem.itemSeq}
              onChange={(e) => setCurrentItem({...currentItem, itemSeq: e.target.value})}
              required
              fullWidth
              margin="normal"
            />
            <TextField
              label="Module Name"
              value={currentItem.moduleName}
              onChange={(e) => setCurrentItem({...currentItem, moduleName: e.target.value})}
              fullWidth
              margin="normal"
            />
            <TextField
              label="Menu Action Link"
              value={currentItem.main_menu_action_name}
              onChange={(e) => setCurrentItem({...currentItem, main_menu_action_name: e.target.value})}
              fullWidth
              margin="normal"
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowAddModal(false)}>CANCEL</Button>
          <Button onClick={handleAdd} variant="contained">ADD</Button>
        </DialogActions>
      </Dialog>

      {/* Edit Submenu Modal */}
      <Dialog open={showEditModal} onClose={() => setShowEditModal(false)}>
        <DialogTitle>Update Sub Menu Maintenance</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
            <TextField
              label="Menu ID"
              value={menuItemId}
              disabled
              fullWidth
              margin="normal"
            />
            <TextField
              label="Menu Item Name"
              value={currentItem.menuItemDesc}
              onChange={(e) => setCurrentItem({...currentItem, menuItemDesc: e.target.value})}
              required
              fullWidth
              margin="normal"
            />
            <TextField
              label="Sequence"
              type="number"
              value={currentItem.itemSeq}
              onChange={(e) => setCurrentItem({...currentItem, itemSeq: e.target.value})}
              required
              fullWidth
              margin="normal"
            />
            <TextField
              label="Module Name"
              value={currentItem.moduleName}
              onChange={(e) => setCurrentItem({...currentItem, moduleName: e.target.value})}
              fullWidth
              margin="normal"
            />
            <TextField
              label="Menu Action Link"
              value={currentItem.main_menu_action_name}
              onChange={(e) => setCurrentItem({...currentItem, main_menu_action_name: e.target.value})}
              fullWidth
              margin="normal"
            />
            <Select
              value={currentItem.status}
              onChange={(e) => setCurrentItem({...currentItem, status: e.target.value})}
              fullWidth
              margin="dense"
            >
              <MenuItem value="Enable">Enable</MenuItem>
              <MenuItem value="Disable">Disable</MenuItem>
            </Select>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowEditModal(false)}>CANCEL</Button>
          <Button onClick={handleUpdate} variant="contained">UPDATE</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SubMenuMaintenance;
