import React, { useEffect, useMemo, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TablePagination,
  CircularProgress,
  Grid,
  Box,
  Button,
  FormControl,
  Typography,
  TextField,
  MenuItem,
  InputAdornment,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import {
  useDeleteCategoryMutation,
  useGetAllCategoryNameQuery,
  useGetAllMainCategoryQuery,
  useGetCoursingQuery,
  useGetDepartmentQuery,
  useGetTaxQuery,
} from "../../../Api/attoDeskApi";
import {
  ICategory,
  ICoursing,
  IDepartment,
  ITaxes,
} from "../../../Api/Interface/api.interface";
import DeletePopup from "../../../Components/Delete/DeletePopup";
import { useNotifier } from "../../../Core/Notifier";
import NewPopUpCategory from "./NewPopUpCategory";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { Dayjs } from "dayjs";
import { RooleType } from "../../../Core/Enum/enum";
import SearchIcon from "@mui/icons-material/Search";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import FilterAltIcon from "@mui/icons-material/FilterAlt";
import { useStyles } from "../../../theme/styles";
import AlertPopUp from "../../../Components/AlertPopUp/AlertPopup";
import useDebounce from "../../../Components/SearchDebonce/useDebounce";
import { setSelectionRange } from "@testing-library/user-event/dist/utils";

const CategoryTable: React.FC<{ onDataLoaded: () => void }> = ({
  onDataLoaded,
}) => {
  const classes = useStyles();
  const getFormattedDate = (createDate: Dayjs | null): string => {
    return createDate ? createDate.format('YYYY-MM-DD') : '';
  };
  const { showErrorMessage, showMessage } = useNotifier();
  const [searchQuery, setSearchQuery] = useState("");
  const [currentSearchQuery, setCurrentSearchQuery] = useState("");
  const [selectedCoursingId, setSelectedCousingId] = useState<string>("");
  const [selectedProductTaxId, setSelectedProductTaxId] = useState<string>("");
  const [selectedProductRoles, setSelectedProducRoles] = useState<string[]>([]);
  const [selectedIsActive, setSelectedProductIsActive] =
    useState<boolean>(true);
    const [selectedIsLooping, setSelectedIsLooping] =
    useState<string>("");
  const debouncedSearchQuery = useDebounce(searchQuery, 300);
  const [selectedDepartment, setSelectedDepartment] = useState<string>("");
  const [startDate, setStartDate] = useState<Dayjs | null>(null);
  const [endDate, setEndDate] = useState<Dayjs | null>(null);
  const [createDate, setCreateDate] = useState<Dayjs | null>(null);
  const startDateAsDate = startDate?.toDate() || null;
  const endDateAsDate = endDate?.toDate() || null;
  const [isPaperVisible, setIsPaperVisible] = useState(false);
  
  const { data, isLoading, isError, refetch } = useGetAllMainCategoryQuery({
    departmentId: selectedDepartment,
    coursingId: selectedCoursingId,
    roleId: selectedProductRoles,
    taxeId: selectedProductTaxId,
    createdDateStart: startDateAsDate as Date,
    createdDateEnd: endDateAsDate as Date,
    searchText: currentSearchQuery,
    numberOfLength: null,
    isActive: true,
    categoryIsLooping: selectedIsLooping,
    createdDate: getFormattedDate(createDate),
  });
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);
  const [selectedCoursing, setSelectedCoursing] = useState<ICategory | null>(
    null
  );
  const [openDialog, setOpenDialog] = useState(false);
  const [openDeleteCategory, setOpenDeleteCategory] = useState(false);
  const [coursingToDelete, setCoursingToDelete] = useState<ICategory | null>(
    null
  );
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [alertMessage, setAlertMessage] = useState("");

  const { data: departmentData, isLoading: departmentLoading } =
    useGetDepartmentQuery({
      searchText: "",
    });
  const { data: coursingData, isLoading: coursingLoading } =
    useGetCoursingQuery({
      searchText: "",
    });
  const { data: taxData, isLoading: taxLoading } = useGetTaxQuery({
    searchText: "",
  });
  const { data: categoryData, isLoading: categoryLoading } =
    useGetAllCategoryNameQuery();

  const departmentList = useMemo(() => {
    return departmentData?.data as IDepartment[];
  }, [departmentData?.data]);

  const coursingList = useMemo(() => {
    return coursingData?.data as ICoursing[];
  }, [coursingData?.data]);

  const taxList = useMemo(() => {
    return taxData?.data as ITaxes[];
  }, [taxData?.data]);

  const categoryList = useMemo(() => {
    return categoryData?.data as ICategory[];
  }, [categoryData?.data]);

  const categoryMap = useMemo(() => {
    const map = new Map();
    categoryList?.forEach((printer) => {
      map.set(printer.id, printer.categoryName);
    });
    return map;
  }, [categoryList]);

  const departmentMap = useMemo(() => {
    const map = new Map();
    departmentList?.forEach((category) => {
      map.set(category.id, category.departmentName);
    });
    return map;
  }, [departmentList]);

  const coursingMap = useMemo(() => {
    const map = new Map();
    coursingList?.forEach((category) => {
      map.set(category.id, category.coursingName);
    });
    return map;
  }, [coursingList]);

  const taxMap = useMemo(() => {
    const map = new Map();
    taxList?.forEach((category) => {
      map.set(category.id, category.taxName);
    });
    return map;
  }, [taxList]);

  useEffect(() => {
    if (debouncedSearchQuery.length >= 4 || debouncedSearchQuery === "") {
      setCurrentSearchQuery(debouncedSearchQuery);
      refetch(); 
    }
  }, [debouncedSearchQuery]);

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleOpenDialog = (coursing: ICategory) => {
    setSelectedCoursing(coursing);
    setOpenDialog(true);
  };

  const handleCloseDialog = () => {
    setSelectedCoursing(null);
    setOpenDialog(false);
  };

  const handleOpenDeletePopup = (coursing: ICategory) => {
    setCoursingToDelete(coursing);
    setOpenDeleteCategory(true);
  };

  const handleCloseDeletePopup = () => {
    setCoursingToDelete(null);
    setOpenDeleteCategory(false);
  };

  const handleCoursing = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedValues = event.target.value;
    setSelectedCousingId(selectedValues);
  };

  const handleDepartment = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedValues = event.target.value;
    setSelectedDepartment(selectedValues);
  };

  const handleProductTax = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedValues = event.target.value;
    setSelectedProductTaxId(selectedValues);
  };

  const handleProductIsActive = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const selectedValue = event.target.checked; // Use `checked` for boolean values from checkboxes
    setSelectedProductIsActive(selectedValue);
  };

  const handleIsLooping = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const selectedValues = event.target.value;
    setSelectedIsLooping(selectedValues);
  };

  const handleStartDateChange = (newValue: Dayjs | null) => {
    setStartDate(newValue);
  };

  const handleCreateDateChange = (newValue: Dayjs | null) => {
    setCreateDate(newValue);
  };

  const handleEndDateChange = (newValue: Dayjs | null) => {
    setEndDate(newValue);
  };

  const handleProductRoals = (event: React.ChangeEvent<HTMLInputElement>) => {
    const {
      target: { value },
    } = event;
    setSelectedProducRoles(
      typeof value === "string" ? value.split(",") : value
    );
  };

  const [deleteCategory] = useDeleteCategoryMutation();
  const handleDelete = async (id: string) => {
    try {
      const response = await deleteCategory(id).unwrap();
      if (response.status) {
        showMessage(response.message);
        setOpenDeleteCategory(false);
      } else {
        setAlertMessage(response.message);
        setDeleteAlert(true);
      }
    } catch (error) {
      showErrorMessage("Failed to delete the category");
    }
  };

  const handleToggle = () => {
    setIsPaperVisible(!isPaperVisible);
  };

  useEffect(() => {
    if (!isLoading && !departmentLoading && !coursingLoading && !taxLoading) {
      onDataLoaded();
    }
  }, [isLoading, departmentLoading, coursingLoading, taxLoading, onDataLoaded]);

  if (isLoading || departmentLoading || coursingLoading || taxLoading) {
    return (
      <Box
        display="flex"
        justifyContent="center"
        alignItems="center"
        height="10vh"
      >
        <CircularProgress />
      </Box>
    );
  }

  const coursings: ICategory[] = Array.isArray(data?.data)
    ? (data?.data as ICategory[])
    : [];

  const resetFields = () => {
    setSelectedDepartment("");
    setSelectedCousingId("");
    setSelectedProductTaxId("");
    setSelectedIsLooping("");
    setSelectedProducRoles([]);
    setStartDate(null);
    setEndDate(null);
    setSelectedProductIsActive(true);
    setCreateDate(null);
  };

  const handleSearch = () => {
    setCurrentSearchQuery(searchQuery);
  };

  const resetSearchFields = () => {
    setSearchQuery("");
    setCurrentSearchQuery("");
    refetch();
  };

  return (
    <Box>
      <Grid container spacing={2} display={"flex"} justifyContent={"flex-end"}>
        {/* <Grid
          item
          lg={4}
          md={6}
          sm={12}
          xs={12}
          sx={{ display: "flex", justifyContent: "flex-end", my: 2 }}
        >
          <Button
            variant="contained"
            startIcon={<FilterAltIcon />}
            sx={{
              backgroundColor: appColor.blue[100],
              textTransform: "none",
              boxShadow: "none",
              "&:hover": {
                backgroundColor: appColor.blue[100],
                boxShadow: "none",
              },
              "&:active": {
                backgroundColor: appColor.blue[100],
                boxShadow: "none",
              },
            }}
            onClick={handleToggle}
          >
            {isPaperVisible ? "Close Filter" : "Open Filter"}
          </Button>
        </Grid> */}
      </Grid>
      {isPaperVisible && (
        <>
          <Paper
            sx={{
              borderRadius: 2,
              maxWidth: "100%",
              p: 2,
              py: 5,
            }}
          >
            <Grid container spacing={2}>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Product Department
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1, width: "100%" }}
                      value={selectedDepartment || ""}
                      onChange={handleDepartment}
                      InputLabelProps={{ shrink: true }}
                    >
                      <MenuItem value="" style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      {departmentList &&
                        departmentList.map((department) => (
                          <MenuItem key={department.id} value={department.id}>
                            {department.departmentName}
                          </MenuItem>
                        ))}
                    </TextField>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Product Coursing
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1, width: "100%" }}
                      value={selectedCoursingId || ""}
                      onChange={handleCoursing}
                      InputLabelProps={{ shrink: true }}
                    >
                      <MenuItem value="" style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      {coursingList &&
                        coursingList.map((coursing) => (
                          <MenuItem key={coursing.id} value={coursing.id}>
                            {coursing.coursingName}
                          </MenuItem>
                        ))}
                    </TextField>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Product Tax
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1, width: "100%" }}
                      value={selectedProductTaxId || ""}
                      onChange={handleProductTax}
                      InputLabelProps={{ shrink: true }}
                    >
                      <MenuItem value="" style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      {taxList &&
                        taxList.map((tax) => (
                          <MenuItem key={tax.id} value={tax.id}>
                            {tax.taxName}
                          </MenuItem>
                        ))}
                    </TextField>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Product Roles
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ width: "100%" }}
                      SelectProps={{
                        multiple: true,
                        native: false,
                      }}
                      InputLabelProps={{ shrink: true }}
                      value={selectedProductRoles || ""}
                      onChange={handleProductRoals}
                    >
                      {Object.entries(RooleType).map(([key, value], index) => (
                        <MenuItem key={index} value={value}>
                          {key}
                        </MenuItem>
                      ))}
                      {Object.keys(RooleType).length === 0 && (
                        <MenuItem value="" style={{ color: "gray" }}>
                          Select an option
                        </MenuItem>
                      )}
                    </TextField>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Looping
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1, width: "100%" }}
                      value={selectedIsLooping || ""}
                      onChange={handleIsLooping}
                      InputLabelProps={{ shrink: true }}
                    >
                      <MenuItem value="" style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      <MenuItem value="1">Yes</MenuItem>
                      <MenuItem value="0">No</MenuItem>
                    </TextField>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Create Date
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                      <DatePicker
                        onChange={handleCreateDateChange}
                        value={createDate}
                        slotProps={{
                          textField: {
                            size: "small",
                            sx: { width: "100%" },
                            InputProps: {
                              sx: { fontSize: 14 },
                            },
                            InputLabelProps: {
                              sx: { fontSize: 14 },
                            },
                          },
                        }}
                      />
                    </LocalizationProvider>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Start Date
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                      <DatePicker
                        onChange={handleStartDateChange}
                        value={startDate}
                        slotProps={{
                          textField: {
                            size: "small",
                            sx: { width: "100%" },
                            InputProps: {
                              sx: { fontSize: 14 },
                            },
                            InputLabelProps: {
                              sx: { fontSize: 14 },
                            },
                          },
                        }}
                      />
                    </LocalizationProvider>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={2} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      End Date
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                      <DatePicker
                       onChange={handleEndDateChange}
                       value={endDate}
                        slotProps={{
                          textField: {
                            size: "small",
                            sx: { width: "100%" },
                            InputProps: {
                              sx: { fontSize: 14 },
                            },
                            InputLabelProps: {
                              sx: { fontSize: 14 },
                            },
                          },
                        }}
                      />
                    </LocalizationProvider>
                  </Grid>
                </Grid>
              </Grid>
              {/* <Grid item lg={3} md={12} sm={12} xs={12}>
                <Grid container>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Product Active
                    </Typography>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1, width: "100%" }}
                      SelectProps={{ native: true }}
                      value={selectedIsActive}
                      onChange={handleProductIsActive}
                      InputLabelProps={{ shrink: true }}
                    >
                      <MenuItem value="1">Yes</MenuItem>
                      <MenuItem value="0">No</MenuItem>
                    </TextField>
                  </Grid>
                </Grid>
              </Grid> */}

              <Grid item lg={12} md={12} sm={12} xs={12}>
                <Box display="flex" justifyContent="flex-end">
                  <Button
                    variant="contained"
                    startIcon={<RestartAltIcon />}
                    className={classes.resetButton}
                    onClick={resetFields}
                  >
                    Reset
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </Paper>
          <Box sx={{ height: "25px" }} />
        </>
      )}
      <Paper
        sx={{
          borderRadius: 2,
          maxWidth: "100%",
          p: 2,
        }}
      >
        <Grid
          container
          spacing={2}
          display={"flex"}
          justifyContent={"flex-end"}
        >
          <Grid
            item
            lg={3}
            md={6}
            sm={12}
            xs={12}
            sx={{ display: "flex", justifyContent: "flex-end", my: 2 }}
          >
            <TextField
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
              fullWidth
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search Category Name"
              sx={{ width: "100%" }}
              InputLabelProps={{
                sx: {
                  fontSize: 14,
                },
              }}
              size="small"
            />
            {/* <Box m={0.5}></Box>
            <Button
              variant="contained"
              className={classes.searchButton}
              onClick={handleSearch}
            >
              <SearchIcon />
            </Button>
            <Box m={0.5}></Box>
            <Button
              variant="contained"
              className={classes.resetButton}
              onClick={resetSearchFields}
            >
              <RestartAltIcon />
            </Button> */}
          </Grid>

          <Grid
            item
            sx={{ display: "flex", justifyContent: "flex-end", my: 2 }}
          >
            <Button
              variant="contained"
              startIcon={<FilterAltIcon />}
              className={classes.searchButton}
              onClick={handleToggle}
            >
              {isPaperVisible ? "Close Filter" : "Open Filter"}
            </Button>
          </Grid>
        </Grid>
        <TableContainer className={classes.tableContainer}>
          <Table className={classes.table}>
            <TableHead>
              <TableRow className={classes.tableHeaderRow}>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>#</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Category Name</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Perent</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Active</strong>
                </TableCell>
                {/* <TableCell className={classes.tableHeaderCell}>
                  <strong>Looping</strong>
                </TableCell> */}
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Department</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCellRight}>
                  <strong>Actions</strong>
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {isError || coursings.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={20} align="center">
                    {isError ? "Error fetching data" : "No data available"}
                  </TableCell>
                </TableRow>
              ) : (
                coursings
                  .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                  .map((row: ICategory, index) => (
                    <TableRow
                      key={row.id}
                      sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                    >
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {page * rowsPerPage + index + 1}
                      </TableCell>
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {row.categoryName}
                      </TableCell>
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {row.parent_ids
                          ?.map((id) => categoryMap.get(id) || " ")
                          .join(" → ")}
                      </TableCell>
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {row.isActive ? "Active" : "Inactive"}
                      </TableCell>
                      {/* <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {row.categoryIsLooping ? "Yes" : "No"}
                      </TableCell> */}
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {departmentMap.get(row.departmentId) || ""}
                      </TableCell>
                      <TableCell>
                        <Grid
                          container
                          spacing={1}
                          sx={{ display: "flex", justifyContent: "flex-end" }}
                        >
                          <Grid item>
                            <Button
                              onClick={() => handleOpenDialog(row)}
                              className={classes.actionsButton}
                            >
                              <EditIcon sx={{ p: "2px", color: "green" }} />
                              Edit
                            </Button>
                          </Grid>
                          <Grid item>
                            <Button
                              onClick={() => handleOpenDeletePopup(row)}
                              className={classes.actionsButton}
                            >
                              <DeleteIcon sx={{ p: "2px", color: "green" }} />
                              Delete
                            </Button>
                          </Grid>
                        </Grid>
                      </TableCell>
                    </TableRow>
                  ))
              )}
            </TableBody>
          </Table>

          <TablePagination
            rowsPerPageOptions={[5, 10, 25]}
            component="div"
            count={coursings.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
            className={classes.tablePagination}
          />
        </TableContainer>
        {selectedCoursing && (
          <NewPopUpCategory
            openModel={openDialog}
            handleCloseDialog={handleCloseDialog}
            data={selectedCoursing}
          />
        )}
        {coursingToDelete && (
          <DeletePopup
            open={openDeleteCategory}
            handleCloseDelete={handleCloseDeletePopup}
            onConfirm={async () => {
              await handleDelete(coursingToDelete.id.toString());
            }}
            title="Delete Category"
            content={`Are you sure you want to delete "${coursingToDelete.categoryName}"?`}
          />
        )}

        <AlertPopUp
          open={deleteAlert}
          onCloseAlert={setDeleteAlert}
          message={alertMessage}
        />
      </Paper>
    </Box>
  );
};

export default CategoryTable;
