import React, { useEffect, useState, useRef } from "react";

import TitleCard from "pages/titleCard";
import HoverSocialCard from "components/cards/statistics/HoverSocialCard";
import { useTheme } from "@mui/material/styles";
import { FilterList } from "@mui/icons-material";
import { DateRangePicker } from "mui-daterange-picker";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import dayjs from "dayjs";
var utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
import { DashboardOutlined } from "@ant-design/icons";
import { HiHandThumbDown, HiHandThumbUp } from "react-icons/hi2";
import LoadingIcons from "react-loading-icons";

// import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import VisibilityIcon from "@mui/icons-material/Visibility";
import {
  addDays,
  addMonths,
  addWeeks,
  addYears,
  endOfMonth,
  endOfWeek,
  endOfYear,
  startOfMonth,
  startOfWeek,
  startOfYear,
} from "date-fns";
import {
  Grid,
  Button,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  Tabs,
  Tab,
  Typography,
  Box,
  OutlinedInput,
  InputAdornment,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  Stack,
  Chip,
} from "@mui/material";
import { enqueueSnackbar } from "notistack";
import Loader from "components/Loader";
import {
  SearchOutlined,
  LeftOutlined,
  RightOutlined,
  PlusCircleFilled,
} from "@ant-design/icons";
import ClearIcon from "@mui/icons-material/Clear";
import { DownloadOutlined, PrinterFilled } from "@ant-design/icons";
import ReactToPrint from "react-to-print";

import nearleLogo from "../../assets/images/nearleLogo.png";

import AddIcon from "@mui/icons-material/Add";
import MainCard from "components/MainCard";
import { CSVExport } from "components/third-party/ReactTable"; // table columns
const columns = [
  { id: "sno", label: "sno" },
  { id: "client", label: "client" },
  { id: "invoice ", label: "Invoice Id " },

  {
    id: "invoice date",
    label: "invoice date",
    align: "left",
    // format: (value) => value.toLocaleString("en-US"),
  },
  {
    id: "due date",
    label: "due date",
    align: "left",
    // format: (value) => value.toLocaleString("en-US"),
  },
  { id: "unit", label: "units", align: "left" },

  {
    id: "itemcount",
    label: "Count",
    align: "left",
    // format: (value) => typeof value === "number" && value.toFixed(2),
  },

  { id: "amount", label: "amount", align: "right" },
  { id: "action", label: "action", align: "center" },
];

// table data

const rows = [];
function CustomTabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    "aria-controls": `simple-tabpanel-${index}`,
  };
}
function formatNumberToRupees(value) {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    minimumFractionDigits: 2,
  }).format(value);
}
const Invoice = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [value, setValue] = React.useState(0);
  const [content, setcontent] = React.useState("one");
  const [opendate, setOpendate] = useState(false);
  const [deliveryList, setDeliveryList] = useState([]);
  const [predialog, setpredialog] = useState(false);
  const [selected, setselected] = useState({});
  const componentRef = useRef(null);
  const [billStatus, setBillStatus] = useState(0);
  const [isloader, setIsLoader] = useState(false);
  const [insightdata, setinsightdata] = useState(false);
  const textFieldRef = useRef(null);
  /* ============================================= || 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);
    };
  }, []);

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

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event?.target?.value);
    setPage(0);
  };

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };
  const okclicked = () => {
    setOpendate(false);
  };
  /* ============================================= || fetchinvoiceinsight| ============================================= */
  const fetchinvoiceinsight = async () => {
    try {
      const insightResponse = await axios.get(
        `${process.env.REACT_APP_URL}/invoice/getinvoiceinsight`
      );
      console.log("insightResponse", insightResponse.data.details);
      setinsightdata(insightResponse.data.details);
    } catch (error) {
      console.log("insightResponse", error);
    }
  };
  useEffect(() => {
    fetchinvoiceinsight();
  }, []);
  /* ============================================= || fetchdeliverylist| ============================================= */
  const fetchdeliverylist = async () => {
    setIsLoader(true);
    console.log("billstatus", billStatus);
    try {
      let url =
        billStatus == 0
          ? `${process.env.REACT_APP_URL}/invoice/getallinvoice`
          : `${process.env.REACT_APP_URL}/invoice/getallinvoice/?billstatus=${billStatus}`;

      const deliveyResponse = await axios.get(url);
      console.log("fetchdeliverylist", deliveyResponse.data.details);
      setDeliveryList(deliveyResponse.data.details);
      setIsLoader(false);
    } catch (error) {
      console.log("fetchdeliverylist", error);
    }
  };
  useEffect(() => {
    fetchdeliverylist();
  }, [billStatus]);
  useEffect(() => {
    console.log("selected", selected);
  }, [selected]);

  return (
    <>
      {isloader && <Loader />}
      {/* ============================================= || TitleCard || ============================================= */}
      <Grid container>
        <Grid item xs={6}>
          <TitleCard title="Invoice" sx={{ bgcolor: "green" }} />{" "}
        </Grid>
        <Grid
          item
          xs={6}
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "end",
            mb: 3,
          }}
        >
          <Button
            component="label"
            variant="contained"
            startIcon={<AddIcon style={{ fontSize: "20px" }} />}
            onClick={() => {
              navigate("/invoice/create");
            }}
          >
            Create Invoice
          </Button>
        </Grid>
      </Grid>
      {/* ============================================= || Create Invoice || ============================================= */}
      <Grid container sx={{}}></Grid>
      {/* ============================================= || Hover Social Card  || ============================================= */}
      <Grid container spacing={3}>
        {" "}
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setValue(0);
            setBillStatus(0);
            setcontent("one");
          }}
        >
          <HoverSocialCard
            primary="All"
            secondary={insightdata.totalcount}
            iconPrimary={DashboardOutlined}
            color={theme.palette.primary.main}
          />
        </Grid>{" "}
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setValue(1);
            setBillStatus(1);
            setcontent("two");
          }}
        >
          <HoverSocialCard
            primary="0pen"
            secondary={insightdata.pendingcount}
            iconPrimary={LoadingIcons.ThreeDots}
            color={theme.palette.error.main}
          />
        </Grid>
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setValue(2);
            setBillStatus(2);
            setcontent("three");
          }}
        >
          <HoverSocialCard
            primary="Overdue"
            secondary={insightdata.overduecount}
            iconPrimary={HiHandThumbDown}
            color={theme.palette.warning.main}
          />
        </Grid>
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: "pointer" }}
          onClick={() => {
            setValue(3);
            setBillStatus(3);
            setcontent("four");
          }}
        >
          <HoverSocialCard
            primary="Paid"
            secondary={insightdata.paidcount}
            color={theme.palette.success.main}
            iconPrimary={HiHandThumbUp}
          />
        </Grid>
      </Grid>
      {/* ============================================= || Invoice Table || ============================================= */}
      <MainCard
        content={false}
        title={
          <Grid container sx={{}}>
            <Grid item xs={9} sx={{}}>
              <Tabs
                value={value}
                onChange={handleChange}
                aria-label="basic tabs example"
                sx={{ mt: -1, mb: -2 }}
              >
                <Tab
                  label="All"
                  {...a11yProps(0)}
                  onClick={() => {
                    setValue(0);
                    setBillStatus(0);
                    setcontent("one");
                  }}
                />
                <Tab
                  label="Open"
                  {...a11yProps(1)}
                  onClick={() => {
                    setValue(1);
                    setBillStatus(1);
                    setcontent("two");
                  }}
                />
                <Tab
                  label="Overdue"
                  {...a11yProps(2)}
                  onClick={() => {
                    setValue(2);
                    setBillStatus(2);
                    setcontent("three");
                  }}
                />
                <Tab
                  label="Paid"
                  {...a11yProps(3)}
                  onClick={() => {
                    setValue(3);
                    setBillStatus(3);
                    setcontent("four");
                  }}
                />
              </Tabs>
            </Grid>
            <Grid item xs={3} sx={{ display: "flex", justifyContent: "end" }}>
              <Stack sx={{ mr: 2 }}>
                <OutlinedInput
                  inputRef={textFieldRef}
                  id="input-search-header"
                  placeholder="Search "
                  // value={search}
                  onChange={(e) => {}}
                  sx={{
                    "& .MuiOutlinedInput-input": {
                      p: "1.5px 0px 1px",
                    },
                    width: "100%",
                  }}
                  //   style={{ margin: "15px 20px" }}
                  startAdornment={
                    <InputAdornment position="start">
                      <SearchOutlined
                        style={{
                          fontSize: "medium",

                          fontWeight: "bolder",
                        }}
                      />
                    </InputAdornment>
                  }
                  endAdornment={
                    <IconButton
                      // sx={{ visibility: search ? "visible" : "hidden" }}
                      onClick={() => {}}
                    >
                      <ClearIcon
                        style={{ fontSize: "medium", color: "#65387A" }}
                      />
                    </IconButton>
                  }
                />
              </Stack>
              {/* <Tooltip title="Order Filter">
                <IconButton
                  color="secondary"
                  variant="light"
                  sx={{
                    color: "text.primary",
                    bgcolor: "grey.200",
                    mr: 2,
                  }}
                  aria-haspopup="true"
                  onClick={() => setOpendate(true)}
                >
                  <FilterList />
                </IconButton>
              </Tooltip> */}
            </Grid>
          </Grid>
        }
        // secondary={<CSVExport data={rows} filename={"sticky-table-data.csv"} />}
        sx={{ mt: 3 }}
      >
        <CustomTabPanel value={value} index={value}>
          <TableContainer
            sx={{
              maxHeight: 430,
              mt: -3,
              "&::-webkit-scrollbar": {
                width: "4px", // Width of vertical scrollbar
                height: "4px", // Height of horizontal scrollbar
              },
              "&::-webkit-scrollbar-thumb": {
                backgroundColor: "#65387A", // Color of the scrollbar thumb
              },
            }}
          >
            <Table stickyHeader aria-label="sticky table" sx={{}}>
              <TableHead
                sx={{
                  "& th": {
                    borderTop: `1px solid ${theme.palette.divider}`,
                    borderBottom: `2px solid ${theme.palette.divider} !important`,
                  },
                }}
              >
                <TableRow>
                  {columns.map((column) => (
                    <TableCell
                      sx={{
                        minWidth: column.minWidth,
                        position: "sticky !important",
                      }}
                      key={column.id}
                      align={column.align}
                    >
                      {column.label}
                    </TableCell>
                  ))}
                </TableRow>
              </TableHead>
              <TableBody>
                {deliveryList
                  .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                  .map((item, index) => (
                    // <TableRow
                    //   sx={{ py: 3 }}
                    //   hover
                    //   role="checkbox"
                    //   tabIndex={-1}
                    //   key={row.code}
                    // >
                    //   {columns.map((column) => {
                    //     const value = row[column.id];
                    //     return (
                    //       <TableCell key={column.id} align={column.align}>
                    //         {column.format && typeof value === "number"
                    //           ? column.format(value)
                    //           : value}
                    //       </TableCell>
                    //   );
                    //   })}

                    // </TableRow>
                    <TableRow key={index}>
                      <TableCell>{index + 1}</TableCell>
                      <TableCell>
                        <Typography>{item.tenantname} </Typography>

                        <Typography variant="caption" color={"secondary"}>
                          {item.contactperson}{" "}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="caption">
                          {item.invoiceno}{" "}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <stack direction={"column"}>
                          <Typography variant="caption">
                            {dayjs(item.transactiondate).format("DD-MM-YYYY")}
                          </Typography>
                          <br />
                          <Typography variant="caption">
                            {dayjs(item.transactiondate)
                              .utc()
                              .format("hh:mm a")}
                          </Typography>
                        </stack>
                      </TableCell>
                      <TableCell>
                        <stack direction={"column"}>
                          <Typography variant="caption">
                            {dayjs(item.duedate).format("DD-MM-YYYY")}
                          </Typography>
                          <br />
                          <Typography variant="caption">
                            {dayjs(item.duedate).utc().format("hh:mm a")}
                          </Typography>
                        </stack>
                      </TableCell>

                      <TableCell>
                        {" "}
                        <Typography variant="caption">
                          {item.pricingtype}{" "}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        {" "}
                        <Typography variant="caption">
                          {item.itemcount}
                        </Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="caption">
                          {formatNumberToRupees(item.totalamount)}
                        </Typography>
                      </TableCell>
                      <TableCell align="center">
                        <IconButton
                          sx={{
                            "&:hover": {
                              color: theme.palette.primary.main,
                            },
                          }}
                          onClick={() => {
                            setIsLoader(true);
                            console.log("selected", item);
                            setselected(item);
                            setTimeout(() => {
                              setIsLoader(false);
                              // setpredialog(true);
                              navigate("/invoice/preview", {
                                state: item,
                              });
                            }, 500);
                          }}
                        >
                          <VisibilityIcon fontSize="small" />
                        </IconButton>{" "}
                      </TableCell>
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          </TableContainer>
        </CustomTabPanel>

        <Divider />
        {/* table pagination */}
        <TablePagination
          rowsPerPageOptions={[5, 10, 25, 100]}
          component="div"
          count={deliveryList.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </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>
      {/* ============================================= || 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" },
        }}
      >
        {selected && (
          <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: "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(selected.transactiondate).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(selected.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">
                                    {selected.tenantname}
                                  </Typography>
                                  <Typography color="secondary">
                                    {selected.address}
                                  </Typography>
                                  <Typography color="secondary">
                                    {selected.suburb}
                                  </Typography>
                                  <Typography color="secondary">
                                    {selected.city}
                                  </Typography>
                                  <Typography color="secondary">
                                    {selected.state}
                                  </Typography>{" "}
                                </Stack>
                              </Stack>
                            </Grid>
                          </Grid>
                        </Box>
                      </Grid>
                    </Grid>
                  </Box>
                </Box>
                <TableContainer>
                  <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>
                    {selected.tenantsalesdetails && (
                      <TableBody>
                        {selected.tenantsalesdetails.map((item, index) => (
                          <TableRow key={index}>
                            <TableCell>{index + 1}</TableCell>
                            <TableCell>
                              <stack direction={"column"}>
                                <Typography variant="body2">
                                  {dayjs(item.orderdate).format("DD-MM-YYYY")}
                                </Typography>

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

                            <TableCell>
                              {" "}
                              <Typography variant="caption">
                                {item.pickup}{" "}
                              </Typography>
                            </TableCell>
                            <TableCell>
                              <Typography variant="caption">
                                {item.drop}{" "}
                              </Typography>
                            </TableCell>
                            <TableCell>
                              <Typography variant="caption">
                                {formatNumberToRupees(item.totalamount)}
                              </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(selected.salesamount)}
                          </Typography>
                        </Stack>
                        <Stack direction="row" justifyContent="space-between">
                          <Typography color="secondary">Discount:</Typography>
                          <Typography
                            variant="h6"
                            color={theme.palette.success.main}
                          >
                            {formatNumberToRupees(selected.discountamt)}
                          </Typography>
                        </Stack>
                        <Stack direction="row" justifyContent="space-between">
                          <Typography color={theme.palette.grey[500]}>
                            Tax:
                          </Typography>
                          <Typography variant="h6">
                            {formatNumberToRupees(selected.taxamount)}
                          </Typography>
                        </Stack>
                        <Stack direction="row" justifyContent="space-between">
                          <Typography sx={{ pr: 2 }} variant="subtitle1">
                            Grand Total:
                          </Typography>
                          <Typography variant="h6">
                            {formatNumberToRupees(
                              Math.round(selected.totalamount)
                            )}
                          </Typography>
                        </Stack>
                      </Stack>
                    </Grid>
                  </Grid>
                </Box>
              </Box>
              <Divider />
              <Box sx={{ p: 2.5 }}>
                <Typography>Notes: {selected.remarks}</Typography>
              </Box>

              <Divider />
            </div>

            <Stack
              direction="row"
              justifyContent="flex-end"
              spacing={2}
              sx={{ p: 2.5 }}
            >
              <Button
                variant="outlined"
                color="error"
                onClick={() => {
                  setpredialog(false);
                }}
              >
                Cancel
              </Button>
              <ReactToPrint
                trigger={() => (
                  // <IconButton>
                  //   <PrinterFilled style={{ color: theme.palette.grey[900] }} />
                  // </IconButton>
                  <Button
                    startIcon={<PrinterFilled />}
                    variant="outlined"
                    color="primary"
                    // onClick={downloadpdf}
                  >
                    Print
                  </Button>
                )}
                content={() => componentRef.current}
              />

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

export default Invoice;
