import React from "react";
import { useState, useEffect, useRef } from "react";
import TitleCard from "pages/titleCard";
import axios from "axios";
import { enqueueSnackbar } from "notistack";
import { CSVExport } from "components/third-party/ReactTable";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { Empty } from "antd";

import nearleLogo from "../../assets/images/nearleLogo.png";
// import { PDFDownloadLink } from "@react-pdf/renderer";
import { DownloadOutlined, PrinterFilled } from "@ant-design/icons";
import ReactToPrint from "react-to-print";
import { useNavigate } from "react-router-dom";
import { FaArrowLeft } from "react-icons/fa6";

import {
  Grid,
  InputLabel,
  TextField,
  Stack,
  Badge,
  FormControl,
  MenuItem,
  Select,
  Typography,
  Box,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Divider,
  OutlinedInput,
  InputAdornment,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Chip,
} from "@mui/material";
import { DateRangePicker } from "mui-daterange-picker";
import {
  addDays,
  addMonths,
  addWeeks,
  addYears,
  endOfMonth,
  endOfWeek,
  endOfYear,
  startOfMonth,
  startOfWeek,
  startOfYear,
} from "date-fns";
import MainCard from "components/MainCard";
import { useTheme } from "@mui/material/styles";
import { FilterList } from "@mui/icons-material";
import { FieldArray, Form, Formik } from "formik";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { EditOutlined, PlusOutlined } from "@ant-design/icons";
import { SearchOutlined, LeftOutlined, RightOutlined } from "@ant-design/icons";
import ClearIcon from "@mui/icons-material/Clear";
import { useDispatch, useSelector } from "store";
import InvoiceItem from "sections/apps/invoice/InvoiceItem";
import AddressModal from "sections/apps/invoice/AddressModal";
// import InvoiceModal from "sections/apps/invoice/InvoiceModal";
import dayjs from "dayjs";
var utc = require("dayjs/plugin/utc");
dayjs.extend(utc);

const createInvoice = () => {
  const textFieldRef = useRef(null);
  const theme = useTheme();
  const [opendate, setOpendate] = useState(false);
  const [isCustomerOpen, setIsCustomerOpen] = useState(false);
  const [searchCustList, setSearchCustList] = useState("");
  const [pageno, setPageno] = useState(1);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [customerlist, setCustomerlist] = React.useState([]);
  const [selectedCustomer, setSelectedCustomer] = React.useState("");
  const [deliveryList, setDeliveryList] = React.useState([]);
  const [startdate, setStartdate] = useState(dayjs().format("YYYY-MM-DD"));
  const [enddate, setEnddate] = useState(dayjs().format("YYYY-MM-DD"));
  const [dateselect, setDateselect] = useState("");
  const [datestatus, setDatestatus] = useState("Today");
  const [totalCharge, settotalCharge] = useState(0);
  const [totalAmount, settotalAmount] = useState(0);
  const [invoiceId, setInvoiceId] = useState();
  const [invoiceNo, setInvoiceNo] = useState();
  const [notes, setnotes] = useState("");
  const [dispercent, setdispercent] = useState(0);
  const [disamt, setdisamt] = useState(0);
  const [taxpercent, settaxpercent] = useState(0);
  const [taxamt, settaxamt] = useState(0);
  const [grandtotal, setgrandtotal] = useState(0);
  const [contPerson, setContPerson] = useState("");
  const [predialog, setpredialog] = useState(false);
  const [listCount, setListCount] = useState(0);
  const componentRef = useRef(null);
  const navigate = useNavigate();
  const [obj1, setobj1] = useState();
  const [orderdetails, setorderDetails] = useState({});
  const [tenantPricing, setTenantPricing] = useState({});
  const [otherCharges, setOtherCharges] = useState(0);
  const [invoiceDate, setInvoiceDate] = useState(
    dayjs().format("YYYY-MM-DD HH:mm:ss")
  );
  const [dueDate, setDueDate] = useState(dayjs().format("YYYY-MM-DD HH:mm:ss"));
  const [isDueDate, setIsDueDate] = useState(false);
  const pdfRef = useRef();
  const okclicked = () => {
    setOpendate(false);
  };
  const [basrPrice, setBasePrice] = useState(0);
  const [pricePerKm, setPricePerKm] = useState(0);
  const [minKm, setMinKm] = useState(0);
  const [qty, setQty] = useState(0);

  useEffect(() => {
    console.log("start", startdate);
    console.log("end", enddate);
    console.log("datestatus", datestatus);
  }, [startdate, enddate]);

  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === "k" && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

        textFieldRef.current.focus();
      }
      if (
        event.key === "Escape" &&
        document.activeElement === textFieldRef.current
      ) {
        // Remove focus from the TextField
        textFieldRef.current.blur();
      }
    };
    document.addEventListener("keydown", handleKeyPress);

    return () => {
      document.removeEventListener("keydown", handleKeyPress);
    };
  }, []);
  /* ============================================= || fetchAllTenants| ============================================= */
  const fetchAllTenants = async () => {
    try {
      let url = "";
      if (searchCustList) {
        url = `${process.env.REACT_APP_URL}/tenants/search/?keyword=${searchCustList}&status=active`;
      } else {
        url = `${process.env.REACT_APP_URL}/tenants/getalltenants/?status=active&pageno=${pageno}&pagesize=${rowsPerPage}`;
      }
      const allTenantResponse = await axios.get(url);
      console.log("fetchAllTenants", allTenantResponse.data.details);
      setCustomerlist(allTenantResponse.data.details);
    } catch (error) {
      console.log("fetchAllTenants", error);
    }
  };
  /* ============================================= || fetchDelivery| ============================================= */
  const fetchDelivery = async () => {
    if (selectedCustomer && startdate && enddate) {
      try {
        let url = "";

        url = `${process.env.REACT_APP_URL}/deliveries/getdeliveries/?tenantid=${selectedCustomer.tenantid}&fromdate=${startdate}&todate=${enddate}&status=delivered`;

        const deliveryResponse = await axios.get(url);
        console.log("deliveryResponse", deliveryResponse.data.details);
        setDeliveryList(deliveryResponse.data.details);
      } catch (error) {
        console.log("fetchDelivery", error);
      }
    }
  };
  /* ============================================= || fetchinvoiceNo| ============================================= */
  const fetchinvoiceNo = async () => {
    if (selectedCustomer) {
      try {
        let url = "";
        url = `${process.env.REACT_APP_URL}/invoice/getseqno/?tenantid=${selectedCustomer.tenantid}`;
        const invoiceresponse = await axios.get(url);
        console.log("invoiceresponse", invoiceresponse.data.Details);
        setInvoiceId(invoiceresponse.data.Details);
        setInvoiceNo(invoiceresponse.data.Details);
      } catch (error) {
        console.log("fetchinvoiceNo", error);
      }
    }
  };
  /* ============================================= || getinvoiceorders | ============================================= */
  const getinvoiceorders = async () => {
    if (selectedCustomer && startdate && enddate) {
      try {
        let url = "";
        url = `${process.env.REACT_APP_URL}/invoice/getinvoiceorders/?tenantid=${selectedCustomer.tenantid}&fromdate=${startdate}&todate=${enddate}`;
        const invoiceordersRes = await axios.get(url);
        console.log("orderdetails", invoiceordersRes.data.details);
        setorderDetails(invoiceordersRes.data.details);
        setQty(invoiceordersRes.data.details.actualkms);
      } catch (error) {
        console.log("invoiceordersRes", error);
      }
    }
  };

  const fetchTenantPricing = async () => {
    if (selectedCustomer) {
      try {
        const pricingResponse = await axios.get(
          `${process.env.REACT_APP_URL}/tenants/gettenantpricing/?tenantid=${selectedCustomer.tenantid}`
        );
        console.log("tenantPricing", pricingResponse.data.details);
        setTenantPricing(pricingResponse.data.details);
        setBasePrice(pricingResponse.data.details.baseprice);
        setPricePerKm(pricingResponse.data.details.priceperkm);
        setMinKm(pricingResponse.data.details.minkm);
      } catch (error) {
        console.log("fetchTenantPricing error", error);
      }
    }
  };
  useEffect(() => {
    getinvoiceorders();
    fetchTenantPricing();
  }, [selectedCustomer, startdate, enddate]);

  useEffect(() => {
    fetchAllTenants();
  }, [pageno, searchCustList]);
  useEffect(() => {
    console.log("selectedCustomer", selectedCustomer);
    fetchinvoiceNo();
  }, [selectedCustomer]);
  useEffect(() => {
    fetchDelivery();
  }, [selectedCustomer, startdate, enddate]);

  // ==============================|| calculate||============================== //

  useEffect(() => {
    setListCount(deliveryList.length || "0");
  }, [deliveryList]);

  useEffect(() => {
    settotalAmount(Number(pricePerKm) * Number(qty) + Number(otherCharges));
    settotalCharge(Number(pricePerKm) * Number(qty) + Number(otherCharges));
    setgrandtotal(Number(pricePerKm) * Number(qty) + Number(otherCharges));
  }, [pricePerKm, qty, otherCharges]);
  useEffect(() => {
    setgrandtotal(
      Number(pricePerKm) * Number(qty) +
        Number(otherCharges) -
        Number(disamt) +
        Number(taxamt)
    );
  }, [disamt, taxamt]);

  // ==============================|| createInvoice||============================== //
  const createInvoice = async () => {
    let obj = {
      salesid: 0,
      transactiondate: invoiceDate,
      duedate: dueDate,
      tenantid: selectedCustomer.tenantid,
      tenantname: selectedCustomer.tenantname,
      address: selectedCustomer.address,
      suburb: selectedCustomer.suburb,
      city: selectedCustomer.city,
      state: selectedCustomer.state,
      contactperson: contPerson,
      applocationid: selectedCustomer.applocationid,
      invoiceno: invoiceNo,
      invoiceid: invoiceId,
      // itemcount: deliveryList.length,
      itemcount: orderdetails.deliveries,
      salesamount: totalAmount,
      discountpercent: parseInt(dispercent),
      discountamt: parseInt(disamt),
      taxpercent: parseInt(taxpercent),
      taxamount: taxamt,
      totalamount: Math.round(grandtotal),
      remarks: notes,
      tenantsalesdetails: deliveryList.map((data, index) => ({
        salesdetailid: 0,
        salesid: 0,
        tenantid: selectedCustomer.tenantid,
        orderheaderid: data.orderheaderid,
        orderid: data.orderid,
        orderdate: dayjs(data.deliverydate).format("YYYY-MM-DD HH:mm:ss"),
        pickup: data.pickuplocation,
        drop: data.deliverylocation,
        qty: parseInt(data.actualkms) || parseInt(data.kms),
        baserate: 0,
        amount: 0,
        taxpercent: 0,
        taxamount: 0,
        totalamount: data.deliveryamt || data.deliverycharges,
      })),
    };

    console.log(obj);

    try {
      await axios
        .post(`${process.env.REACT_APP_URL}/invoice/create`, obj)
        .then((res) => {
          console.log(res);
          if (res.data.status) {
            enqueueSnackbar(" Created Successfully ", {
              variant: "success",
              anchorOrigin: { vertical: "top", horizontal: "right" },
              autoHideDuration: 1000,
            });
          }
          navigate("/invoice");
        })
        .catch((err) => {
          console.log(err);

          enqueueSnackbar(err.message, {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 1000,
          });
        });
    } catch (err) {
      console.log(err);
    }
  };
  // ==============================|| formatNumberToRupees||============================== //
  function formatNumberToRupees(value) {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      minimumFractionDigits: 2,
    }).format(value);
  }
  // ==============================|| opentoast||============================== //

  const opentoast = (message) => {
    enqueueSnackbar(message, {
      variant: "error",
      anchorOrigin: { vertical: "top", horizontal: "right" },
      autoHideDuration: 2000,
    });
    // console.log(alertmessage)
  };

  /* ======================================= || handleDelete ||  ======================================= */
  const handleDelete = (index) => {
    const newData = [...deliveryList];
    newData.splice(index, 1);
    setDeliveryList(newData);
  };

  /* ======================================= || handleEdit ||  ======================================= */
  const handleEdit = (index, field, value) => {
    const newData = [...deliveryList];
    newData[index][field] = value;
    setDeliveryList(newData);
  };
  const downloadpdf = () => {
    console.log("clicke");
    const input = pdfRef.current;

    html2canvas(input).then((canvas) => {
      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF("p", "mm", "a4", true);
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = pdf.internal.pageSize.getHeight();
      const imgWidth = canvas.width;
      const imgHeigth = canvas.height;
      const ratio = Math.min(pdfWidth / imgWidth / pdfHeight / imgHeigth);
      const imgX = (pdfWidth - imgWidth * ratio) / 2;
      const imgY = 30;

      pdf.addImage(
        imgData,
        "PNG",
        imgX,
        imgY,
        imgWidth * ratio,
        imgHeigth * ratio
      );

      pdf.save("invoice.pdf");
    });
  };

  return (
    <>
      {/* <TitleCard title="Create Invoice" /> */}
      <Stack
        direction="row"
        justifyContent="Space-between"
        alignItems={"center"}
        spacing={2}
        sx={{ px: 2.5, py: 1, bgcolor: "#eeeeee" }}
      >
        <Stack direction={"row"} alignItems={"center"} spacing={2}>
          <Tooltip title="back">
            <IconButton
              color="primary"
              onClick={() => {
                navigate("/invoice");
              }}
            >
              <FaArrowLeft size={"large"} />
            </IconButton>
          </Tooltip>

          <Stack alignItems={"center"}>
            <Typography variant="h3" color={"primary"}>
              Create Invoice
            </Typography>
          </Stack>
        </Stack>
        <Stack
          direction="row"
          justifyContent="flex-end"
          alignItems="flex-end"
          spacing={2}
          sx={{ height: "100%" }}
        >
          <Button
            disabled={!selectedCustomer}
            variant="outlined"
            color="primary"
            sx={{
              "&:hover": {
                backgroundColor: "primary.main",
                color: "primary.contrastText",
              },
            }}
            onClick={() => {
              // setpredialog(true);
              navigate("/invoice/create/preview", {
                state: {
                  selectedCustomer: selectedCustomer,
                  deliveryList: deliveryList,
                  invoiceNo: invoiceNo,
                  invoiceDate: invoiceDate,
                  dueDate: dueDate,
                  totalAmount: totalAmount,
                  disamt: disamt,
                  taxamt: taxamt,
                  grandtotal: grandtotal,
                  notes: notes,
                  contPerson: contPerson,
                  invoiceId: invoiceId,
                  dispercent: dispercent,
                  taxpercent: taxpercent,
                  startdate: startdate,
                  enddate: enddate,
                  tenantPricing: tenantPricing,
                  orderdetails: orderdetails,
                  otherCharges: otherCharges,
                  ordercount: orderdetails.deliveries,
                },
              });
            }}
          >
            Preview
          </Button>
          {/* <Button
            disabled={!selectedCustomer || !isDueDate}
            startIcon={<PlusOutlined />}
            color="primary"
            variant="contained"
            onClick={() => {
              createInvoice();
            }}
          >
            Save
          </Button> */}
        </Stack>
      </Stack>
      <MainCard>
        <Formik>
          <Form>
            <Grid container spacing={2}>
              {/* ======================================= || Invoice No ||  ======================================= */}
              <Grid item xs={12} sm={6} md={3}>
                {" "}
                <Stack spacing={1}>
                  <InputLabel>Invoice No</InputLabel>
                  <FormControl sx={{ width: "100%" }}>
                    <TextField
                      label={!invoiceNo && "000 - 0000"}
                      value={invoiceNo && invoiceNo}
                      onChange={(e) => {
                        setInvoiceNo(e.target.value);
                      }}
                    />
                  </FormControl>
                </Stack>
              </Grid>{" "}
              {/* ======================================= || Invoice Date ||  ======================================= */}
              <Grid item xs={12} sm={6} md={3}>
                <Stack spacing={1}>
                  <InputLabel> Invoice Date</InputLabel>
                  <FormControl
                    sx={{ width: "100%" }}

                    // error={Boolean(touched.date && errors.date)}
                  >
                    <LocalizationProvider dateAdapter={AdapterDateFns}>
                      <DatePicker
                        format="dd/MM/yyyy"
                        defaultValue={new Date()}
                        onChange={(e) => {
                          console.log(
                            "invoicedate",
                            dayjs(e).format("YYYY-MM-DD HH:mm:ss")
                          );
                          setInvoiceDate(
                            dayjs(e).format("YYYY-MM-DD HH:mm:ss")
                          );
                        }}
                      />
                    </LocalizationProvider>
                  </FormControl>
                </Stack>
              </Grid>{" "}
              {/* ======================================= || Due date ||  ======================================= */}
              <Grid item xs={12} sm={6} md={3}>
                <Stack spacing={1}>
                  <InputLabel>Due Date</InputLabel>
                  <FormControl sx={{ width: "100%" }}>
                    <LocalizationProvider dateAdapter={AdapterDateFns}>
                      <DatePicker
                        format="dd/MM/yyyy"
                        // value={values.due_date}
                        onChange={(e) => {
                          setDueDate(dayjs(e).format("YYYY-MM-DD HH:mm:ss"));
                          setIsDueDate(true);
                        }}
                      />
                    </LocalizationProvider>
                  </FormControl>
                </Stack>
                {/* {touched.due_date && errors.due_date && (
            <FormHelperText error={true}>{errors.due_date}</FormHelperText>
          )} */}
              </Grid>{" "}
              {/* ======================================= || Contact person ||  ======================================= */}
              <Grid item xs={12} sm={6} md={3}>
                {" "}
                <Stack spacing={1}>
                  <InputLabel>Contact person</InputLabel>
                  <FormControl sx={{ width: "100%" }}>
                    <TextField
                      required
                      name="invoice_id"
                      id="invoice_id"
                      value={contPerson}
                      onChange={(e) => {
                        setContPerson(e.target.value);
                      }}
                    />
                  </FormControl>
                </Stack>
              </Grid>{" "}
              {/* ======================================= || From ||  ======================================= */}
              <Grid item xs={12} sm={6}>
                <MainCard sx={{ minHeight: 240 }}>
                  <Grid container spacing={2}>
                    <Grid item xs={12} sm={8}>
                      <Stack spacing={2}>
                        <Typography variant="h5">From:</Typography>
                        <Stack sx={{ width: "100%" }}>
                          <Typography variant="subtitle1">
                            Nearle Technology Private Limited.
                          </Typography>
                          <Typography color="secondary">
                            424, 4<sup>th</sup>floor,
                          </Typography>
                          <Typography color="secondary">
                            Red rose towers,
                          </Typography>
                          <Typography color="secondary">
                            DB Road, RS Puram,
                          </Typography>
                          <Typography color="secondary">641002.</Typography>
                          <Typography color="secondary">
                            care@nearle.in
                          </Typography>
                          <Typography color="secondary">9087368666</Typography>
                        </Stack>
                      </Stack>
                    </Grid>
                    <Grid item xs={12} sm={4}>
                      <Box
                        textAlign={{ xs: "left", sm: "right" }}
                        color="grey.200"
                      >
                        {/* <Button
                          variant="outlined"
                          startIcon={<EditOutlined />}
                          color="secondary"
                          onClick={() =>
                            dispatch(
                              toggleCustomerPopup({
                                open: true,
                              })
                            )
                          }
                          size="small"
                        >
                          Change
                        </Button> */}
                        <AddressModal
                          open={false}
                          // setOpen={(value) =>
                          //   dispatch(
                          //     toggleCustomerPopup({
                          //       open: value,
                          //     })
                          //   )
                          // }
                          // handlerAddress={(address) =>
                          //   setFieldValue("cashierInfo", address)
                          // }
                        />
                      </Box>
                    </Grid>
                  </Grid>
                </MainCard>
              </Grid>{" "}
              {/* ======================================= ||  To  ||  ======================================= */}
              <Grid item xs={12} sm={6}>
                <MainCard sx={{ minHeight: 240 }}>
                  <Grid container spacing={2}>
                    <Grid item xs={12} sm={8}>
                      <Stack spacing={2}>
                        <Typography variant="h5">To:</Typography>
                        <Stack sx={{ width: "100%" }}>
                          {selectedCustomer == "" ? (
                            <>
                              {" "}
                              <Typography variant="subtitle1">
                                Select Customer
                              </Typography>
                            </>
                          ) : (
                            <>
                              <Typography variant="subtitle1">
                                {selectedCustomer.companyname}
                              </Typography>
                              <Typography color="secondary">
                                {selectedCustomer.address}
                              </Typography>
                              <Typography color="secondary">
                                {selectedCustomer.postcode}
                              </Typography>
                              <Typography color="secondary">
                                {selectedCustomer.primaryemail}
                              </Typography>
                              <Typography color="secondary">
                                {selectedCustomer.primarycontact}
                              </Typography>{" "}
                            </>
                          )}
                        </Stack>
                      </Stack>
                    </Grid>
                    <Grid item xs={12} sm={4}>
                      <Box textAlign="right" color="grey.200">
                        <Button
                          size="small"
                          startIcon={<PlusOutlined />}
                          color="secondary"
                          variant="outlined"
                          onClick={() => {
                            setIsCustomerOpen(true);
                            setSearchCustList("");
                          }}
                        >
                          Add
                        </Button>
                      </Box>
                    </Grid>
                  </Grid>
                </MainCard>
              </Grid>{" "}
              {/* ======================================= || deliveries Table||  ======================================= */}
              <Grid item xs={12}>
                <FieldArray
                  name="invoice_detail"
                  render={({ remove, push }) => {
                    return (
                      <>
                        <MainCard
                          content={false}
                          /* ======================================= ||  Filter  ||  ======================================= */
                          title={
                            <Grid container>
                              <Grid
                                item
                                xs={12}
                                sx={{
                                  display: "flex",
                                  flexDirection: "row",
                                  alignItems: "center",
                                  justifyContent: "space-between",
                                }}
                              >
                                <stack
                                  direction={"row"}
                                  spacing={4}
                                  sx={{
                                    display: "flex",
                                    flexDirection: "row",
                                    alignItems: "center",
                                    // justifyContent: "space-between",
                                    width: "100%",
                                  }}
                                >
                                  {datestatus && (
                                    <Chip
                                      label={`orders-${datestatus}`}
                                      color="info"
                                      variant="contained"
                                      size="small"
                                      sx={{ mr: 2 }}
                                    />
                                  )}
                                  {startdate && enddate && (
                                    <Badge
                                      badgeContent={orderdetails.deliveries}
                                      color="primary"
                                      max={1000000}
                                    >
                                      <Chip
                                        label={`${dayjs(startdate).format(
                                          "DD/MM/YYYY"
                                        )} - ${dayjs(enddate).format(
                                          "DD/MM/YYYY"
                                        )}`}
                                        color="primary"
                                        variant="contained"
                                        size="small"
                                      />
                                    </Badge>
                                  )}
                                  {selectedCustomer && (
                                    <>
                                      <Chip
                                        label={`Orders: ${orderdetails.deliveries}`}
                                        color="secondary"
                                        variant="contained"
                                        size="small"
                                        sx={{ ml: 3 }}
                                      />
                                      <Chip
                                        label={`BasePrice: ₹${tenantPricing.baseprice}.00`}
                                        color="secondary"
                                        variant="contained"
                                        size="small"
                                        sx={{ ml: 3 }}
                                      />
                                      <Chip
                                        label={`Price/km: ₹${tenantPricing.priceperkm}.00`}
                                        color="secondary"
                                        variant="contained"
                                        size="small"
                                        sx={{ ml: 3 }}
                                      />
                                      <Chip
                                        label={`MinKm: ${tenantPricing.minkm}km`}
                                        color="secondary"
                                        variant="contained"
                                        size="small"
                                        sx={{ ml: 3 }}
                                      />{" "}
                                      <Chip
                                        label={`Unit: ${tenantPricing.slab}`}
                                        color="secondary"
                                        variant="contained"
                                        size="small"
                                        sx={{ ml: 3 }}
                                      />{" "}
                                    </>
                                  )}
                                </stack>
                                <Tooltip title="Order Filter">
                                  <IconButton
                                    color="secondary"
                                    variant="light"
                                    sx={{
                                      color: "text.primary",
                                      bgcolor: "grey.200",
                                    }}
                                    aria-haspopup="true"
                                    onClick={() => setOpendate(true)}
                                  >
                                    <FilterList />
                                  </IconButton>
                                </Tooltip>
                              </Grid>
                            </Grid>
                          }
                        >
                          <div className="print-page">
                            <TableContainer
                              sx={{
                                minHeight: 100,
                                maxHeight: 430,
                                "&::-webkit-scrollbar": {
                                  width: "5px", // Width of vertical scrollbar
                                  height: "2px", // Height of horizontal scrollbar
                                },
                                "&::-webkit-scrollbar-thumb": {
                                  backgroundColor: "#65387A", // Color of the scrollbar thumb
                                },
                              }}
                            >
                              <Table stickyHeader aria-label="sticky table">
                                <TableHead
                                  sx={{
                                    "& th": {
                                      borderTop: `1px solid ${theme.palette.divider}`,
                                      borderBottom: `2px solid ${theme.palette.divider} !important`,
                                    },
                                  }}
                                >
                                  <TableRow>
                                    <TableCell>S.No</TableCell>
                                    {/* <TableCell>From</TableCell>
                                    <TableCell>To</TableCell> */}
                                    <TableCell>Particulars</TableCell>
                                    <TableCell>Units</TableCell>
                                    <TableCell>Quantity</TableCell>
                                    <TableCell align="right">Rate</TableCell>
                                    <TableCell align="right">Charge</TableCell>
                                    {/* {tenantPricing?.pricingtypeid === 73 && ( */}
                                    <TableCell align="right">
                                      Other Charges
                                    </TableCell>
                                    {/* )} */}
                                    <TableCell align="right">Amount</TableCell>
                                  </TableRow>
                                </TableHead>
                                <TableBody>
                                  {deliveryList.length == 0 ? (
                                    selectedCustomer == "" ? (
                                      <>
                                        <TableCell colSpan={9}>
                                          <Stack
                                            width={"100%"}
                                            direction={"row"}
                                            justifyContent={"center"}
                                          >
                                            <Empty />
                                          </Stack>
                                        </TableCell>
                                      </>
                                    ) : (
                                      <TableRow>
                                        <TableCell>1</TableCell>
                                        <TableCell>
                                          <Typography>
                                            {`Invoice from ${dayjs(
                                              startdate
                                            ).format("DD-MM-YYYY")} to  ${dayjs(
                                              enddate
                                            ).format("DD-MM-YYYY")}`}
                                          </Typography>
                                        </TableCell>
                                        <TableCell>
                                          <Typography>
                                            {tenantPricing.slab}
                                          </Typography>
                                        </TableCell>

                                        <TableCell>
                                          <Typography>{`${orderdetails.actualkms}km`}</Typography>
                                        </TableCell>
                                        <TableCell>
                                          <Typography align="right">
                                            {" "}
                                            {`₹ ${tenantPricing.priceperkm}.00`}
                                          </Typography>
                                        </TableCell>
                                        <TableCell align="right">
                                          <Typography>
                                            {`₹ ${(
                                              Number(orderdetails.actualkms) *
                                              Number(tenantPricing.priceperkm)
                                            ).toFixed(2)}`}
                                          </Typography>
                                        </TableCell>

                                        <TableCell align="right">
                                          {/* <Typography>{`₹ ${otherCharges}.00`}</Typography> */}
                                          <TextField
                                            value={otherCharges}
                                            onChange={(e) => {
                                              setOtherCharges(e.target.value);
                                            }}
                                            InputProps={{
                                              startAdornment: (
                                                <InputAdornment position="start">
                                                  (₹)
                                                </InputAdornment>
                                              ),
                                              endAdornment: (
                                                <InputAdornment position="end">
                                                  .00
                                                </InputAdornment>
                                              ),
                                            }}
                                          />
                                        </TableCell>

                                        <TableCell align="right">
                                          <Typography>
                                            {`₹ ${(
                                              Number(orderdetails.actualkms) *
                                                Number(
                                                  tenantPricing.priceperkm
                                                ) +
                                              Number(otherCharges)
                                            ).toFixed(2)}`}
                                          </Typography>
                                        </TableCell>
                                      </TableRow>
                                    )
                                  ) : (
                                    <TableRow>
                                      <TableCell>1</TableCell>
                                      <TableCell>
                                        <Typography>
                                          {`Invoice from ${dayjs(
                                            startdate
                                          ).format("DD-MM-YYYY")} to  ${dayjs(
                                            enddate
                                          ).format("DD-MM-YYYY")}`}
                                        </Typography>
                                      </TableCell>
                                      <TableCell>
                                        <Typography>
                                          {tenantPricing.slab}
                                        </Typography>
                                      </TableCell>
                                      <TableCell>
                                        {" "}
                                        <TextField
                                          sx={{ width: 150 }}
                                          variant="outlined"
                                          type="number"
                                          value={qty}
                                          InputProps={{
                                            startAdornment: (
                                              <InputAdornment position="start">
                                                kg
                                              </InputAdornment>
                                            ),
                                          }}
                                          inputProps={{
                                            style: {
                                              textAlign: "left",
                                            },
                                          }}
                                          onChange={(e) => {
                                            setQty(e.target.value);
                                            setorderDetails({
                                              ...orderdetails,
                                              actualkms: e.target.value,
                                            });
                                            setdispercent(0);
                                            settaxpercent(0);
                                            setdisamt(0);
                                            settaxamt(0);
                                          }}
                                        />
                                      </TableCell>

                                      <TableCell align="left">
                                        <TextField
                                          sx={{ width: 150 }}
                                          variant="outlined"
                                          type="number"
                                          value={pricePerKm}
                                          InputProps={{
                                            startAdornment: (
                                              <InputAdornment position="left">
                                                ₹
                                              </InputAdornment>
                                            ),
                                          }}
                                          inputProps={{
                                            style: {
                                              textAlign: "left",
                                            },
                                          }}
                                          onChange={(e) => {
                                            setPricePerKm(e.target.value);
                                            setTenantPricing({
                                              ...tenantPricing,
                                              priceperkm: e.target.value,
                                            });
                                            setdispercent(0);
                                            settaxpercent(0);
                                            setdisamt(0);
                                            settaxamt(0);
                                          }}
                                        />
                                      </TableCell>
                                      {/* {tenantPricing.pricingtypeid == 73 && ( */}
                                      <TableCell align="left">
                                        <TextField
                                          sx={{ width: 150 }}
                                          variant="outlined"
                                          type="number"
                                          InputProps={{
                                            startAdornment: (
                                              <InputAdornment position="left">
                                                ₹
                                              </InputAdornment>
                                            ),
                                          }}
                                          inputProps={{
                                            style: {
                                              textAlign: "left",
                                            },
                                          }}
                                          onChange={(e) => {
                                            setOtherCharges(e.target.value);
                                            settotalAmount(
                                              Number(qty) * Number(pricePerKm) +
                                                Number(e.target.value)
                                            );
                                            setdispercent(0);
                                            settaxpercent(0);
                                            setdisamt(0);
                                            settaxamt(0);
                                          }}
                                        />
                                      </TableCell>
                                      {/* )} */}
                                      <TableCell align="right">
                                        <Typography>
                                          {`₹ ${totalAmount.toFixed(2)}`}
                                        </Typography>
                                      </TableCell>
                                    </TableRow>
                                  )}
                                </TableBody>
                              </Table>
                            </TableContainer>
                          </div>
                        </MainCard>

                        <Divider />

                        <Grid container justifyContent="space-between">
                          <Grid item xs={12} md={8}>
                            <Box
                              sx={{ pt: 2.5, pr: 2.5, pb: 2.5, pl: 0 }}
                            ></Box>
                          </Grid>
                          {/* ======================================= || Sub Total ||  ======================================= */}

                          <Grid item xs={12} md={4}>
                            <Grid
                              container
                              justifyContent="space-between"
                              spacing={2}
                              sx={{ pt: 2.5, pb: 2.5 }}
                            >
                              <Grid item xs={6}>
                                <Stack spacing={1}>
                                  <InputLabel>Discount(%)</InputLabel>
                                  <TextField
                                    type="number"
                                    fullWidth
                                    name="discount"
                                    id="discount"
                                    placeholder="0.0"
                                    inputProps={{
                                      min: 0,
                                      max: 99,
                                    }}
                                    value={dispercent == 0 ? "" : dispercent}
                                    onChange={(e) => {
                                      setdispercent(e.target.value);
                                      let val;
                                      if (e) {
                                        val =
                                          // (e.target.value / 100) * totalAmount;
                                          (e.target.value / 100) * totalAmount;
                                      }
                                      setdisamt(val > 0 ? val.toFixed(2) : 0);
                                      // setgrandtotal(totalAmount - val);
                                      settaxpercent(0);
                                      settaxamt(0);
                                    }}
                                  />
                                </Stack>
                              </Grid>
                              <Grid item xs={6}>
                                <Stack spacing={1}>
                                  <InputLabel>Discount(₹)</InputLabel>
                                  <TextField
                                    readonly
                                    fullWidth
                                    name="tax"
                                    id="tax"
                                    placeholder="0.0"
                                    value={formatNumberToRupees(disamt || 0)}
                                    // onChange={(e) => {
                                    //   setdisamt(e.target.value);
                                    // }}
                                    inputProps={{
                                      min: 0,
                                      style: {
                                        textAlign: "right",
                                      },
                                    }}
                                  />
                                </Stack>
                              </Grid>
                              <Grid item xs={6}>
                                <Stack spacing={1}>
                                  <InputLabel>Tax(%)</InputLabel>
                                  <TextField
                                    type="number"
                                    fullWidth
                                    name="discount"
                                    id="discount"
                                    placeholder="0.0"
                                    inputProps={{
                                      min: 0,
                                    }}
                                    value={taxpercent == 0 ? "" : taxpercent}
                                    onChange={(e) => {
                                      settaxpercent(e.target.value);

                                      let val =
                                        ((totalAmount - disamt) *
                                          e.target.value) /
                                        100;
                                      settaxamt(val);
                                      // let val1 =
                                      //   totalAmount -
                                      //   disamt +
                                      //   ((totalAmount - disamt) *
                                      //     e.target.value) /
                                      //     100;
                                      // setgrandtotal(val1);
                                    }}
                                  />
                                </Stack>
                              </Grid>
                              <Grid item xs={6}>
                                <Stack spacing={1}>
                                  <InputLabel>Tax(₹)</InputLabel>
                                  <TextField
                                    readonly
                                    fullWidth
                                    name="tax"
                                    id="tax"
                                    placeholder="0.0"
                                    value={formatNumberToRupees(taxamt)}
                                    inputProps={{
                                      min: 0,
                                      style: {
                                        textAlign: "right",
                                      },
                                    }}
                                  />
                                </Stack>
                              </Grid>
                            </Grid>
                            <Grid item xs={12}>
                              <Stack spacing={2}>
                                <Stack
                                  direction="row"
                                  justifyContent="space-between"
                                >
                                  <Typography color={theme.palette.grey[500]}>
                                    Sub Total:
                                  </Typography>
                                  <Typography>
                                    {/* {`₹ ${(
                                      Number(orderdetails.actualkms) *
                                        Number(tenantPricing.priceperkm) +
                                      Number(otherCharges)
                                    ).toFixed(2)}`} */}
                                    {formatNumberToRupees(totalAmount || 0)}
                                  </Typography>
                                </Stack>
                                <Stack
                                  direction="row"
                                  justifyContent="space-between"
                                >
                                  <Typography color={theme.palette.grey[500]}>
                                    Discount:
                                  </Typography>
                                  <Typography color={theme.palette.error.main}>
                                    - {formatNumberToRupees(disamt)}
                                  </Typography>
                                </Stack>
                                <Stack
                                  direction="row"
                                  justifyContent="space-between"
                                >
                                  <Typography color={theme.palette.grey[500]}>
                                    Tax:
                                  </Typography>
                                  <Typography
                                    color={theme.palette.success.main}
                                  >
                                    +{formatNumberToRupees(taxamt)}
                                  </Typography>
                                </Stack>
                                <Stack
                                  direction="row"
                                  justifyContent="space-between"
                                >
                                  <Typography variant="subtitle1">
                                    Grand Total:
                                  </Typography>
                                  <Typography variant="subtitle1">
                                    {formatNumberToRupees(
                                      Math.round(grandtotal) || 0
                                    )}
                                  </Typography>
                                </Stack>
                              </Stack>
                            </Grid>
                          </Grid>
                        </Grid>
                      </>
                    );
                  }}
                />
              </Grid>{" "}
              {/* ======================================= || Notes ||  ======================================= */}
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel>Notes</InputLabel>
                  <TextField
                    placeholder="Address"
                    rows={3}
                    // value={values.notes}
                    multiline
                    name="notes"
                    onChange={(e) => {
                      setnotes(e.target.value);
                    }}
                    // inputProps={{
                    //   maxLength: notesLimit,
                    // }}
                    // helperText={`${values.notes.length} / ${notesLimit}`}
                    sx={{
                      width: "100%",
                      "& .MuiFormHelperText-root": {
                        mr: 0,
                        display: "flex",
                        justifyContent: "flex-end",
                      },
                    }}
                  />
                </Stack>
              </Grid>
            </Grid>
          </Form>
        </Formik>
      </MainCard>
      {/* ============================================= || Date Dialog|| ============================================= */}
      <Dialog open={opendate}>
        <DialogTitle align="left">
          <Typography variant="h4">Select Filter Options</Typography>
        </DialogTitle>
        <DialogContent sx={{ width: "100%" }} className="datedialog">
          <DateRangePicker
            open={opendate}
            toggle={() => setOpendate(!opendate)}
            id="daterange1"
            onChange={(range) => {
              if (range.label === "All") {
                setDateselect("all");
                setStartdate("");
                setEnddate("");
                setOpendate(false);
              } else {
                setDateselect("select");
                setStartdate(dayjs(range.startDate).format("YYYY-MM-DD"));
                setEnddate(dayjs(range.endDate).format("YYYY-MM-DD"));
                if (range.label) {
                  setDatestatus(range.label);
                } else {
                  setDatestatus("");
                }
              }
              console.log(range);
            }}
            definedRanges={[
              {
                label: "Today",
                startDate: new Date(),
                endDate: new Date(),
              },
              {
                label: "Yesterday",
                startDate: addDays(new Date(), -1),
                endDate: addDays(new Date(), -1),
              },
              {
                label: "Tomorrow",
                startDate: addDays(new Date(), +1),
                endDate: addDays(new Date(), +1),
              },
              {
                label: "This Week",
                startDate: startOfWeek(new Date()),
                endDate: endOfWeek(new Date()),
              },
              {
                label: "Last Week",
                startDate: startOfWeek(addWeeks(new Date(), -1)),
                endDate: endOfWeek(addWeeks(new Date(), -1)),
              },
              {
                label: "Last 7 Days",
                startDate: addWeeks(new Date(), -1),
                endDate: new Date(),
              },
              {
                label: "This Month",
                startDate: startOfMonth(new Date()),
                endDate: endOfMonth(new Date()),
              },
              {
                label: "Last Month",
                startDate: startOfMonth(addMonths(new Date(), -1)),
                endDate: endOfMonth(addMonths(new Date(), -1)),
              },
              // {
              //   label: "All",
              //   startDate: new Date(),
              //   endDate: addDays(new Date(), -1),
              // },
            ]}
          />
        </DialogContent>
        <Stack
          direction="row"
          justifyContent="flex-end"
          sx={{ width: "100%", p: 2 }}
        >
          <Button variant="contained" size="small" onClick={okclicked}>
            ok
          </Button>
        </Stack>
      </Dialog>
      {/* ============================================= || Customer Dialog || ============================================= */}
      <Dialog
        open={isCustomerOpen}
        onClose={() => {
          setIsCustomerOpen(false);
        }}
        minWidth={"lg"}
        fullWidth
        // sx={{
        //   "& .MuiDialog-paper": { p: 0 },
        //   "& .MuiBackdrop-root": { opacity: "0.5 !important" },
        // }}
      >
        <DialogTitle
          sx={{ bgcolor: theme.palette.primary.main, color: "white" }}
        >
          <Stack>
            <Typography variant="h3">Select Address</Typography>
            <FormControl
              sx={{
                width: "100%",
                mt: 1,
              }}
            >
              <Stack spacing={2} sx={{ py: 0.2 }}>
                <OutlinedInput
                  inputRef={textFieldRef}
                  fullWidth
                  id="input-search-header"
                  placeholder="Search (ctrl+k)"
                  value={searchCustList}
                  onChange={(e) => setSearchCustList(e.target.value)}
                  // onChange={handleSearch}
                  sx={{
                    "& .MuiOutlinedInput-input": {
                      p: "10.5px 0px 12px",
                    },
                    bgcolor: "white",
                  }}
                  startAdornment={
                    <InputAdornment position="start">
                      <SearchOutlined style={{ fontSize: "small" }} />
                    </InputAdornment>
                  }
                  endAdornment={
                    <IconButton
                      sx={{ visibility: searchCustList ? "visible" : "hidden" }}
                      onClick={() => {
                        setSearchCustList("");
                      }}
                    >
                      <ClearIcon />
                    </IconButton>
                  }
                  autoComplete="off"
                />
              </Stack>
            </FormControl>
          </Stack>
        </DialogTitle>
        <Divider />
        <DialogContent sx={{ p: 2.5 }}>
          {customerlist.length == 0 ? (
            <Stack
              spacing={2}
              direction={"row"}
              alignItems={"center"}
              justifyContent={"center"}
              sx={{ minHeight: 600, maxHeight: 600 }}
            >
              <Empty />
            </Stack>
          ) : (
            <Stack spacing={2} sx={{ minHeight: 600, maxHeight: 600 }}>
              {customerlist &&
                customerlist.map((address, index) => (
                  <Box
                    onClick={() => {
                      setSelectedCustomer(address);
                      setIsCustomerOpen(false);
                      setdispercent(0);
                      settaxpercent(0);
                      setdisamt(0);
                      settaxamt(0);
                    }}
                    key={index}
                    sx={{
                      width: "100%",
                      border: "1px solid",
                      borderColor: "grey.200",
                      borderRadius: 1,
                      p: 1.25,
                      cursor: "pointer",
                      "&:hover": {
                        bgcolor: "#e1bee7",
                      },
                    }}
                  >
                    <Typography textAlign="left" variant="subtitle1">
                      {`${address.tenantname} (${address.primarycontact}) `}
                    </Typography>
                    <Stack direction={{ xs: "column", sm: "row" }} spacing={1}>
                      <Typography
                        textAlign="left"
                        variant="body2"
                        color="secondary"
                      >
                        {` ${address.address} `}
                      </Typography>
                    </Stack>
                  </Box>
                ))}
            </Stack>
          )}
        </DialogContent>
        <Divider />
        <DialogActions sx={{ p: 2.5 }}>
          <Button
            color="error"
            variant="outlined"
            sx={{
              "&:hover": {
                bgcolor: "red",
                color: "white",
              },
            }}
            onClick={() => {
              setIsCustomerOpen(false);
              setSelectedCustomer("");
              setDeliveryList("");
            }}
          >
            Cancel
          </Button>
          {/* <Button
            onClick={() => {
              setIsCustomerOpen(false);
            }}
            color="primary"
            variant="contained"
          >
            ok
          </Button> */}
        </DialogActions>
      </Dialog>
      {/* ============================================= || Preview Dialog || ============================================= */}
      <Dialog
        open={predialog}
        onClose={() => {
          setpredialog(false);
        }}
        maxWidth="md"
        sx={{
          "& .MuiDialog-paper": {
            p: 0,
            minWidth: { xl: 1200, sm: "calc(100% - 20%)" },
          },
          "& .MuiBackdrop-root": { opacity: "0.5 !important" },
        }}
      >
        <Box sx={{ pb: 2.5 }}>
          {/* This element is to trick the browser into centering the modal contents. */}
          <span aria-hidden="true">&#8203;</span>

          <div ref={componentRef}>
            <Box id="print" sx={{ p: 2.5 }}>
              <Box sx={{ pb: 2.5 }}>
                <Stack
                  sx={{
                    flexDirection: { xs: "column", sm: "row" },
                    bgcolor: theme.palette.primary.main,
                    px: 3,
                  }}
                  justifyContent="space-between"
                >
                  <Box sx={{ pt: 2.5 }}>
                    <Stack direction="row" spacing={2}>
                      <img src={nearleLogo} />{" "}
                      {/* <Chip label="Paid" variant="light" color="success" /> */}
                    </Stack>
                    {/* <Typography sx={{ color: "white", pl: 4 }}>
                    {invoiceNo || "000-0000"}
                  </Typography> */}
                  </Box>
                  <Box sx={{ pt: 2.5, pb: 1.75 }}>
                    <Stack direction="row" justifyContent="space-between">
                      <Typography
                        sx={{ pl: 4, color: "white" }}
                        variant="subtitle1"
                      >
                        Date :{" "}
                      </Typography>
                      <Typography sx={{ color: "white" }}>
                        {dayjs(invoiceDate).format("DD-MM-YYYY")}
                      </Typography>
                    </Stack>
                    <Stack direction="row" justifyContent="space-between">
                      <Typography
                        sx={{ pr: 2, overflow: "hidden", color: "white" }}
                        variant="subtitle1"
                      >
                        Due Date :
                      </Typography>
                      <Typography sx={{ color: "white" }}>
                        {dayjs(dueDate).format("DD-MM-YYYY")}
                      </Typography>
                    </Stack>
                  </Box>
                </Stack>
                <Box sx={{ pt: 2.5 }}>
                  <Grid
                    container
                    spacing={2}
                    justifyContent="space-between"
                    direction="row"
                  >
                    <Grid item xs={12} sm={6}>
                      <Box
                        sx={{
                          border: 1,
                          minHeight: 240,
                          borderColor: "grey.200",
                          borderRadius: 0.5,
                          p: 2.5,
                        }}
                      >
                        <Grid container direction="row">
                          <Grid item md={8}>
                            <Stack spacing={2}>
                              <Typography variant="h5">From:</Typography>
                              <Stack sx={{ width: "100%" }}>
                                <Typography variant="subtitle1">
                                  Nearle Technology Private Limited.
                                </Typography>
                                <Typography color="secondary">
                                  424, 4<sup>th</sup>floor,
                                </Typography>
                                <Typography color="secondary">
                                  Red rose towers,
                                </Typography>
                                <Typography color="secondary">
                                  DB Road, RS Puram,
                                </Typography>
                                <Typography color="secondary">
                                  641002.
                                </Typography>
                                <Typography color="secondary">
                                  care@nearle.in
                                </Typography>
                                <Typography color="secondary">
                                  9087368666
                                </Typography>
                              </Stack>
                            </Stack>
                          </Grid>
                        </Grid>
                      </Box>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Box
                        sx={{
                          border: 1,
                          minHeight: 240,
                          borderColor: "grey.200",
                          borderRadius: 0.5,
                          p: 2.5,
                        }}
                      >
                        <Grid container direction="row">
                          <Grid item md={8}>
                            <Stack spacing={2}>
                              <Typography variant="h5">To:</Typography>
                              <Stack sx={{ width: "100%" }}>
                                <Typography variant="subtitle1">
                                  {selectedCustomer.companyname}
                                </Typography>
                                <Typography color="secondary">
                                  {selectedCustomer.address}
                                </Typography>
                                <Typography color="secondary">
                                  {selectedCustomer.postcode}
                                </Typography>
                                <Typography color="secondary">
                                  {selectedCustomer.primaryemail}
                                </Typography>
                                <Typography color="secondary">
                                  {selectedCustomer.primarycontact}
                                </Typography>
                              </Stack>
                            </Stack>
                          </Grid>
                        </Grid>
                      </Box>
                    </Grid>
                  </Grid>
                </Box>
              </Box>
              <TableContainer ref={pdfRef}>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>#</TableCell>
                      <TableCell>Date</TableCell>
                      <TableCell>Order Id</TableCell>
                      <TableCell>Pickup</TableCell>
                      <TableCell>Drop</TableCell>
                      <TableCell>Customer</TableCell>
                      <TableCell>Contact no</TableCell>
                      <TableCell>KMS</TableCell>
                      <TableCell>Amount</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {deliveryList &&
                      deliveryList.map((item, index) => (
                        <TableRow key={index}>
                          <TableCell>{index + 1}</TableCell>
                          <TableCell>
                            <stack direction={"column"}>
                              <Typography variant="body2">
                                {dayjs(item.deliverydate).format("DD-MM-YYYY")}
                              </Typography>

                              <Typography variant="caption">
                                {dayjs(item.deliverydate).format("hh:mm a")}
                              </Typography>
                            </stack>
                          </TableCell>
                          <TableCell>
                            {" "}
                            <Typography variant="caption">
                              {item.orderid}{" "}
                            </Typography>
                          </TableCell>

                          <TableCell>
                            {" "}
                            <Typography variant="caption">
                              {item.pickuplocation}{" "}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant="caption">
                              {item.deliverylocation}{" "}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant="caption">
                              {" "}
                              {item.deliverycustomer}{" "}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant="caption">
                              {item.deliverycontactno}{" "}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant="caption">
                              {item.actualkms == "" || 0
                                ? parseInt(item.kms).toFixed(1)
                                : parseInt(item.actualkms).toFixed(1)}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant="caption">
                              {item.deliveryamt == "" || 0
                                ? `₹ ${item.deliverycharges}.00`
                                : `₹ ${item.deliveryamt}.00`}
                            </Typography>
                          </TableCell>
                        </TableRow>
                      ))}
                  </TableBody>
                </Table>
              </TableContainer>
              <Divider />
              <Box sx={{ p: 2.5 }}>
                <Grid container direction="row" justifyContent="flex-end">
                  <Grid item md={4}>
                    <Stack spacing={2}>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography color="secondary">Sub Total:</Typography>
                        <Typography variant="h6">
                          {formatNumberToRupees(totalAmount)}
                        </Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography color="secondary">Discount:</Typography>
                        <Typography
                          variant="h6"
                          color={theme.palette.success.main}
                        >
                          {formatNumberToRupees(disamt)}
                        </Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography color={theme.palette.grey[500]}>
                          Tax:
                        </Typography>
                        <Typography variant="h6">
                          {formatNumberToRupees(taxamt)}
                        </Typography>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Typography sx={{ pr: 2 }} variant="subtitle1">
                          Grand Total:
                        </Typography>
                        <Typography variant="h6">
                          {formatNumberToRupees(Math.round(grandtotal))}
                        </Typography>
                      </Stack>
                    </Stack>
                  </Grid>
                </Grid>
              </Box>
            </Box>
            <Divider />
            <Box sx={{ p: 2.5 }}>
              <Typography>Notes: {notes}</Typography>
            </Box>

            <Divider />
          </div>

          <Stack
            direction="row"
            justifyContent="flex-end"
            spacing={2}
            sx={{ p: 2.5 }}
          >
            <ReactToPrint
              trigger={() => (
                <IconButton>
                  <PrinterFilled style={{ color: theme.palette.grey[900] }} />
                </IconButton>
              )}
              content={() => componentRef.current}
            />

            <Button
              color="secondary"
              onClick={() => {
                setpredialog(false);
              }}
            >
              Cancel
            </Button>
            {/* <PDFDownloadLink
              document={<ExportPDFView list={deliveryList} />}
              fileName={`invoice.pdf`}
              style={{ textDecoration: "none" }}
            > */}
            <Button
              startIcon={<DownloadOutlined />}
              variant="contained"
              color="primary"
              onClick={downloadpdf}
            >
              Download
            </Button>
            {/* </PDFDownloadLink> */}
          </Stack>
        </Box>
      </Dialog>
    </>
  );
};

export default createInvoice;
