import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  Box,
  Button,
  Card,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  ImageList,
  ImageListItem,
  MenuItem,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import AddIcon from "@mui/icons-material/Add";
import { styled } from "@mui/material/styles";
import Switch, { SwitchProps } from "@mui/material/Switch";
import CloseIcon from "@mui/icons-material/Close";
import { useFormik } from "formik";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import AppsIcon from "@mui/icons-material/Apps";
import {
  useCreateCategoryMutation,
  useGetAllMainCategoryQuery,
  useGetCoursingQuery,
  useGetDepartmentQuery,
  useGetLoopingTableQuery,
  useGetPrinterQuery,
  useGetSubCategoryByArrayQuery,
  useGetTaxQuery,
} from "../../../Api/attoDeskApi";
import { useNotifier } from "../../../Core/Notifier";
import {
  ICategory,
  ICategoryNew,
  ICoursing,
  IDepartment,
  ILoopingTable,
  IPrinter,
  ITaxes,
} from "../../../Api/Interface/api.interface";
import { appColor } from "../../../theme/appColor";
import {
  ItemServiceChargeType,
  LoopingConst,
  RooleType,
  SizeOfLevelType,
} from "../../../Core/Enum/enum";
import NewCoursing from "../../Coursing/Components/NewPopUpCoursing";
import NewTax from "../../Tax/Components/NewPopUpTax";
import NewDepartement from "../../Department/Components/NewPopUpDepartment";
import { HexColorPicker } from "react-colorful";
import ColorLensIcon from "@mui/icons-material/ColorLens";
import NewPopUpPrinter from "../../Printer/Components/NewPopUpPrinter";
import CustomSwitch from "../../../Components/Switch/CustomSwitch";
import { useStyles } from "../../../theme/styles";
import { uploadImage } from "../../../Components/UploadFile/upload";

const IOSSwitch = styled((props: SwitchProps) => (
  <Switch focusVisibleClassName=".Mui-focusVisible" disableRipple {...props} />
))(({ theme }) => ({
  width: 62,
  height: 34,
  padding: 0,
  "& .MuiSwitch-switchBase": {
    padding: 0,
    margin: 2,
    transitionDuration: "300ms",
    "&.Mui-checked": {
      transform: "translateX(28px)",
      color: "#fff",
      "& + .MuiSwitch-track": {
        backgroundColor: theme.palette.mode === "dark" ? "#2ECA45" : "#65C466",
        opacity: 1,
        border: 0,
      },
      "&.Mui-disabled + .MuiSwitch-track": {
        opacity: 0.5,
      },
    },
    "&.Mui-focusVisible .MuiSwitch-thumb": {
      color: "#33cf4d",
      border: "6px solid #fff",
    },
    "&.Mui-disabled .MuiSwitch-thumb": {
      color:
        theme.palette.mode === "light"
          ? theme.palette.grey[100]
          : theme.palette.grey[600],
    },
    "&.Mui-disabled + .MuiSwitch-track": {
      opacity: theme.palette.mode === "light" ? 0.7 : 0.3,
    },
  },
  "& .MuiSwitch-thumb": {
    boxSizing: "border-box",
    width: 30,
    height: 30,
  },
  "& .MuiSwitch-track": {
    borderRadius: 34 / 2,
    backgroundColor: theme.palette.mode === "light" ? "#757575" : "#39393D",
    opacity: 1,
    transition: theme.transitions.create(["background-color"], {
      duration: 500,
    }),
    "&::before, &::after": {
      content: '""',
      position: "absolute",
      top: "50%",
      transform: "translateY(-50%)",
      width: 16,
      height: 16,
    },
    "&::before": {
      backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16" viewBox="0 0 24 24"><path fill="${encodeURIComponent(
        theme.palette.getContrastText(theme.palette.primary.main)
      )}" d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"/></svg>')`, // Using SVG path for check
      left: 12,
    },
    "&::after": {
      backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16" viewBox="0 0 24 24"><path fill="${encodeURIComponent(
        theme.palette.getContrastText(theme.palette.primary.main)
      )}" d="M19,13H5V11H19V13Z" /></svg>')`, // Using SVG path for minus
      right: 12,
    },
  },
}));

const isPrinterArray = (data: any): data is IPrinter[] => {
  return (
    Array.isArray(data) &&
    data.every(
      (item) =>
        "id" in item && "printerName" in item && "printerDescription" in item
    )
  );
};

// Image imports
const img1 = require("../../../Images/img1.jpg");
const img2 = require("../../../Images/img2.jpg");
const img3 = require("../../../Images/img3.jpg");

const Expense: React.FC = () => {
  const classes = useStyles();
  const [newCategory, { isLoading }] = useCreateCategoryMutation();
  const { showErrorMessage, showMessage } = useNotifier();
  const [openPrinter, setOpenPrinter] = useState(false);
  const { data: categoryData } = useGetAllMainCategoryQuery({
    departmentId: "",
    coursingId: "",
    roleId: null,
    taxeId: "",
    createdDateStart: null,
    createdDateEnd: null,
    searchText: "",
    numberOfLength: 0,
    isActive: true,
    categoryIsLooping: null,
    createdDate: null
  });

  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(
    null
  );
  const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<
    number | null
  >(null);

  const [selectedSubToSubCategoryId, setSelectedSubToSubCategoryId] = useState<
    number | null
  >(null);

  const { data: subCategoryData, refetch: refetchSubCategories } =
    useGetSubCategoryByArrayQuery({
      parent_ids: selectedCategoryId ? [Number(selectedCategoryId)] : [],
    });

  const { data: subCategory2Data, refetch: refetchS2bCategories } =
    useGetSubCategoryByArrayQuery({
      parent_ids: selectedSubCategoryId
        ? [Number(selectedCategoryId), Number(selectedSubCategoryId)]
        : [],
    });
  const { data: departmentData, isLoading: departmentLoading } =
    useGetDepartmentQuery({
      searchText: "",
    });
  const { data: coursingData, isLoading: coursingLoading } =
    useGetCoursingQuery({
      searchText: "",
    });
  const { data: taxData, isLoading: taxLoading } = useGetTaxQuery({
    searchText: "",
  });
  const { data: printerData, isLoading: PrinterLoading } = useGetPrinterQuery({
    searchText: "",
  });
  const { data: loopingTabeData, isLoading: loopingTableLoading } =
    useGetLoopingTableQuery({
      searchText: "",
    });
  const [openDepartment, setOpenDepartment] = useState(false);
  const [openCoursing, setOpenCoursing] = useState(false);
  const [openTax, setOpenTax] = useState(false);
  const [selectedColor, setSelectedColor] = useState<string>("#FFFFFF");
  const [showColorPicker, setShowColorPicker] = useState(false);
  const colorPickerRef = useRef<HTMLDivElement>(null);

  const [openGallery, setOpenGallery] = useState(false);
  const [selectedImage, setSelectedImage] = useState<File | undefined>(
    undefined
  );
  const [isImageUploading, setIsImageUploading] = useState(false);

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

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

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

  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 loopingTableList = useMemo(() => {
    return loopingTabeData?.data as ILoopingTable[];
  }, [loopingTabeData?.data]);

  const printerList: IPrinter[] = useMemo(() => {
    if (!printerData || !isPrinterArray(printerData.data)) {
      return [];
    }
    return printerData.data;
  }, [printerData]);

  const formik = useFormik<ICategoryNew>({
    initialValues: {
      categoryName: "",
      departmentId: "",
      roleId: [],
      coursingId: "",
      servingSize: [],
      hidePos: false,
      hideOnlineOrder: false,
      hideKiosk: false,
      Conversational: false,
      itemServiceChargeId: "",
      itemServiceChargePrice: "",
      ageRestriction: false,
      excludeCheckTax: false,
      categoryPrinterIds: [],
      taxeId: "",
      categoryButtonColor: "",
      categoryIsLooping: false,
      categoryLoopingConstant: "",
      categoryImg: null,
      isActive: true,
      parent_ids: null,
      mainCatId: "",
    },
    onSubmit: async (values, { resetForm }) => {
      try {
        const formData = new FormData();
        let categoryImg: string | undefined;

        if (selectedImage) {
          setIsImageUploading(true);
          formData.append("categoryImg", selectedImage);
          categoryImg = (await uploadImage(selectedImage)) || "";
          setIsImageUploading(false);
        }

        const parent_ids = selectedSubToSubCategoryId
          ? [
              Number(selectedCategoryId),
              Number(selectedSubCategoryId),
              Number(selectedSubToSubCategoryId),
            ]
          : selectedSubCategoryId
          ? [Number(selectedCategoryId), Number(selectedSubCategoryId)]
          : selectedCategoryId
          ? [Number(selectedCategoryId)]
          : null;

        const temData = {
          categoryName: values.categoryName,
          departmentId: values.departmentId,
          roleId: values.roleId,
          coursingId: values.coursingId,
          servingSize: values.servingSize,
          hidePos: values.hidePos,
          hideOnlineOrder: values.hideOnlineOrder,
          hideKiosk: values.hideKiosk,
          Conversational: values.Conversational,
          itemServiceChargeId: values.itemServiceChargeId,
          itemServiceChargePrice: values.itemServiceChargePrice,
          ageRestriction: values.ageRestriction,
          excludeCheckTax: values.excludeCheckTax,
          categoryPrinterIds: values.categoryPrinterIds,
          taxeId: values.taxeId,
          categoryButtonColor: values.categoryButtonColor,
          categoryIsLooping: values.categoryIsLooping,
          categoryLoopingConstant: values.categoryLoopingConstant,
          isActive: values.isActive,
          categoryImg,
          ...(parent_ids && { parent_ids }),
        };

        const addCategoryResponse = await newCategory(temData).unwrap();
        if (!addCategoryResponse.status) {
          showErrorMessage(addCategoryResponse.message);
        } else {
          showMessage(addCategoryResponse.message);
          resetForm();
          setSelectedImage(undefined);
          setOpenGallery(false);
          if (selectedCategoryId) {
            refetchSubCategories();
          }
          setSelectedCategoryId(null);
          setSelectedSubCategoryId(null);
          setSelectedSubToSubCategoryId(null);
          setSelectedImage(undefined);
        }
      } catch (error) {
        showErrorMessage("Something went wrong");
      }
    },
  });

  const formValid = useMemo(() => {
    return formik.values.categoryName === "" ||
      formik.values.categoryName === undefined
      ? false
      : true;
  }, [formik]);

  const handleMainCategoryChange = (
    event: React.ChangeEvent<{ value: unknown }>
  ) => {
    const categoryId = event.target.value as number;
    setSelectedCategoryId(categoryId);
    setSelectedSubCategoryId(null);
    setSelectedSubToSubCategoryId(null);
    formik.setFieldValue("mainCatId", categoryId);

    const selectedCategory = categoryList.find(
      (category) => category.id == categoryId
    );

    // if (selectedCategory) {
    //   // Update Formik values for categoryIsLooping and categoryLoopingConstant
    //   formik.setFieldValue(
    //     "categoryIsLooping",
    //     selectedCategory.categoryIsLooping
    //   );
    //   formik.setFieldValue(
    //     "categoryLoopingConstant",
    //     selectedCategory.categoryLoopingConstant
    //   );
    // }
  };

  const handleSubCategoryChange = (
    event: React.ChangeEvent<{ value: unknown }>
  ) => {
    const subCategoryId = event.target.value as number;
    setSelectedSubCategoryId(subCategoryId);
    setSelectedSubToSubCategoryId(null);
  };

  const handleSubToSubCategoryChange = (
    event: React.ChangeEvent<{ value: unknown }>
  ) => {
    const selectedSubToSubCategoryId = event.target.value as number;
    setSelectedSubToSubCategoryId(selectedSubToSubCategoryId);
  };

  const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;

    if (files && files.length > 0) {
      const file = files[0];
      const validTypes = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
      const maxSize = 2048 * 1024;

      if (!validTypes.includes(file.type)) {
        showErrorMessage("The file must be an image (jpeg, png, jpg, gif).");
        setSelectedImage(undefined);
      } else if (file.size > maxSize) {
        showErrorMessage("The file must be smaller than 2 MB.");
        setSelectedImage(undefined);
      } else {
        setSelectedImage(file);
      }
    } else {
      setSelectedImage(undefined);
    }
  };

  const handleGallerySelection = (selectedImage: string) => {
    fetch(selectedImage)
      .then((res) => res.blob())
      .then((blob) => {
        const file = new File([blob], "image.jpg", { type: blob.type });
        setSelectedImage(file);
      });
    setOpenGallery(false);
  };

  const openGalleryDialog = () => {
    setOpenGallery(true);
  };

  const closeGalleryDialog = () => {
    setOpenGallery(false);
  };

  const galleryImages = [img2, img3, img2, img3, img2, img3];

  const handlePrinterToggle = (printerId: number) => {
    const { categoryPrinterIds } = formik.values;
    const updatedPrinterIds = categoryPrinterIds.includes(printerId)
      ? categoryPrinterIds.filter((id) => id !== printerId)
      : [...categoryPrinterIds, printerId];
    formik.setFieldValue("categoryPrinterIds", updatedPrinterIds);
  };


  const handleColorChange = (newColor: string) => {
    setSelectedColor(newColor);
    formik.setFieldValue("categoryButtonColor", newColor);
  };

  const toggleColorPicker = () => {
    setShowColorPicker(!showColorPicker);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        colorPickerRef.current &&
        !colorPickerRef.current.contains(event.target as Node)
      ) {
        setShowColorPicker(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

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

  const cancelFunction = () => {
    formik.resetForm();
    setSelectedImage(undefined);
    setOpenGallery(false);
    if (selectedCategoryId) {
      refetchSubCategories();
    }
    setSelectedCategoryId(null);
    setSelectedSubCategoryId(null);
    setSelectedSubToSubCategoryId(null);
  };

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container>
        <Grid item lg={12} md={12} sm={12} xs={12} className={classes.grid1}>
          <Card
            sx={{
              p: 2,
              width: "100%",
              boxShadow: "none",
              pb: 2,
            }}
          >
            <Grid container spacing={5}>
              <Grid
                item
                lg={12}
                md={12}
                sm={12}
                xs={12}
                sx={{ borderBottom: 1 }}
                className={classes.cardTitleGrid}
              >
                <Typography className={classes.cardTitleTypography}>
                  New Category
                </Typography>
              </Grid>

              <Grid item lg={6} md={6} sm={12} xs={12} py={2}>
                <Grid container direction="row" alignItems="center" spacing={2}>
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Name
                    </Typography>
                  </Grid>
                  <Grid item lg={9} md={9} sm={12} xs={12}>
                    <TextField
                      placeholder="Enter Category Name"
                      size="small"
                      {...formik.getFieldProps("categoryName")}
                      sx={{ width: "100%" }}
                      InputProps={{
                        sx: {
                          fontSize: 14,
                        },
                        inputProps: {
                          style: {
                            fontSize: 14,
                          },
                        },
                      }}
                      InputLabelProps={{
                        sx: {
                          fontSize: 14,
                        },
                      }}
                    />
                  </Grid>
                </Grid>

                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 1 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Main Category
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={9}
                    md={9}
                    sm={12}
                    xs={12}
                    display="flex"
                    alignItems="center"
                  >
                    <TextField
                      select
                      fullWidth
                      size="small"
                      sx={{ flexGrow: 1 }}
                      value={selectedCategoryId || ""}
                      onChange={handleMainCategoryChange}
                      InputLabelProps={{ shrink: true }}
                    >
                      <MenuItem value="" disabled style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      {categoryList &&
                        categoryList.map((category) => (
                          <MenuItem key={category.id} value={category.id}>
                            {category.categoryName}
                          </MenuItem>
                        ))}
                    </TextField>
                  </Grid>
                </Grid>

                {selectedCategoryId && subCategoryList.length > 0 && (
                  <Grid
                    container
                    direction="row"
                    alignItems="center"
                    spacing={2}
                    sx={{ mt: 1 }}
                  >
                    <Grid item lg={3} md={3} sm={12} xs={12}>
                      <Typography
                        variant="subtitle1"
                        className={classes.typography}
                      >
                        Sub Category
                      </Typography>
                    </Grid>
                    <Grid
                      item
                      lg={9}
                      md={9}
                      sm={12}
                      xs={12}
                      display="flex"
                      alignItems="center"
                    >
                      <TextField
                        select
                        fullWidth
                        size="small"
                        sx={{ flexGrow: 1 }}
                        value={
                          selectedSubCategoryId === null
                            ? ""
                            : selectedSubCategoryId
                        }
                        onChange={handleSubCategoryChange}
                        InputLabelProps={{ shrink: true }}
                      >
                        <MenuItem value="" disabled style={{ color: "gray" }}>
                          Select an option
                        </MenuItem>
                        {subCategoryList.map((subcategory) => (
                          <MenuItem key={subcategory.id} value={subcategory.id}>
                            {subcategory.categoryName}
                          </MenuItem>
                        ))}
                      </TextField>
                    </Grid>
                  </Grid>
                )}

                {selectedCategoryId &&
                  selectedSubCategoryId &&
                  subToSubCategoryList.length > 0 && (
                    <Grid
                      container
                      direction="row"
                      alignItems="center"
                      spacing={2}
                      sx={{ mt: 1 }}
                    >
                      <Grid item lg={3} md={3} sm={12} xs={12}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Sub-to-Sub Category
                        </Typography>
                      </Grid>
                      <Grid
                        item
                        lg={9}
                        md={9}
                        sm={12}
                        xs={12}
                        display="flex"
                        alignItems="center"
                      >
                        <TextField
                          select
                          fullWidth
                          size="small"
                          sx={{ flexGrow: 1 }}
                          value={
                            selectedSubToSubCategoryId === null
                              ? ""
                              : selectedSubToSubCategoryId
                          }
                          onChange={handleSubToSubCategoryChange}
                          InputLabelProps={{ shrink: true }}
                        >
                          <MenuItem value="" disabled style={{ color: "gray" }}>
                            Select an option
                          </MenuItem>
                          {subToSubCategoryList.map((subToSubcategory) => (
                            <MenuItem
                              key={subToSubcategory.id}
                              value={subToSubcategory.id}
                            >
                              {subToSubcategory.categoryName}
                            </MenuItem>
                          ))}
                        </TextField>
                      </Grid>
                    </Grid>
                  )}

                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Department
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={9}
                    md={9}
                    sm={12}
                    xs={12}
                    display="flex"
                    alignItems="center"
                  >
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1 }}
                      defaultValue=""
                      InputLabelProps={{ shrink: true }}
                      {...formik.getFieldProps("departmentId")}
                    >
                      <MenuItem value="" disabled style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      {departmentList &&
                        departmentList.map((department) => (
                          <MenuItem key={department.id} value={department.id}>
                            {department.departmentName}
                          </MenuItem>
                        ))}
                    </TextField>

                    {/* <Select
                        size="small"
                        fullWidth
                        className={classes.select}
                        defaultValue=""
                        {...formik.getFieldProps("departmentId")}
                      >
                        <MenuItem value="" disabled>
                          Select an MenuItem
                        </MenuItem>

                        {departmentList &&
                          departmentList.map((department) => (
                            <MenuItem key={department.id} value={department.id}>
                              {department.departmentName}
                            </MenuItem>
                          ))}
                      </Select> */}

                    <Button
                      variant="contained"
                      size="small"
                      sx={{ ml: 2 }}
                      className={classes.addButton}
                      onClick={() => {
                        setOpenDepartment(true);
                      }}
                    >
                      <AddIcon sx={{ fontSize: 30 }} />
                    </Button>
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Roles
                    </Typography>
                  </Grid>
                  <Grid item lg={9} md={9} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ width: "100%" }}
                      SelectProps={{
                        multiple: true,
                        native: false,
                      }}
                      defaultValue=""
                      InputLabelProps={{ shrink: true }}
                      {...formik.getFieldProps("roleId")}
                    >
                      {!formik.values.roleId.length && (
                        <MenuItem value="" disabled>
                          Select some option
                        </MenuItem>
                      )}
                      {Object.entries(RooleType).map(([key, value], index) => (
                        <MenuItem key={index} value={value}>
                          {key}
                        </MenuItem>
                      ))}
                    </TextField>
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Coursing
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={9}
                    md={9}
                    sm={12}
                    xs={12}
                    display="flex"
                    alignItems="center"
                  >
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1 }}
                      defaultValue=""
                      InputLabelProps={{ shrink: true }}
                      {...formik.getFieldProps("coursingId")}
                    >
                      <MenuItem value="" disabled style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      {coursingList &&
                        coursingList.map((coursing) => (
                          <MenuItem key={coursing.id} value={coursing.id}>
                            {coursing.coursingName}
                          </MenuItem>
                        ))}
                    </TextField>
                    <Button
                      variant="contained"
                      size="small"
                      sx={{ ml: 2 }}
                      className={classes.addButton}
                      onClick={() => {
                        setOpenCoursing(true);
                      }}
                    >
                      <AddIcon sx={{ fontSize: 30 }} />
                    </Button>
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Serving Size Levels
                    </Typography>
                  </Grid>
                  <Grid item lg={9} md={9} sm={12} xs={12}>
                    <TextField
                      select
                      size="small"
                      sx={{ width: "100%" }}
                      SelectProps={{
                        multiple: true,
                        native: false,
                      }}
                      defaultValue=""
                      InputLabelProps={{ shrink: true }}
                      {...formik.getFieldProps("servingSize")}
                    >
                      {!formik.values.servingSize.length && (
                        <MenuItem value="" disabled>
                          Select some option
                        </MenuItem>
                      )}
                      {Object.entries(SizeOfLevelType).map(
                        ([key, value], index) => (
                          <MenuItem key={index} value={value}>
                            {key}
                          </MenuItem>
                        )
                      )}
                    </TextField>
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Item Service Charge
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <TextField
                      select
                      size="small"
                      sx={{ width: "100%" }}
                      SelectProps={{
                        native: false,
                      }}
                      defaultValue=""
                      InputLabelProps={{ shrink: true }}
                      {...formik.getFieldProps("itemServiceChargeId")}
                    >
                      {!formik.values.itemServiceChargeId.length && (
                        <MenuItem value="" disabled>
                          Select some option
                        </MenuItem>
                      )}
                      {Object.entries(ItemServiceChargeType).map(
                        ([key, value], index) => (
                          <MenuItem key={index} value={value}>
                            {key}
                          </MenuItem>
                        )
                      )}
                    </TextField>
                  </Grid>
                  {formik.values.itemServiceChargeId == "1" && (
                    <>
                      <Grid item lg={2} md={2} sm={2} xs={2}>
                        <Typography
                          variant="subtitle1"
                          className={classes.typography}
                        >
                          Price
                        </Typography>
                      </Grid>
                      <Grid
                        item
                        lg={4}
                        md={4}
                        sm={4}
                        xs={4}
                        display="flex"
                        alignItems="center"
                      >
                        <TextField
                          placeholder="Enter Item Service Price"
                          size="small"
                          {...formik.getFieldProps("itemServiceChargePrice")}
                          sx={{ width: "100%" }}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </>
                  )}
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Hide in POS
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <CustomSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      formik={formik}
                      name="hidePos"
                    />
                  </Grid>
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Hide in Online Order
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <CustomSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      formik={formik}
                      name="hideOnlineOrder"
                    />
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Hide in Kiosk
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <CustomSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      formik={formik}
                      name="hideKiosk"
                    />
                  </Grid>
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Conversational
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <CustomSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      formik={formik}
                      name="Conversational"
                    />
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Age Restriction
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <CustomSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      formik={formik}
                      name="ageRestriction"
                    />
                  </Grid>
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Exclude Check Tax
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <CustomSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      formik={formik}
                      name="excludeCheckTax"
                    />
                  </Grid>
                </Grid>
              </Grid>

              <Grid item lg={6} md={6} sm={12} xs={12} py={2}>
                <Grid container direction="row" alignItems="center" spacing={2}>
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Printer
                    </Typography>
                  </Grid>
                  <Grid item lg={7} md={7} sm={12} xs={12}>
                    <Grid container spacing={2}>
                      {printerList.map((printer) => (
                        <Grid
                          item
                          lg={4}
                          md={12}
                          sm={12}
                          xs={12}
                          key={printer.id}
                        >
                          <Typography
                            variant="subtitle1"
                            className={classes.typography}
                          >
                            {printer.printerName}
                          </Typography>
                          <IOSSwitch
                            color="primary"
                            sx={{ mr: 2 }}
                            checked={formik.values.categoryPrinterIds.includes(
                              printer.id
                            )}
                            onChange={() => handlePrinterToggle(printer.id)}
                          />
                        </Grid>
                      ))}
                    </Grid>
                  </Grid>

                  <Grid item lg={2} md={2} sm={4} xs={4} textAlign={"end"}>
                    <Button
                      variant="contained"
                      size="small"
                      className={classes.addButton}
                      onClick={() => {
                        setOpenPrinter(true);
                      }}
                    >
                      <AddIcon sx={{ fontSize: 30 }} />
                    </Button>
                  </Grid>
                </Grid>

                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Taxes
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={9}
                    md={9}
                    sm={12}
                    xs={12}
                    display="flex"
                    alignItems="center"
                  >
                    <TextField
                      select
                      size="small"
                      sx={{ flexGrow: 1 }}
                      defaultValue=""
                      InputLabelProps={{ shrink: true }}
                      {...formik.getFieldProps("taxeId")}
                    >
                      <MenuItem value="" disabled style={{ color: "gray" }}>
                        Select an option
                      </MenuItem>
                      {taxList &&
                        taxList.map((tax) => (
                          <MenuItem key={tax.id} value={tax.id}>
                            {tax.taxName}
                          </MenuItem>
                        ))}
                    </TextField>
                    <Button
                      variant="contained"
                      size="small"
                      sx={{ ml: 2 }}
                      className={classes.addButton}
                      onClick={() => {
                        setOpenTax(true);
                      }}
                    >
                      <AddIcon sx={{ fontSize: 30 }} />
                    </Button>
                  </Grid>
                </Grid>

                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Select Image
                    </Typography>
                  </Grid>
                  <Grid item lg={9} md={9} sm={12} xs={12}>
                    <Box
                      sx={{
                        border: 1,
                        borderColor: "#d3d3d3",
                        borderRadius: 1,
                        display: "flex",
                        justifyContent: "flex-end",
                        alignItems: "center",
                        padding: 1,
                      }}
                    >
                      {selectedImage && (
                        <img
                          src={URL.createObjectURL(selectedImage)}
                          alt="Uploaded"
                          style={{
                            maxWidth: "200px",
                            maxHeight: "200px",
                            marginRight: "auto",
                          }}
                        />
                      )}
                      <div>
                        <input
                          accept="image/*"
                          style={{ display: "none" }}
                          id="icon-button-file-1"
                          type="file"
                          onChange={handleImageChange}
                        />
                        <label htmlFor="icon-button-file-1">
                          <Tooltip title="Select image from desk">
                            <IconButton
                              color="primary"
                              aria-label="upload picture"
                              component="span"
                            >
                              <CloudUploadIcon
                                sx={{ fontSize: 45, color: "green" }}
                              />
                            </IconButton>
                          </Tooltip>
                        </label>
                        <Tooltip title="Select image from our gallery">
                          <IconButton
                            color="primary"
                            aria-label="select from gallery"
                            component="span"
                            onClick={openGalleryDialog}
                          >
                            <AppsIcon sx={{ fontSize: 45, color: "green" }} />
                          </IconButton>
                        </Tooltip>
                      </div>

                      <Dialog open={openGallery} onClose={closeGalleryDialog}>
                        <DialogTitle
                          sx={{ backgroundColor: appColor.greenSmoke[40] }}
                        >
                          Select an Image from Gallery
                        </DialogTitle>
                        <DialogContent>
                          <ImageList
                            sx={{ width: 500, height: 450 }}
                            cols={3}
                            rowHeight={164}
                          >
                            {galleryImages.map((imagePath) => (
                              <ImageListItem key={imagePath}>
                                <img
                                  src={`${imagePath}?w=164&h=164&fit=crop&auto=format`}
                                  srcSet={`${imagePath}?w=164&h=164&fit=crop&auto=format&dpr=2 2x`}
                                  alt="Gallery"
                                  loading="lazy"
                                  onClick={() =>
                                    handleGallerySelection(imagePath)
                                  }
                                  style={{ cursor: "pointer" }}
                                />
                              </ImageListItem>
                            ))}
                          </ImageList>
                        </DialogContent>
                      </Dialog>
                    </Box>
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={12} xs={12}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Button Color
                    </Typography>
                  </Grid>
                  <Grid item lg={9} md={9} sm={12} xs={12}>
                    <Box
                      sx={{
                        border: 1,
                        borderColor: "#d3d3d3",
                        borderRadius: 1,
                        display: "flex",
                        justifyContent: "flex-start",
                        alignItems: "center",
                        padding: 1,
                      }}
                    >
                      <Grid container>
                        <Grid item lg={6} md={9} sm={12} xs={12}>
                          <Box
                            sx={{
                              marginLeft: 1,
                              display: "flex",
                              alignItems: "center",
                            }}
                          >
                            <Box
                              sx={{
                                width: 50,
                                height: 50,
                                // borderRadius: "50%",
                                backgroundColor: selectedColor,
                                marginLeft: 1,
                                border: "1px solid #d3d3d3",
                              }}
                            />
                          </Box>
                        </Grid>
                        <Grid
                          item
                          lg={6}
                          md={9}
                          sm={12}
                          xs={12}
                          alignItems={"flex-end"}
                          textAlign={"end"}
                        >
                          <IconButton
                            color="primary"
                            component="span"
                            onClick={toggleColorPicker}
                          >
                            <ColorLensIcon
                              sx={{ fontSize: 45, color: "green" }}
                            />
                          </IconButton>
                          {showColorPicker && (
                            <HexColorPicker
                              color={selectedColor}
                              onChange={handleColorChange}
                            />
                          )}
                        </Grid>
                      </Grid>
                    </Box>
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      className={classes.typography}
                    >
                      Active
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={3}
                    md={3}
                    sm={3}
                    xs={3}
                    display="flex"
                    alignItems="center"
                  >
                    <CustomSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      formik={formik}
                      name="isActive"
                    />
                  </Grid>
                </Grid>
                <Grid
                  container
                  direction="row"
                  alignItems="center"
                  spacing={2}
                  sx={{ mt: 2 }}
                >
                  <Grid item lg={3} md={3} sm={3} xs={3}>
                    <Typography
                      variant="subtitle1"
                      sx={{
                        fontWeight: 400,
                        fontSize: 14,
                      }}
                    >
                      Looping
                    </Typography>
                  </Grid>
                  <Grid
                    item
                    lg={2}
                    md={2}
                    sm={2}
                    xs={2}
                    display="flex"
                    alignItems="center"
                  >
                    <IOSSwitch
                      color="primary"
                      sx={{ mr: 2 }}
                      {...formik.getFieldProps("categoryIsLooping")}
                      checked={formik.values.categoryIsLooping}
                    />
                  </Grid>
                  {formik.values.categoryIsLooping == true && (
                    <>
                      <Grid item lg={2} md={2} sm={2} xs={2}>
                        <Typography
                          variant="subtitle1"
                          sx={{
                            fontWeight: 400,
                            fontSize: 14,
                          }}
                        >
                          Looping Category
                        </Typography>
                      </Grid>
                      <Grid
                        item
                        lg={5}
                        md={5}
                        sm={5}
                        xs={5}
                        display="flex"
                        alignItems="center"
                      >
                        <TextField
                          select
                          size="small"
                          sx={{ flexGrow: 1 }}
                          defaultValue=""
                          InputLabelProps={{ shrink: true }}
                          {...formik.getFieldProps("categoryLoopingConstant")}
                        >
                          <MenuItem value="" disabled style={{ color: "gray" }}>
                            Select an option
                          </MenuItem>
                          {loopingTableList &&
                            loopingTableList.map((department) => (
                              <MenuItem
                                key={department.id}
                                value={department.id}
                              >
                                {department.shortTableName}
                              </MenuItem>
                            ))}
                        </TextField>
                      </Grid>
                    </>
                  )}
                </Grid>
              </Grid>

              <Grid
                item
                lg={12}
                md={12}
                sm={12}
                xs={12}
                sx={{ display: "flex", justifyContent: "flex-end" }}
              >
                <Button
                  variant="contained"
                  startIcon={<CloseIcon />}
                  className={classes.cancelButton}
                  onClick={cancelFunction}
                >
                  Cancel
                </Button>
                <Box m={0.5}></Box>
                <Button
                  variant="contained"
                  startIcon={<SaveAltIcon />}
                  className={classes.saveButton}
                  onClick={() => formik.handleSubmit()}
                  disabled={!formValid || isLoading || isImageUploading}
                >
                  Save
                </Button>
              </Grid>
            </Grid>
          </Card>
        </Grid>
      </Grid>
      {openDepartment && (
        <NewDepartement
          handleCloseDialog={() => setOpenDepartment(false)}
          openModel={openDepartment}
        />
      )}

      {openCoursing && (
        <NewCoursing
          handleCloseDialog={() => setOpenCoursing(false)}
          openModel={openCoursing}
        />
      )}

      {openTax && (
        <NewTax
          handleCloseDialog={() => setOpenTax(false)}
          openModel={openTax}
        />
      )}

      {openPrinter && (
        <NewPopUpPrinter
          handleCloseDialog={() => setOpenPrinter(false)}
          openModel={openPrinter}
        />
      )}
    </form>
  );
};

export default Expense;
