import React, { useEffect, useMemo, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TablePagination,
  CircularProgress,
  Grid,
  Box,
  Button,
  InputAdornment,
  TextField,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import {
  useDeleteCategoryMutation,
  useGetAllCategoryNameQuery,
  useGetProductSubCategoryQuery,
} from "../../../Api/attoDeskApi";
import { ICategory, ISubCategory } from "../../../Api/Interface/api.interface";
import NewPopUpProductCategory from "./NewPopUpProductCategory";
import DeletePopup from "../../../Components/Delete/DeletePopup";
import { useNotifier } from "../../../Core/Notifier";
import SearchIcon from "@mui/icons-material/Search";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import { useStyles } from "../../../theme/styles";
import AlertPopUp from "../../../Components/AlertPopUp/AlertPopup";

const ComponentTable: React.FC<{ onDataLoaded: () => void }> = ({
  onDataLoaded,
}) => {
  const classes = useStyles();
  const { showErrorMessage, showMessage } = useNotifier();
  const [searchQuery, setSearchQuery] = useState("");
  const [currentSearchQuery, setCurrentSearchQuery] = useState("");
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);
  const [selectedCoursing, setSelectedCoursing] = useState<ISubCategory | null>(
    null
  );
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [alertMessage, setAlertMessage] = useState("");

  const { data: categoryData, isLoading: categoryLoading } =
    useGetAllCategoryNameQuery();

  const [openDialog, setOpenDialog] = useState(false);
  const [openDeleteCategory, setOpenDeleteCategory] = useState(false);
  const [coursingToDelete, setCoursingToDelete] = useState<ISubCategory | null>(
    null
  );

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

  const { data, isLoading, isError, refetch } = useGetProductSubCategoryQuery({
    searchText: currentSearchQuery,
    isActive: null,
  });

  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 handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

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

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

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

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

  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 product category");
    }
  };

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

  if (isLoading || categoryLoading)
    return (
      <Box
        display="flex"
        justifyContent="center"
        alignItems="center"
        height="10vh"
      >
        <CircularProgress />
      </Box>
    );

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

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

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

  return (
    <Box>
      <Paper
        sx={{
          borderRadius: 2,
          maxWidth: "100%",
          p: 2,
        }}
      >
        <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 }}
          >
            <TextField
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
              fullWidth
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search Department 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={resetFields}
            >
              <RestartAltIcon />
            </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>Name</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Category</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Main Active</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Active</strong>
                </TableCell>
                <TableCell className={classes.tableHeaderCell}>
                  <strong>Description</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: ISubCategory, 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.subIsMain ? "Active" : "Inactive"}
                      </TableCell>
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {row.isActive ? "Active" : "Inactive"}
                      </TableCell>
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tableCell}
                      >
                        {row.subCatDescription}
                      </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 && (
          <NewPopUpProductCategory
            openModel={openDialog}
            handleCloseDialog={handleCloseDialog}
            data={selectedCoursing}
          />
        )}
      </Paper>
      {coursingToDelete && (
        <DeletePopup
          open={openDeleteCategory}
          handleCloseDelete={handleCloseDeletePopup}
          onConfirm={async () => {
            await handleDelete(coursingToDelete.id.toString());
          }}
          title="Delete Product Category"
          content={`Are you sure you want to delete "${coursingToDelete.categoryName}"?`}
        />
      )}

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

export default ComponentTable;
