import React, { useEffect, useState } from "react";
import {
  Button,
  Card,
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  useMediaQuery,
  useTheme,
  CircularProgress,
  InputAdornment,
  MenuItem,
  Paper,
  Typography,
  IconButton,
  Dialog,
  DialogContent,
  DialogActions,
  Box,
} from "@mui/material";
import { CiSearch } from "react-icons/ci";
import { useNotifier } from "../../../Core/Notifier";
import { useStyles } from "../../../theme/appStyles";
import { IProductPopUP } from "../../../Api/Interface/api.interface";
import useDebounce from "../../../Components/SearchDebonce/useDebounce";
import { useGetProductQuery } from "../../../Api/attoDeskApi";
import { FaTrash } from "react-icons/fa";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import CloseIcon from "@mui/icons-material/Close";
import AddIcon from "@mui/icons-material/Add";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import {
  DatePicker,
  DateTimePicker,
  LocalizationProvider,
  renderTimeViewClock,
} from "@mui/x-date-pickers";
import { TransferType } from "../../../Core/Enum/enum";
import { Dayjs } from "dayjs";
import { uploadImage } from "../../../Components/UploadFile/upload";

interface IProduct {
  productName: string;
  productImg: String | null;
  numberOfPassengers: number | null;
  transferType: string;
  transferTypeFrom: string;
  transferTypeTo: string;
  transferTypeDescription: string;
  departureDateTime: Dayjs | null;
  returnDateTime: Dayjs | null;
  departureAddress: string;
  destinationAddress: string;
  multiDestination: string;
  quantity: number | null;
  price: number | null;
  tax: number | null;
  total: number;
}

interface IDiscount {
  value: number;
  description: string;
}

const Index: React.FC = () => {
  const classes = useStyles();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const { showErrorMessage, showMessage } = useNotifier();

  const [searchQueryProduct, setSearchQueryProduct] = useState<string>("");
  const [currentSearchQueryProduct, setCurrentSearchQueryProduct] =
    useState<string>("");
  const debouncedSearchQueryProduct = useDebounce(searchQueryProduct, 300);

  const [showDropdownProductIndex, setShowDropdownProductIndex] = useState<
    number | null
  >(null);
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [isImageUploading, setIsImageUploading] = useState(false);

  const handleImageChange = async (
    event: React.ChangeEvent<HTMLInputElement>,
    index: number
  ) => {
    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; // 2 MB

      if (!validTypes.includes(file.type)) {
        showErrorMessage("The file must be an image (jpeg, png, jpg, gif).");
        return;
      } else if (file.size > maxSize) {
        showErrorMessage("The file must be smaller than 2 MB.");
        return;
      } else {
        try {
          setIsImageUploading(true);
          const uploadedImageUrl = await uploadImage(file);
          const updatedRows = [...productRows];
          updatedRows[index].productImg = uploadedImageUrl;
          setProductRows(updatedRows);
          setIsImageUploading(false);
        } catch (error) {
          showErrorMessage("Failed to upload the image.");
          setIsImageUploading(false);
        }
      }
    }
  };

  const [productRows, setProductRows] = useState<IProduct[]>([
    {
      productName: "",
      productImg: "",
      numberOfPassengers: null,
      transferType: TransferType.OneWayTransfer,
      transferTypeFrom: "",
      transferTypeTo: "",
      transferTypeDescription: "",
      departureDateTime: null,
      returnDateTime: null,
      departureAddress: "",
      destinationAddress: "",
      multiDestination: "",
      quantity: null,
      price: null,
      tax: null,
      total: 0,
    },
  ]);

  const [discounts, setDiscounts] = useState<IDiscount[]>([
    { value: 0, description: "" },
  ]);
  const [discountValue, setDiscountValue] = useState<number>(0);
  const [discountDescription, setDiscountDescription] = useState<string>("");
  const [subTotal, setSubTotal] = useState<number>(0);
  const [totalDiscount, setTotalDiscount] = useState<number>(0);
  const [grandTotal, setGrandTotal] = useState<number>(0);
  const [dialogOpen, setDialogOpen] = useState<boolean>(false);

  const {
    data: productData,
    isLoading: productIsLoading,
    refetch: productRefetch,
  } = useGetProductQuery({
    productBrandId: null,
    productCategoryId: null,
    productTagIds: null,
    productViewOnline: null,
    createdDateStart: null,
    createdDateEnd: null,
    searchText: currentSearchQueryProduct,
    createdDate: null,
    id: null,
  });

  useEffect(() => {
    if (
      debouncedSearchQueryProduct.length >= 2 ||
      debouncedSearchQueryProduct === ""
    ) {
      setCurrentSearchQueryProduct(debouncedSearchQueryProduct);
      productRefetch();
    }
  }, [debouncedSearchQueryProduct, productRefetch]);

  useEffect(() => {
    const totalSubTotal = productRows.reduce((acc, row) => acc + row.total, 0);
    setSubTotal(totalSubTotal);

    const calculatedTotalDiscount = discounts.reduce(
      (acc, discount) => acc + discount.value,
      0
    );
    setTotalDiscount(calculatedTotalDiscount);

    const totalGrandTotal = totalSubTotal - calculatedTotalDiscount;
    setGrandTotal(totalGrandTotal);
  }, [productRows, discounts]);

  const productList: IProductPopUP[] = Array.isArray(productData?.data)
    ? (productData?.data as IProductPopUP[])
    : [];

  const handleProductSelect = (product: IProductPopUP, index: number) => {
    const updatedRows = [...productRows];
    updatedRows[index].productName = product.productName;
    updatedRows[index].productImg = product.productImg || "";
    updatedRows[index].price = Number(product.productPrice) || null;

    updatedRows[index].quantity = null;
    updatedRows[index].total = 0;

    setProductRows(updatedRows);
    setShowDropdownProductIndex(null);
  };

  const handleAddRow = () => {
    setProductRows((prev) => [
      ...prev,
      {
        productName: "",
        productImg: "",
        numberOfPassengers: null,
        transferType: TransferType.OneWayTransfer,
        transferTypeFrom: "",
        transferTypeTo: "",
        transferTypeDescription: "",
        departureDateTime: null,
        returnDateTime: null,
        departureAddress: "",
        destinationAddress: "",
        multiDestination: "",
        quantity: null,
        price: null,
        tax: null,
        total: 0,
      },
    ]);
    setSearchQueryProduct("");
  };

  const handleFieldChange = <K extends keyof IProduct>(
    index: number,
    field: K,
    value: IProduct[K]
  ) => {
    const updatedRows = [...productRows];
    updatedRows[index][field] = value;

    const price = updatedRows[index].price ?? 0; // Default to 0 if null
    const quantity = updatedRows[index].quantity ?? 0; // Default to 0 if null
    const tax = updatedRows[index].tax ?? 0; // Default to 0 if null

    updatedRows[index].total = price * quantity * (1 + tax / 100);

    setProductRows(updatedRows);
  };

  const handleProductNameChange = (index: number, value: string) => {
    setSearchQueryProduct(value);
    handleFieldChange(index, "productName", value);
  };

  const handleDeleteRow = (index: number) => {
    const updatedRows = productRows.filter((_, i) => i !== index);
    setProductRows(updatedRows);
  };

  const handleDiscountChange = (
    index: number,
    field: keyof IDiscount,
    value: any
  ) => {
    const updatedDiscounts = [...discounts];
    updatedDiscounts[index] = {
      ...updatedDiscounts[index],
      [field]: value,
    };
    setDiscounts(updatedDiscounts);
  };
  const handleOpenDialog = () => {
    setDiscountValue(0);
    setDiscountDescription("");
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
  };

  const handleSaveDiscount = () => {
    setDiscounts((prev) => [
      ...prev,
      { value: discountValue, description: discountDescription },
    ]);
    handleCloseDialog();
  };

  const handleDeleteDiscount = (index: number) => {
    const updatedDiscounts = discounts.filter((_, i) => i !== index);
    setDiscounts(updatedDiscounts);
  };

  return (
    <div>
      <Card className={classes.quotesCard}>
        <Grid container spacing={3} padding={2}>
          <Grid
            item
            lg={12}
            md={12}
            sm={12}
            xs={12}
            sx={{ borderBottom: 2, paddingBottom: 5 }}
            className={classes.titleGrid}
          >
            <Grid container spacing={5}>
              <Grid item lg={12} md={12} sm={12} xs={12} mt={5}>
                <Grid container direction="row" alignItems="center" spacing={2}>
                  <TableContainer>
                    <Table className={classes.table}>
                      <TableHead className={classes.tableHeaderRow}>
                        <Grid container>
                          <Grid
                            item
                            lg={5}
                            md={5}
                            sm={5}
                            xs={5}
                            className={classes.tablheader}
                          >
                            <strong>Services Information</strong>
                          </Grid>
                          <Grid
                            item
                            lg={5}
                            md={5}
                            sm={5}
                            xs={5}
                            className={classes.tablheader}
                          >
                            <strong>Trip Information</strong>
                          </Grid>
                          <Grid
                            item
                            lg={2}
                            md={2}
                            sm={2}
                            xs={2}
                            className={classes.tablheader}
                          >
                            <strong>Payment Details</strong>
                          </Grid>
                        </Grid>
                      </TableHead>
                      <TableBody>
                        {productRows.map((product, index) => (
                          <Grid container key={index}>
                            <Grid item lg={5} md={5} sm={5} xs={5}>
                              <Grid container spacing={1}>
                                <Grid
                                  item
                                  lg={4}
                                  md={12}
                                  sm={12}
                                  xs={12}
                                  className={classes.SelectImageQuoteTableGrid}
                                  container
                                  alignItems="center"
                                  justifyContent="center"
                                  textAlign="center"
                                >
                                  <Grid
                                    className={classes.SelectImageQuoteTableBox}
                                    container
                                    alignItems="center"
                                    justifyContent="center"
                                  >
                                    <img
                                      src={String(product.productImg || "")}
                                      alt="Product"
                                      className={classes.SelectImageBox}
                                    />
                                    <input
                                      accept="image/*"
                                      style={{ display: "none" }}
                                      id={`icon-button-file-${index}`}
                                      type="file"
                                      onChange={(e) =>
                                        handleImageChange(e, index)
                                      }
                                    />
                                    <label
                                      htmlFor={`icon-button-file-${index}`}
                                    >
                                      <IconButton
                                        color="primary"
                                        component="span"
                                      >
                                        <AddIcon />
                                      </IconButton>
                                    </label>
                                  </Grid>
                                </Grid>

                                <Grid item lg={8} md={12} sm={12} xs={12}>
                                  <Grid container spacing={1}>
                                    <Grid item lg={12} md={12} sm={12} xs={12}>
                                      <TextField
                                        placeholder="Product Name .."
                                        size="small"
                                        sx={{ width: "100%" }}
                                        value={product.productName}
                                        onChange={(e) =>
                                          handleProductNameChange(
                                            index,
                                            e.target.value
                                          )
                                        }
                                        InputProps={{
                                          startAdornment: (
                                            <InputAdornment position="start">
                                              <CiSearch
                                                className={
                                                  classes.searchWidgetIcon
                                                }
                                              />
                                            </InputAdornment>
                                          ),
                                          classes: {
                                            root: classes.formControlListQuto,
                                            notchedOutline:
                                              classes.notchedOutline,
                                          },
                                        }}
                                        onFocus={() =>
                                          setShowDropdownProductIndex(index)
                                        }
                                      />

                                      {showDropdownProductIndex === index && (
                                        <Paper
                                          className={classes.dropdownPaper}
                                        >
                                          {productIsLoading ? (
                                            <div
                                              style={{
                                                textAlign: "center",
                                                padding: "10px",
                                              }}
                                            >
                                              <CircularProgress size={24} />
                                            </div>
                                          ) : (
                                            productList.length > 0 &&
                                            productList.map((Product) => (
                                              <MenuItem
                                                key={Product.id}
                                                onClick={() =>
                                                  handleProductSelect(
                                                    Product,
                                                    index
                                                  )
                                                }
                                              >
                                                {Product.productName}
                                              </MenuItem>
                                            ))
                                          )}
                                        </Paper>
                                      )}
                                    </Grid>
                                    <Grid item lg={12} md={12} sm={12} xs={12}>
                                      <TextField
                                        placeholder="Number of Passengers"
                                        size="small"
                                        type="number"
                                        value={product.numberOfPassengers}
                                        sx={{ width: "100%" }}
                                        onChange={(e) =>
                                          handleFieldChange(
                                            index,
                                            "numberOfPassengers",
                                            Number(e.target.value)
                                          )
                                        }
                                        InputProps={{
                                          sx: {
                                            fontSize: 14,
                                            border: "none",
                                          },
                                          classes: {
                                            root: classes.textFieldQuote,
                                            notchedOutline:
                                              classes.notchedOutline,
                                          },
                                        }}
                                        InputLabelProps={{
                                          sx: {
                                            fontSize: 14,
                                            border: "none",
                                          },
                                        }}
                                      />
                                    </Grid>
                                    <Grid item lg={12} md={12} sm={12} xs={12}>
                                      <TextField
                                        select
                                        size="small"
                                        className={classes.textField}
                                        SelectProps={{
                                          native: false,
                                        }}
                                        value={product.transferType}
                                        sx={{ width: "100%" }}
                                        onChange={(e) =>
                                          handleFieldChange(
                                            index,
                                            "transferType",
                                            String(e.target.value)
                                          )
                                        }
                                        InputProps={{
                                          sx: {
                                            fontSize: 14,
                                            border: "none",
                                          },
                                          classes: {
                                            root: classes.textFieldQuote,
                                            notchedOutline:
                                              classes.notchedOutline,
                                          },
                                        }}
                                        defaultValue=""
                                        InputLabelProps={{ shrink: true }}
                                        // {...formik.getFieldProps(
                                        //   "quoteWorkOrderStatus"
                                        // )}
                                      >
                                        <MenuItem value="" disabled>
                                          Select an option
                                        </MenuItem>

                                        {Object.entries(TransferType).map(
                                          ([key, value], index) => (
                                            <MenuItem key={index} value={value}>
                                              {key}
                                            </MenuItem>
                                          )
                                        )}
                                      </TextField>
                                    </Grid>
                                  </Grid>
                                </Grid>
                                {(product.transferType ===
                                  TransferType.OneWayTransfer ||
                                  product.transferType ===
                                    TransferType.RoundTrip) && (
                                  <Grid item lg={12} md={12} sm={12} xs={12}>
                                    <Grid container spacing={1}>
                                      <Grid item lg={6} md={6} sm={6} xs={6}>
                                        <TextField
                                          placeholder="From"
                                          size="small"
                                          value={product.transferTypeFrom}
                                          onChange={(e) =>
                                            handleFieldChange(
                                              index,
                                              "transferTypeFrom",
                                              String(e.target.value)
                                            )
                                          }
                                          InputProps={{
                                            sx: {
                                              fontSize: 14,
                                              border: "none",
                                            },
                                            classes: {
                                              root: classes.textFieldQuote,
                                              notchedOutline:
                                                classes.notchedOutline,
                                            },
                                          }}
                                          InputLabelProps={{
                                            sx: {
                                              fontSize: 14,
                                              border: "none",
                                            },
                                          }}
                                        />
                                      </Grid>
                                      <Grid item lg={6} md={6} sm={6} xs={6}>
                                        <TextField
                                          placeholder="To"
                                          size="small"
                                          value={product.transferTypeTo}
                                          onChange={(e) =>
                                            handleFieldChange(
                                              index,
                                              "transferTypeTo",
                                              String(e.target.value)
                                            )
                                          }
                                          className={classes.textField}
                                          InputProps={{
                                            sx: {
                                              fontSize: 14,
                                              border: "none",
                                            },
                                            classes: {
                                              root: classes.textFieldQuote,
                                              notchedOutline:
                                                classes.notchedOutline,
                                            },
                                          }}
                                          InputLabelProps={{
                                            sx: {
                                              fontSize: 14,
                                            },
                                          }}
                                        />
                                      </Grid>
                                    </Grid>
                                  </Grid>
                                )}
                                {product.transferType ===
                                  TransferType.MultiDestination && (
                                  <Grid item lg={12} md={12} sm={12} xs={12}>
                                    <TextField
                                      placeholder="Enter Muilti Destination"
                                      size="small"
                                      multiline
                                      rows={3}
                                      value={product.transferTypeDescription}
                                      onChange={(e) =>
                                        handleFieldChange(
                                          index,
                                          "transferTypeDescription",
                                          String(e.target.value)
                                        )
                                      }
                                      className={classes.discriptionTextField}
                                      InputProps={{
                                        sx: {
                                          fontSize: 14,
                                          border: "none",
                                        },
                                        classes: {
                                          root: classes.textFieldQuote,
                                          notchedOutline:
                                            classes.notchedOutline,
                                        },
                                      }}
                                      InputLabelProps={{
                                        sx: {
                                          fontSize: 14,
                                        },
                                      }}
                                    />
                                  </Grid>
                                )}
                              </Grid>
                            </Grid>
                            <Grid item lg={5} md={5} sm={5} xs={5}>
                              <Grid container spacing={1}>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <LocalizationProvider
                                    dateAdapter={AdapterDayjs}
                                  >
                                    <DateTimePicker
                                      value={product.departureDateTime}
                                      onChange={(value) =>
                                        handleFieldChange(
                                          index,
                                          "departureDateTime",
                                          value
                                        )
                                      }
                                      viewRenderers={{
                                        hours: renderTimeViewClock,
                                        minutes: renderTimeViewClock,
                                        seconds: renderTimeViewClock,
                                      }}
                                      slotProps={{
                                        textField: {
                                          placeholder: "Departure Date & Time",
                                          size: "small",
                                          sx: { width: "100%" },
                                          InputProps: {
                                            sx: { fontSize: 14 },
                                            classes: {
                                              root: classes.textFieldQuote,
                                              notchedOutline:
                                                classes.notchedOutline,
                                            },
                                          },
                                          InputLabelProps: {
                                            sx: { fontSize: 14 },
                                          },
                                        },
                                      }}
                                    />
                                  </LocalizationProvider>
                                </Grid>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <TextField
                                    placeholder="Departure Address"
                                    size="small"
                                    value={product.departureAddress}
                                    sx={{ width: "100%" }}
                                    onChange={(e) =>
                                      handleFieldChange(
                                        index,
                                        "departureAddress",
                                        String(e.target.value)
                                      )
                                    }
                                    InputProps={{
                                      sx: {
                                        fontSize: 14,
                                        border: "none",
                                      },
                                      classes: {
                                        root: classes.textFieldQuote,
                                        notchedOutline: classes.notchedOutline,
                                      },
                                    }}
                                    InputLabelProps={{
                                      sx: {
                                        fontSize: 14,
                                        border: "none",
                                      },
                                    }}
                                  />
                                </Grid>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <LocalizationProvider
                                    dateAdapter={AdapterDayjs}
                                  >
                                    <DateTimePicker
                                      value={product.returnDateTime}
                                      onChange={(value) =>
                                        handleFieldChange(
                                          index,
                                          "returnDateTime",
                                          value
                                        )
                                      }
                                      viewRenderers={{
                                        hours: renderTimeViewClock,
                                        minutes: renderTimeViewClock,
                                        seconds: renderTimeViewClock,
                                      }}
                                      slotProps={{
                                        textField: {
                                          placeholder: "Return Date & Time",
                                          size: "small",
                                          sx: { width: "100%" },
                                          InputProps: {
                                            sx: { fontSize: 14 },
                                            classes: {
                                              root: classes.textFieldQuote,
                                              notchedOutline:
                                                classes.notchedOutline,
                                            },
                                          },
                                          InputLabelProps: {
                                            sx: { fontSize: 14 },
                                          },
                                        },
                                      }}
                                    />
                                  </LocalizationProvider>
                                </Grid>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <TextField
                                    placeholder="Destination Address"
                                    size="small"
                                    value={product.destinationAddress}
                                    sx={{ width: "100%" }}
                                    onChange={(e) =>
                                      handleFieldChange(
                                        index,
                                        "destinationAddress",
                                        String(e.target.value)
                                      )
                                    }
                                    InputProps={{
                                      sx: {
                                        fontSize: 14,
                                        border: "none",
                                      },
                                      classes: {
                                        root: classes.textFieldQuote,
                                        notchedOutline: classes.notchedOutline,
                                      },
                                    }}
                                    InputLabelProps={{
                                      sx: {
                                        fontSize: 14,
                                        border: "none",
                                      },
                                    }}
                                  />
                                </Grid>
                              </Grid>
                            </Grid>
                            <Grid item lg={2} md={2} sm={2} xs={2}>
                              <Grid container spacing={1}>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <TextField
                                    placeholder="Quantity"
                                    size="small"
                                    type="number"
                                    value={product.quantity}
                                    onChange={(e) =>
                                      handleFieldChange(
                                        index,
                                        "quantity",
                                        Number(e.target.value)
                                      )
                                    }
                                    className={classes.textField}
                                    InputProps={{
                                      sx: {
                                        fontSize: 14,
                                        border: "none",
                                      },
                                      classes: {
                                        root: classes.textFieldQuote,
                                        notchedOutline: classes.notchedOutline,
                                      },
                                    }}
                                    InputLabelProps={{
                                      sx: {
                                        fontSize: 14,
                                      },
                                    }}
                                  />
                                </Grid>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <TextField
                                    placeholder="Price"
                                    size="small"
                                    type="number"
                                    value={product.price}
                                    onChange={(e) =>
                                      handleFieldChange(
                                        index,
                                        "price",
                                        Number(e.target.value)
                                      )
                                    }
                                    className={classes.textField}
                                    InputProps={{
                                      sx: {
                                        fontSize: 14,
                                      },
                                      classes: {
                                        root: classes.textFieldQuote,
                                        notchedOutline: classes.notchedOutline,
                                      },
                                    }}
                                    InputLabelProps={{
                                      sx: {
                                        fontSize: 14,
                                      },
                                    }}
                                  />
                                </Grid>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <TextField
                                    placeholder="Tax Percentage"
                                    size="small"
                                    type="number"
                                    value={product.tax}
                                    onChange={(e) =>
                                      handleFieldChange(
                                        index,
                                        "tax",
                                        Number(e.target.value)
                                      )
                                    }
                                    className={classes.textField}
                                    InputProps={{
                                      sx: {
                                        fontSize: 14,
                                      },
                                      classes: {
                                        root: classes.textFieldQuote,
                                        notchedOutline: classes.notchedOutline,
                                      },
                                    }}
                                    InputLabelProps={{
                                      sx: {
                                        fontSize: 14,
                                      },
                                    }}
                                  />
                                </Grid>
                                <Grid item lg={12} md={12} sm={12} xs={12}>
                                  <TextField
                                    placeholder="Toatal"
                                    size="small"
                                    type="number"
                                    value={product.total.toFixed(2)}
                                    className={classes.textField}
                                    InputProps={{
                                      readOnly: true,
                                      sx: {
                                        fontSize: 14,
                                      },

                                      classes: {
                                        root: classes.textFieldQuote,
                                        notchedOutline: classes.notchedOutline,
                                      },
                                    }}
                                    InputLabelProps={{
                                      sx: {
                                        fontSize: 14,
                                      },
                                    }}
                                  />
                                </Grid>
                                <Grid
                                  item
                                  lg={12}
                                  md={12}
                                  sm={12}
                                  xs={12}
                                  sx={{
                                    display: "flex",
                                    alignItems: "end",
                                    justifyContent: "end",
                                  }}
                                >
                                  <IconButton
                                    color="error"
                                    onClick={() => handleDeleteRow(index)}
                                  >
                                    <FaTrash />
                                  </IconButton>
                                </Grid>
                              </Grid>
                            </Grid>
                          </Grid>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                  <Grid
                    item
                    lg={12}
                    md={12}
                    sm={12}
                    xs={12}
                    py={2}
                    sx={{
                      display: "flex",
                      justifyContent: "flex-end",
                    }}
                  >
                    <Button
                      variant="contained"
                      startIcon={<AddIcon />}
                      className={classes.addButton}
                      onClick={handleAddRow}
                    >
                      Product
                    </Button>
                  </Grid>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
          <Grid
            item
            lg={12}
            md={12}
            sm={12}
            xs={12}
            sx={{ borderBottom: 2, paddingBottom: 5 }}
            className={classes.titleGrid}
          >
            <Grid container spacing={3}>
              <Grid item lg={6} md={6} sm={12} xs={12}>
                <Grid container alignItems="center">
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <TextField
                      placeholder="Enter Remark .."
                      size="small"
                      multiline
                      rows={8}
                      className={classes.discriptionTextField}
                      InputProps={{
                        sx: {
                          fontSize: 14,
                        },
                      }}
                      InputLabelProps={{
                        sx: {
                          fontSize: 14,
                        },
                      }}
                    />
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={6} md={6} sm={12} xs={12}>
                <Grid container spacing={3} alignItems="center">
                  {discounts.map((discount, index) => (
                    <Grid item lg={12} md={12} sm={12} xs={12}>
                      <Grid container spacing={3}>
                        <Grid item lg={3} md={3} sm={3} xs={3}>
                          <TextField
                            placeholder="Quantity"
                            size="small"
                            type="number"
                            value={discount.value}
                            onChange={(e) =>
                              handleDiscountChange(
                                index,
                                "value",
                                Number(e.target.value)
                              )
                            }
                            InputProps={{
                              startAdornment: (
                                <InputAdornment position="start">
                                  $
                                </InputAdornment>
                              ),
                            }}
                            className={classes.textField}
                          />
                        </Grid>
                        <Grid item lg={8} md={8} sm={8} xs={8}>
                          <TextField
                            placeholder="Description"
                            size="small"
                            value={discount.description}
                            onChange={(e) =>
                              handleDiscountChange(
                                index,
                                "description",
                                e.target.value
                              )
                            }
                            InputProps={{
                              sx: {
                                fontSize: 14,
                              },
                            }}
                            InputLabelProps={{
                              sx: {
                                fontSize: 14,
                              },
                            }}
                            className={classes.textField}
                          />
                        </Grid>
                        <Grid item lg={1} md={1} sm={1} xs={1}>
                          <IconButton
                            color="error"
                            onClick={() => handleDeleteDiscount(index)}
                          >
                            <FaTrash />
                          </IconButton>
                        </Grid>
                      </Grid>
                    </Grid>
                  ))}
                  <Grid
                    item
                    lg={12}
                    md={12}
                    sm={12}
                    xs={12}
                    py={2}
                    sx={{ display: "flex", justifyContent: "flex-end" }}
                  >
                    <Button
                      variant="contained"
                      className={classes.addButton}
                      onClick={handleOpenDialog}
                    >
                      Add Discount
                    </Button>
                  </Grid>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
          <Grid
            item
            lg={12}
            md={12}
            sm={12}
            xs={12}
            sx={{ borderBottom: 2, paddingBottom: 5 }}
            className={classes.titleGrid}
          >
            <Grid container spacing={3}>
              <Grid item lg={12} md={12} sm={12} xs={12}>
                <Grid
                  container
                  spacing={3}
                  display={"flex"}
                  justifyContent={"flex-end"}
                >
                  <Grid
                    item
                    lg={4}
                    md={4}
                    sm={12}
                    xs={12}
                    sx={{
                      display: "flex",
                      justifyContent: "flex-end",
                    }}
                  >
                    <Grid container spacing={1}>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <Typography className={classes.h5}>
                          Sub Total :
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Sub Total"
                          size="small"
                          value={subTotal}
                          className={classes.textField}
                          InputProps={{
                            readOnly: true,
                            sx: {
                              fontSize: 14,
                            },
                            startAdornment: (
                              <InputAdornment position="start">
                                $
                              </InputAdornment>
                            ),
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={12} md={12} sm={12} xs={12}>
                <Grid
                  container
                  spacing={3}
                  display={"flex"}
                  justifyContent={"flex-end"}
                >
                  <Grid
                    item
                    lg={4}
                    md={4}
                    sm={12}
                    xs={12}
                    sx={{
                      display: "flex",
                      justifyContent: "flex-end",
                    }}
                  >
                    <Grid container spacing={1}>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <Typography className={classes.h5}>
                          Total Discount :
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Discount"
                          size="small"
                          value={totalDiscount.toFixed(2)}
                          className={classes.textField}
                          InputProps={{
                            readOnly: true,
                            sx: {
                              fontSize: 14,
                            },
                            startAdornment: (
                              <InputAdornment position="start">
                                $
                              </InputAdornment>
                            ),
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item lg={12} md={12} sm={12} xs={12}>
                <Grid
                  container
                  spacing={3}
                  display={"flex"}
                  justifyContent={"flex-end"}
                >
                  <Grid
                    item
                    lg={4}
                    md={4}
                    sm={12}
                    xs={12}
                    sx={{
                      display: "flex",
                      justifyContent: "flex-end",
                    }}
                  >
                    <Grid container spacing={1}>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <Typography className={classes.h5}>
                          Grand Amount :
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Grand Amount"
                          size="small"
                          value={grandTotal}
                          className={classes.textField}
                          InputProps={{
                            readOnly: true,
                            sx: {
                              fontSize: 14,
                            },
                            startAdornment: (
                              <InputAdornment position="start">
                                $
                              </InputAdornment>
                            ),
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
          <Dialog open={dialogOpen} onClose={handleCloseDialog}>
            <Grid className={classes.Dialog}>
              <Grid
                container
                justifyContent={"space-between"}
                spacing={5}
                sx={{ borderBottom: 2, padding: 2 }}
                className={classes.titleGrid}
              >
                <Grid
                  item
                  lg={12}
                  md={12}
                  sm={12}
                  xs={12}
                  pt={2}
                  alignContent={"center"}
                >
                  <Typography className={classes.cardTitle}>
                    Set Discount
                  </Typography>
                </Grid>
              </Grid>
              <DialogContent>
                <Grid container spacing={3}>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Grid container alignItems="center">
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <Typography variant="subtitle1">Discount :</Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Invoice Number :"
                          size="small"
                          value={discountValue}
                          onChange={(e) =>
                            setDiscountValue(Number(e.target.value))
                          }
                          className={classes.textField}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                            startAdornment: (
                              <InputAdornment position="start">
                                $
                              </InputAdornment>
                            ),
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>
                  <Grid item lg={12} md={12} sm={12} xs={12}>
                    <Grid container alignItems="center">
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <Typography variant="subtitle1">
                          Description :
                        </Typography>
                      </Grid>
                      <Grid item lg={12} md={12} sm={12} xs={12}>
                        <TextField
                          placeholder="Enter Description .."
                          size="small"
                          multiline
                          rows={8}
                          value={discountDescription}
                          onChange={(e) =>
                            setDiscountDescription(e.target.value)
                          }
                          className={classes.discriptionTextField}
                          InputProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                          InputLabelProps={{
                            sx: {
                              fontSize: 14,
                            },
                          }}
                        />
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </DialogContent>
              <DialogActions sx={{ paddingRight: "24px", p: 4, py: 3, gap: 2 }}>
                <Grid container spacing={3}>
                  <Grid
                    item
                    lg={12}
                    md={12}
                    sm={12}
                    xs={12}
                    sx={{ display: "flex", justifyContent: "flex-end" }}
                  >
                    <Button
                      variant="outlined"
                      startIcon={<CloseIcon />}
                      className={classes.addButton}
                      onClick={handleCloseDialog}
                    >
                      Cancel
                    </Button>
                    <Box m={0.5}></Box>

                    <Button
                      variant="contained"
                      startIcon={<SaveAltIcon />}
                      className={classes.addButton}
                      onClick={handleSaveDiscount}
                    >
                      Save
                    </Button>
                  </Grid>
                </Grid>
              </DialogActions>
            </Grid>
          </Dialog>
        </Grid>
      </Card>
    </div>
  );
};

export default Index;
