import React from "react";
import { useState, useEffect, useRef } from "react";
import axios from "axios";
import { enqueueSnackbar } from "notistack";
import nearleLogo from "../../assets/images/nearleLogo.png";
import logo_nearle1 from "../../assets/images/logo-nearle1.png";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { FaArrowLeft } from "react-icons/fa6";
import {
  DownloadOutlined,
  PrinterFilled,
  PlusOutlined,
} from "@ant-design/icons";
import ReactToPrint from "react-to-print";
import dayjs from "dayjs";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-router-dom";
import { useTheme } from "@mui/material/styles";

import {
  Grid,
  InputLabel,
  TextField,
  Stack,
  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 MainCard from "components/MainCard";

const CreateInvoicePreview = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const componentRef = useRef(null);
  const location = useLocation();

  const {
    selectedCustomer,
    deliveryList,
    invoiceNo,
    invoiceDate,
    dueDate,
    totalAmount,
    disamt,
    taxamt,
    grandtotal,
    notes,
    contPerson,
    invoiceId,
    dispercent,
    taxpercent,
    startdate,
    enddate,
    tenantPricing,
    orderdetails,
    otherCharges,
    ordercount,
  } = location.state;

  console.log("selectedCustomer", selectedCustomer);
  console.log("deliveryList", deliveryList);
  console.log("invoiceNo", invoiceNo);
  console.log("invoiceDate", invoiceDate);
  console.log("dueDate", dueDate);
  console.log("totalAmount", totalAmount);
  console.log("disamt", disamt);
  console.log("taxamt", taxamt);
  console.log("grandtotal", grandtotal);
  console.log("notes", notes);
  console.log("ordercount", ordercount);

  function formatNumberToRupees(value) {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      minimumFractionDigits: 2,
    }).format(value);
  }

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

  // ==============================|| createInvoice||============================== //
  const createInvoice = async () => {
    let obj = {
      salesid: 0,
      transactiondate: invoiceDate,
      duedate: dueDate,
      applocationid: selectedCustomer.applolcationid,
      invoiceno: invoiceNo,
      invoiceid: invoiceId,
      tenantid: selectedCustomer.tenantid,
      tenantpricingid: tenantPricing.tenantpricingid,
      Pricingtypeid: tenantPricing.pricingtypeid,
      Pricingtype: tenantPricing.slab,
      tenantname: selectedCustomer.tenantname,
      contactperson: contPerson || "",
      address: selectedCustomer.address,
      suburb: selectedCustomer.suburb,
      city: selectedCustomer.city,
      state: selectedCustomer.state,
      // itemcount: deliveryList.length,
      itemcount: ordercount,
      salesamount: totalAmount,
      discountpercent: parseInt(dispercent),
      discountamt: parseInt(disamt),
      taxpercent: parseInt(taxpercent),
      taxamount: +taxamt.toFixed(2),
      totalamount: Math.round(grandtotal),
      remarks: notes,
      tenantsalesdetails: [
        {
          salesdetailid: 0,
          salesid: 0,
          tenantid: selectedCustomer.tenantid,
          particulars: `Invoice from ${dayjs(startdate).format(
            "DD-MM-YYYY"
          )} to ${dayjs(enddate).format("DD-MM-YYYY")}`,
          fromdate: startdate,
          todate: enddate,
          pricingtypeid: tenantPricing.pricingtypeid,
          pricingtype: tenantPricing.slab,
          baserate: parseFloat(tenantPricing.priceperkm),
          quantity: parseFloat(orderdetails.actualkms),
          amount: totalAmount,
          othercharges: parseFloat(otherCharges),
          taxpercent: parseInt(taxpercent),
          taxamount: +taxamt.toFixed(2),
          totalamount: Math.round(grandtotal),
        },
      ],
    };

    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: 2000,
            });
          }
          navigate("/invoice");
        })
        .catch((err) => {
          console.log(err);

          enqueueSnackbar(err.message, {
            variant: "error",
            anchorOrigin: { vertical: "top", horizontal: "right" },
            autoHideDuration: 2000,
          });
        });
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <>
      <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/create");
              }}
            >
              <FaArrowLeft size={"large"} />
            </IconButton>
          </Tooltip>

          <Stack alignItems={"center"}>
            <Typography variant="h3" color={"primary"}>
              Invoice Details
            </Typography>
            <Chip
              size="small"
              color="warning"
              variant="outlined"
              sx={{ bgcolor: theme.palette.warning.lighter }}
              label={`Invoice No :${"\u00a0\u00a0"}${invoiceNo}`}
            />
          </Stack>
        </Stack>
        <Stack
          direction="row"
          justifyContent="flex-end"
          spacing={4}
          sx={{ px: 2.5, py: 1, bgcolor: "#eee" }}
        >
          <ReactToPrint
            trigger={() => (
              <Button
                size="small"
                startIcon={<PrinterFilled />}
                variant="outlined"
                color="primary"
                sx={{
                  "&:hover": {
                    backgroundColor: "primary.main",
                    color: "primary.contrastText",
                  },
                }}
              >
                Print
              </Button>
            )}
            content={() => componentRef.current}
          />
          <Button
            size="small"
            // disabled={selectedCustomer == "" ? true : false}
            startIcon={<PlusOutlined />}
            variant="contained"
            color="primary"
            onClick={() => {
              createInvoice();
            }}
          >
            Save
          </Button>
        </Stack>
      </Stack>

      <Box sx={{ pb: 1 }}>
        <div ref={componentRef}>
          <Box id="print" sx={{ p: 2.5 }}>
            <Box sx={{ pb: 2.5 }}>
              <Stack
                sx={{
                  flexDirection: "row",
                  border: "1px solid #eee",
                  px: 3,
                }}
                justifyContent="space-between"
              >
                <Box sx={{ pt: 0.5 }}>
                  <Stack direction="row" spacing={2}>
                    <img
                      src={logo_nearle1}
                      style={{ width: "150px", height: "50px" }}
                    />{" "}
                  </Stack>
                  {/* <Typography sx={{ color: "white", py: 0.5 }}>
                    {`Invoice No: ${"\u00a0\u00a0\u00a0"}${invoiceNo}`}
                  </Typography> */}
                  <Stack direction="row" justifyContent="space-between">
                    <Typography
                      sx={{
                        overflow: "hidden",
                        color: theme.palette.primary.main,
                      }}
                      variant="subtitle1"
                    >
                      Invoice No :
                    </Typography>
                    <Typography sx={{ color: theme.palette.primary.main }}>
                      {`${"\u00a0\u00a0"}${invoiceNo}`}
                    </Typography>
                  </Stack>
                </Box>
                <Box sx={{ pt: 2.5, pb: 1.75 }}>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography
                      sx={{ pl: 4, color: theme.palette.primary.main }}
                      variant="subtitle1"
                    >
                      Date :{" "}
                    </Typography>
                    <Typography sx={{ color: theme.palette.primary.main }}>
                      {dayjs(invoiceDate).format("DD-MM-YYYY")}
                    </Typography>
                  </Stack>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography
                      sx={{
                        pr: 2,
                        overflow: "hidden",
                        color: theme.palette.primary.main,
                      }}
                      variant="subtitle1"
                    >
                      Due Date :
                    </Typography>
                    <Typography sx={{ color: theme.palette.primary.main }}>
                      {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>
            <MainCard>
              {" "}
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>S.No</TableCell>
                      <TableCell>Particulars</TableCell>
                      <TableCell>Units</TableCell>
                      <TableCell>Quantity</TableCell>
                      <TableCell align="right">Rate</TableCell>
                      <TableCell align="right">Charge</TableCell>
                      {/* {tenantPricing && tenantPricing.pricingtypeid === 73 && ( */}
                      <TableCell align="right">Other Charges</TableCell>
                      {/* )} */}
                      <TableCell align="right">Amount</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    <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>
                      {/* {tenantPricing.pricingtypeid == 73 && ( */}
                      <TableCell align="right">
                        <Typography>{`₹ ${otherCharges}.00`}</Typography>
                      </TableCell>
                      {/* )} */}
                      <TableCell align="right">
                        <Typography>
                          {`₹ ${(
                            Number(orderdetails.actualkms) *
                              Number(tenantPricing.priceperkm) +
                            Number(otherCharges)
                          ).toFixed(2)}`}
                          {/* {item.deliverylocation}{" "} */}
                        </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">
                        <Stack
                          direction="row"
                          justifyContent={"center"}
                          alignItems={"center"}
                        >
                          <Typography color="secondary">Discount</Typography>
                          <Typography
                            variant="h6"
                            color={theme.palette.secondary.main}
                            sx={{ fontSize: "12px" }}
                          >
                            {`(${dispercent}%):`}
                          </Typography>
                        </Stack>
                        <Stack
                          direction="row"
                          justifyContent={"center"}
                          alignItems={"center"}
                        >
                          <Typography
                            variant="h6"
                            color={theme.palette.error.main}
                          >
                            {`- ${formatNumberToRupees(disamt)}`}
                          </Typography>
                        </Stack>
                      </Stack>
                      <Stack direction="row" justifyContent="space-between">
                        <Stack
                          direction="row"
                          justifyContent={"center"}
                          alignItems={"center"}
                        >
                          <Typography color={theme.palette.grey[500]}>
                            Tax
                          </Typography>
                          <Typography
                            variant="h6"
                            color={theme.palette.secondary.main}
                            sx={{ fontSize: "12px" }}
                          >
                            {`(${taxpercent}%):`}
                          </Typography>
                        </Stack>
                        <Typography
                          variant="h6"
                          color={theme.palette.success.main}
                        >
                          + {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>
            </MainCard>
          </Box>
          <Divider />
          <Box sx={{ p: 2.5 }}>
            <Typography>Notes: {notes}</Typography>
          </Box>

          <Divider />
        </div>
      </Box>
    </>
  );
};

export default CreateInvoicePreview;
