import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {
  Form,
  Table,
  Input,
  Select,
  AutoComplete,
  Radio,
  DatePicker,
  Button,
  Tooltip,
  Space,
  Segmented,
} from 'antd';
import { BsUpcScan } from "react-icons/bs";
import {
  ArrowRightOutlined,
  DeleteFilled,
  SearchOutlined,
} from '@ant-design/icons';
import { IoMdAddCircleOutline } from 'react-icons/io';
import { FaEye, FaPrint, FaTruck } from 'react-icons/fa';
import { Messages } from '../../Components/Notifications/Messages.jsx';
import { InputField } from '../../Components/Forms/InputField.jsx';
import Buttons from '../../Components/Forms/Buttons.jsx';
import {
  getSession,
  pdfDiv,
  printDiv,
  validateSafeInput,
} from '../../Services/Others.js';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';
import { CiBarcode } from 'react-icons/ci';
import {
  AdminUserData,
  getProdQuoaVariantdata,
  getPurProductData,
} from '../../Features/PurchaseQuotation/PurchaseQuotation.js';
import './DeliveryChallan.scss';
import { getPurchaseTaxTypeData } from '../../Features/StockMaster/StockMaster.js';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
import { useAuth } from '../../AuthContext.jsx';
import { getAllCustomerAndBranch, PendingOrdersDC } from '../../Features/BookingScreen/BookingData/BookingData.js';
const subDirectory = import.meta.env.BASE_URL;
import TooltipWrapper from '../../Components/Tooltip/Tooltip.jsx';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';
import { PostChallan } from '../../Features/DeliveryChallan/DeliveryChallan.js';
import { MdOutlineMail } from 'react-icons/md';
import DeliveryPrint from './DeliveryPrint.jsx';
import { Emailsend } from '../../Features/PurchaseOrder/PurchaseOrder.js';
import FloatLabel from '../../Components/Forms/FloatLabel/index.jsx';
import { debounce } from 'lodash';
import { DCPrintStyleFunction } from './DCPrintStyleFunction.js';
import { useSelector } from 'react-redux';
import { getPrintSelectionComponentData } from '../../Features/ThemeChange/ThemeChange.js';
import { DCPDFMobilePrint } from './DCPDFMobilePrint.js';
import { isMobile } from 'react-device-detect';

const DeliveryChellanForm = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Delivery challan'
  );
  const formRef = useRef(null);
  const transportFormRef = useRef(null);

  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');
  const [DCPrintTemplateStyle, setDCPrintTemplateStyle] = useState(null);
  const [DCPrintTemplateDtl, setDCPrintTemplateDtl] = useState(null);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [SelecAdminUser, setSelecAdminUser] = useState(null);
  const [SelTaxType, setSelTaxType] = useState(null);
  const [SelTaxTypeName, setSelTaxTypeName] = useState(null);
  const [ProductData, setProductData] = useState([]);
  const [AllCustomer, setAllCustomer] = useState(null);
  const [Modal, setModal] = useState(false);
  const [SelProduct, setSelProduct] = useState(null);
  const [selectedProductName, setSelectedProductName] = useState(null);
  const [productSearchText, setProductSearchText] = useState("");
  const [scanner, setScanner] = useState(false);
  const [Variants, setVariants] = useState([]);
  const [TableData, setTableData] = useState([]);
  const [editingKey, setEditingKey] = useState('');
  const [ordersCustomer, setOrdersCustomer] = useState([]);
  const [TotalBillAmount, setTotalBillAmount] = useState(null);
  const [TotalCgst, setTotalCgst] = useState(null);
  const [TotalSgst, setTotalSgst] = useState(null);
  const [TotalIgst, setTotalIgst] = useState(null);
  const [TotalAmount, setTotalAmount] = useState(null);
  const isEditing = (record, index) => index === editingKey;
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const [selectedMode, setSelectedMode] = useState('');
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [PrintingData, setPrintingData] = useState([]);
  const [iSEmail, setiSEmail] = useState(false);
  const [pendingOrderDetails, setPendingOrderDetails] = useState(null);
  const [pendingRecord, setPendingRecord] = useState(null);
  const [segmentValue, setSegmentValue] = useState("N")
  const [selectedOrder, setSelectedOrder] = useState();
  const [orderTableData, setOrderTableData] = useState([]);

  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
    {
      name: 'Delivery Challan',
      link: `${subDirectory}setting/delivery-challan`,
    },
  ];


  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    getProduct();
    fetchdata();
    getPrintData();
  }, []);

  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);
  useEffect(() => {
    let hasAccess = false;

    if (UserType === 'Admin' || UserType === 'Super Admin') {
      hasAccess = true;
    } else if (UserType === 'Employee') {
      hasAccess = empData?.AddAccess === 'Y';
    } else if (UserType === 'Super Admin User') {
      hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
    }

    setaddnewAccess(!hasAccess);
  }, [empData, SAAccessCommonMaster, UserType]);
  const debouncedScannerSearch = useCallback(
    debounce((value) => {
      const qr = value?.trim();

      const matchedProduct = ProductData.find(
        (p) => p.QRCode?.toLowerCase() === qr?.toLowerCase()
      );
      if (matchedProduct) {
        let productName = {};
        productName.label = `${matchedProduct?.ProdName} (${matchedProduct.Size} ${matchedProduct.UomName})${matchedProduct?.BrandName ? ` - ${matchedProduct?.BrandName}` : ''}`
        ProductDropDownChange(matchedProduct.ProdId, productName);
        if (matchedProduct?.ProdVariantPriceDetails?.length < 2) {
          setSelectedProductName("");
          setSelProduct(null)
        }
      } else {
        setMessageType("error");
        setMessageData("The Scanned Product not Available in Product List")
      }
    }, 300),
    [ProductData]
  );
  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Purchase Quotation'
    );
    setEmpData(datas?.[0]);
  };
  const getPrintData = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    let response = await dispatch(getPrintSelectionComponentData(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      let DCPrintTemplate =
        response?.data?.data?.[0]?.ComponentDetails?.find(
          (item) => item.SetasDefault == 'Y' && item.PrintTypeName === 'Delivery Chalan'
        );
      console.log(DCPrintTemplate, response?.data?.data?.[0]?.ComponentDetails?.find(
        (item) => item.SetasDefault == 'Y' && item.PrintTypeName === 'Delivery Chalan'
      ), 'DCPrintTemplate');
      setDCPrintTemplateStyle(DCPrintTemplate?.StyleName);
      setDCPrintTemplateDtl(DCPrintTemplate);
    }


  };
  // useEffect(() => {
  //   Print();
  // }, [PrintData]);
  useEffect(() => {
    let total = TableData?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.NetAmt;
    }, 0);
    setTotalAmount(total);
    let cgst = TableData?.filter(
      (item) => item.TaxName?.toLowerCase() === 'cgst,sgst'
    );
    let totalgst = cgst?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.TaxAmt;
    }, 0);
    setTotalCgst(totalgst / 2);
    setTotalSgst(totalgst / 2);
    let igst = TableData?.filter(
      (item) => item.TaxName?.toLowerCase() === 'igst'
    );
    let totaligst = igst?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.TaxAmt;
    }, 0);
    setTotalIgst(totaligst);
    let billtotal = TableData?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.NetAmt;
    }, 0);
    console.log(billtotal, total, TableData, 'billtotal');
    setTotalBillAmount(billtotal);
  }, [TableData]);
  const getProduct = async () => {
    let Product = await dispatch(
      getPurProductData({
        CompId: CompId,
        AppId: AppId,
        BranchId: BranchId,
        ActiveStatus: 'A',
      })
    ).unwrap();
    if (Product?.data?.statusCode === 1) {
      let Productonlydata = Product?.data?.data?.filter(
        (item) => item?.ProdTypeName === 'Product'
      );

      setProductData(Productonlydata);
    } else {
      setProductData([]);
    }
  };
  console.log(AllCustomer, "AllCustomerAllCustomer")
  const fetchdata = async () => {
    try {
      const resCustomer = await dispatch(getAllCustomerAndBranch({ CompId, AppId, BranchId })).unwrap();
      if (resCustomer?.data?.statusCode === 1) {
        setAllCustomer(resCustomer?.data?.data);

      } else {
        setAllCustomer([]);
        setMessageType("error");
        setMessageData(resCustomer?.data?.response);
      }

      const resOrders = await dispatch(PendingOrdersDC({ CompId, AppId, BranchId })).unwrap();
      if (resOrders?.data?.statusCode === 1) {
        setOrdersCustomer(resOrders?.data?.data?.PurchaseOrder);
      } else {
        setOrdersCustomer([]);
        setMessageType("error");
        setMessageData(resOrders?.data?.response);
      }

    } catch (err) {
      // setAllCustomer([]);
      setOrdersCustomer([]);
      setMessageType("error");
      setMessageData("Something went wrong");
    }
  };

  const handleOrderChange = (params) => {
    const [suppId, purOrderId] = params.split("||");
    formRef?.current?.setFieldsValue({ Order: suppId })
    setSelectedOrder(suppId)
    const { OrderDetails } = ordersCustomer?.find(find => find.SuppId === suppId && find.PurOrderId === purOrderId);
    setOrderTableData(OrderDetails?.map(item => {
      const { InwardDtlId, OnePcsAvailable, SellPrice, TaxId, TaxName } = ProductData?.find((e) => e.ProdId === item.ProdId);
      return {
        ...item,
        InwardDtlId,
        TaxId,
        TaxName,
        SinglePc: OnePcsAvailable,
        ProductRate: SellPrice,
        TotalAmount: item.OrderQty * SellPrice,
        TaxAmount: 0,
        GrossTotal: item.OrderQty * SellPrice
      }
    }))

    setSelectedProductName(null)
    setVariants([])
    setTableData([])

    formRef?.current?.setFieldsValue({
      ProdId: undefined,
    })
  }

  const handleAdminUserDropDownChange = (UserId) => {
    setSelecAdminUser(UserId);
    formRef.current?.setFieldsValue({ CustId: UserId });
    setIsSubmitted(false);
  };
  const handleScanSearch = () => {
    if (scanner === false) {
      setMessageType("success");
      setMessageData("Search by QrCode/BarCode Enabled")
    } else {
      setMessageType("success");
      setMessageData("Search by QrCode/BarCode Disabled")
    }
    setScanner(prev => !prev)
    setSelectedProductName(null);
    setVariants(null)
    formRef?.current?.setFieldsValue({
      ProdId: null,
      VarProdId: null
    });
  }
  const handleProductSearch = (value) => {
    if (scanner) {
      debouncedScannerSearch(value);
    }
    setSelectedProductName(value);
    setProductSearchText(value)
    setVariants([])
  };
  const ProductDropDownChange = async (ProdId, option) => {
    formRef?.current?.resetFields(['VarProdId']);

    setProductSearchText("")
    setSelectedProductName(option?.label ? option?.label : '')
    setSelProduct(ProdId);
    formRef.current?.setFieldsValue({ ProdId: ProdId });

    let x = ProductData?.find((e) => e.ProdId === ProdId)?.ProdName;

    let variantValues1 = await dispatch(
      getProdQuoaVariantdata({
        CompId: CompId,
        AppId: AppId,
        BranchId: BranchId,
        prodName: x,
      })
    ).unwrap();

    let variants1 = variantValues1?.data?.data;

    // let cc = variants1?.[0]?.ProductDetail;
    let cc = variants1?.filter((item) => item?.ProdName == x)?.[0]?.ProductDetail;

    setVariants(
      cc?.[0]?.ProdVariantDetails?.map((detail) => ({
        ...detail,
        ProdIdProdName: `${detail.ProdVariantName} ${detail.ProdId}`,
      }))
    );


    if (segmentValue === "O") {
      if (cc?.[0]?.ProdVariantDetails?.length < 2) {
        if (orderTableData?.some((e) => e.ProdId === ProdId)) {
          setMessageType('error');
          setMessageData('Already Product Exists');
        } else {
          const { ProdName, UomName, OnePcsAvailable, SellPrice, InwardDtlId, TaxId, TaxName } = ProductData?.find(item => item.ProdId === ProdId);
          setOrderTableData(prev => [...prev, {
            OrderQty: 1,
            ProdId,
            ProdName: ProdName,
            ProdVariantName: "Variant 1",
            PurOrderId: "",
            UOM: UomName,
            InwardDtlId,
            TaxId,
            TaxName,
            SinglePc: OnePcsAvailable,
            ProductRate: SellPrice,
            TotalAmount: 1 * SellPrice,
            TaxAmount: 0,
            GrossTotal: 1 * SellPrice
          }])
        }
      }
    } else {
      if (cc?.[0]?.ProdVariantDetails?.length < 2) {
        if (TableData?.some((e) => e.ProdId === ProdId)) {
          setMessageType('error');
          setMessageData('Already Product Exists');
        } else {
          let ProductData1 = ProductData?.find((e) => e.ProdId === ProdId);
          let ProduData2 = {
            ProdId: ProductData1?.ProdId,
            ProdName: ProductData1?.ProdName,
            UomName: ProductData1?.UomName,
            Price: ProductData1?.SellPrice,
            TaxName: ProductData1?.TaxName,
            HSNCode: ProductData1?.HSNCode,
            Size: ProductData1?.Size,
            InwardDtlId: ProductData1?.InwardDtlId,
            TaxId: ProductData1?.TaxId,
            TaxPercentage: ProductData1?.TaxPercentage,
            SinglePc: ProductData1?.OnePcsAvailable,
          };

          let tempPurData = {
            ...ProduData2,
            Qty: 0,
            ProdVariantName: 'Variant 1',
          };
          setTableData([...TableData, tempPurData]);
        }
      }
    }
  };


  const ProductVariantDropDownChange = (value) => {
    if (segmentValue === "O") {
      const selectedVarientName = Variants?.filter(({ ProdIdProdName }) => ProdIdProdName === value)?.[0]?.ProdVariantName;
      const isVarientDublicate = orderTableData?.some(({ ProdId, ProdVariantName }) =>
        ProdId === SelProduct && ProdVariantName === selectedVarientName);
      if (isVarientDublicate) {
        setMessageType('error');
        setMessageData('Already variant Exists');
      } else {
        formRef?.current?.setFieldsValue({ VarProdId: value });
        setOrderTableData(prev => prev.map(item => {
          if (item.ProdId === SelProduct) {
            return { ...item, ProdVariantName: selectedVarientName }
          }
          return item
        }))
        const { ProdName, UomName, OnePcsAvailable, SellPrice, InwardDtlId, TaxId, TaxName } = ProductData?.find(item => item.ProdId === SelProduct);
        setOrderTableData(prev => [...prev, {
          OrderQty: 1,
          ProdId: SelProduct,
          ProdName: ProdName,
          ProdVariantName: "Variant 1",
          PurOrderId: "",
          UOM: UomName,
          InwardDtlId,
          TaxId,
          TaxName,
          SinglePc: OnePcsAvailable,
          ProductRate: SellPrice,
          TotalAmount: 1 * SellPrice,
          TaxAmount: 0,
          GrossTotal: 1 * SellPrice
        }])
      }
    } else {
      const ProdName2 = Variants?.filter(
        (item) => item.ProdIdProdName === value
      )?.[0]?.ProdVariantName;

      const ProdName1 = TableData?.some(
        (e) =>
          e.ProdId === SelProduct &&
          e.ProdVariantName === ProdName2
      );
      if (ProdName1) {
        setMessageType('error');
        setMessageData('Already variant Exists');
      } else {
        const ProdName = Variants?.filter(
          (item) => item.ProdIdProdName === value
        )?.[0]?.ProdVariantName;
        formRef?.current?.setFieldsValue({ VarProdId: value });
        let ProductData1 = ProductData?.find((e) => e.ProdId === SelProduct);

        let mrp;
        let sellprice;
        let InwardDtlId;
        if (ProdName == 'Variant 1') {
          mrp = ProductData1?.MRP;
          sellprice = ProductData1?.SellPrice;
          InwardDtlId = ProductData1?.ProdVariantPriceDetails?.find(
            (item) => item.ProdVariantName == ProdName
          )?.InwardDtlId;
        } else {
          mrp = ProductData1?.ProdVariantPriceDetails?.find(
            (item) => item.ProdVariantName == ProdName
          )?.MRP;
          sellprice = ProductData1?.ProdVariantPriceDetails?.find(
            (item) => item.ProdVariantName == ProdName
          )?.SellPrice;
          InwardDtlId = ProductData1?.ProdVariantPriceDetails?.find(
            (item) => item.ProdVariantName == ProdName
          )?.InwardDtlId;
        }

        let ProduData2 = {
          ProdId: ProductData1?.ProdId,
          ProdName: ProductData1?.ProdName,
          UomName: ProductData1?.UomName,
          Price: sellprice,
          TaxName: ProductData1?.TaxName,
          HSNCode: ProductData1?.HSNCode,
          InwardDtlId: InwardDtlId,
          Size: ProductData1?.Size,
          TaxId: ProductData1?.TaxId,
          TaxPercentage: ProductData1?.TaxPercentage,
        };

        let tempPurData = {
          ...ProduData2,
          Qty: 0,
          ProdVariantName: ProdName,
        };

        setTableData([...TableData, tempPurData]);
      }
    }
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);
  const save = async (index) => {
    try {
      const row = await form?.validateFields();

      const modifiedObject = {};
      for (const key in row) {
        const newKey = key.slice(0, -1); // Remove the last character ("0") from the key
        modifiedObject[newKey] = row[key];
      }

      const newData = [...TableData];
      // const index = newData.findIndex((item) => recordKey === item.InwardDtlId);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...modifiedObject });
        setTableData(newData);
        setEditingKey('');
      }
    } catch (err) {
      console.error('Save failed:', err);
    }
  };
  const handleKeyPress = async (e, record, index) => {
    if (e.key === 'Enter') {
      try {
        await form.validateFields();
        save(index);
      } catch (error) {
        console.error('Save failed:', error);
      }
    }
  };

  const statusFormatter = (record) => {
    let filterData = TableData?.filter((e) => e?.InwardDtlId != record.InwardDtlId);
    setTableData(filterData)

  }
  const getColumns = (data, seltax) => {
    const hasDiscount = data?.some((record) => record.PurcDisc > 0);

    const baseColumns = [
      {
        title: 'Sl.No',
        align: 'center',
        key: 'sno',
        width: '50px',
        render: (text, object, index) => (
          <a style={{ color: 'black' }}>{index + 1}</a>
        ),
      },
      {
        title: 'Product Name',
        dataIndex: 'ProdName',
        key: 'ProdName',
        align: 'right',
        width: '300px',
        render: (text, record, index) => (
          <a style={{ color: 'black' }}>
            {
              record?.ProdName +
              '(' +
              record?.Size +
              '-' +
              record?.UomName +
              ')'
              //  +
              // '(' +
              // record?.ProdVariantName +
              // ')'
            }
          </a>
        ),
      },
      {
        title: 'Variant Name',
        dataIndex: 'ProdVariantName',
        key: 'ProdVariantName',
      },
      {
        title: 'Qty',
        dataIndex: 'Qty',
        key: 'Qty',
        editable: true,
        with: '100px',
        render: (text, record, index) => {
          return isEditing(record, index) ? (
            <Form.Item
              name={'Qty' + index}
              rules={[
                {
                  required: true,
                  pattern: /^[1-9]\d*(\.\d+)?$/,
                  message: 'Quantity must be at least 1.',
                },
              ]}
            >
              <Input
                onPressEnter={(e) => handleKeyPress(e, record, index)}
                onBlur={(e) => handleQtyChange(e, record)}
                onChange={(e) => handleQtyChange(e, record, index)}
                autoComplete="off"
                inputMode="decimal"
                onInput={(e) => {
                  let cleanedValue = e.target.value.replace(/[^0-9.]/g, ''); // Remove invalid characters
                  const parts = cleanedValue.split('.');

                  if (cleanedValue.startsWith('.')) {
                    cleanedValue = '0' + cleanedValue;
                  }

                  e.target.value =
                    parts.length > 2
                      ? `${parts[0]}.${parts.slice(1).join('')}`
                      : cleanedValue;
                }}
              />
            </Form.Item>
          ) : (
            text
          );
        },
      },
      {
        title: 'Action',
        key: 'Action',
        dataIndex: 'Action',
        render: (_, record, index) =>
          TableData.length >= 1 ? (
            <Space size="middle">

              <a>
                {(
                  <DeleteFilled
                    style={{
                      color: '#FF4D4F',
                    }}
                    onClick={() =>

                      statusFormatter(record)

                    }
                  />
                )

                }
              </a>
            </Space>
          ) : null,
      },
    ];
    return baseColumns;
  };

  const columns = getColumns(TableData, SelTaxType);

  const ordersColumns = [
    {
      title: "SL.NO",
      key: "ProdId",
      dataIndex: 'ProdId',
      align: "center",
      render: (text, object, index) => (
        <a style={{ color: "black" }}>{index + 1}</a>
      ),
    },
    {
      title: "Product Name",
      key: "ProdName",
      dataIndex: 'ProdName',
      align: "center",

      render: (text, record, index) => (
        <a style={{ color: "black" }}>{text + " " + record?.UOM}</a>
      ),
    },
    {
      title: "Product Variant Name",
      key: "ProdVariantName",
      dataIndex: 'ProdVariantName',
      align: "center",
    },
    {
      title: "Product Rate",
      key: "ProductRate",
      dataIndex: 'ProductRate',
      align: "center",
      render: (value) => (
        <span>{Number(value).toFixed(2)}</span>
      ),
    },
    {
      title: "Order Qty",
      key: "OrderQty",
      dataIndex: 'OrderQty',
      align: "center",
      render: (text, object, index) => (
        <Form.Item
          name={['OrderQty', index]}
          initialValue={text}
          rules={[
            {
              required: true,
              message: 'Order Qty is required',
            },
            {
              validator: (_, value) =>
                value && Number(value) >= 1
                  ? Promise.resolve()
                  : Promise.reject('Order Qty must be at least 1'),
            },
          ]}
        >
          <Input
            type="number"
            min={1}
            defaultValue={text}
            onChange={e => {
              const value = e.target.value;
              if (Number(value) < 1) {
                setMessageType('error');
                setMessageData('Order Qty must be at least 1');
                return;
              }
              handlePendingOrdersQtyOnChange(value, object, index);
            }}
          />
        </Form.Item>
      ),
    },
    {
      title: "Total Amount",
      key: "TotalAmount",
      dataIndex: 'TotalAmount',
      align: "center",
      render: (value) => (
        <span>{Number(value).toFixed(2)}</span>
      ),
    },

    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      render: (_, record, index) =>
        <Space size="middle">
          <a>
            <DeleteFilled style={{ color: '#FF4D4F' }} onClick={() => handlePendingOrderDelete(record)} />
          </a>
        </Space>
    },
  ]

  const handlePendingOrdersQtyOnChange = (value, object, index) => {
    const { ProdId } = object;
    setOrderTableData(prev => prev.map(item => {
      if (item.ProdId === ProdId) {
        return {
          ...item, OrderQty: value, TotalAmount: value * item.ProductRate,
          GrossTotal: value * item.ProductRate
        }
      }
      return item
    }))
  }
  const handlePendingOrderDelete = (object) => {
    const { ProdId } = object;
    setOrderTableData(prev => prev.filter(item => item.ProdId !== ProdId))
  }

  const edit = (record, index) => {
    form.setFieldsValue({ ...record });
    setEditingKey(index);
    form.setFieldsValue({ [`Qty${index}`]: record?.Qty });
  };

  const handleQtyChange = (e, record, index) => {
    const qty = e.target.value;
    if (!/^\d*\.?\d*$/.test(qty)) {
      setMessageType('error');
      setMessageData('Only numeric values are allowed');
      return;
    }
    const sellprice = parseInt(record.Price);
    const Amount = !isNaN(sellprice * parseInt(qty))
      ? sellprice * parseInt(qty)
      : 0;
    const taxamt =
      SelTaxTypeName?.toLowerCase() === 'withtax'
        ? (Amount * parseInt(record?.TaxPercentage)) /
        (100 + parseInt(record?.TaxPercentage))
        : 0;
    const newData = TableData.map((item, index1) => {
      if (index1 === index) {
        return {
          ...item,
          Qty: qty,
          NetAmt: Amount,
          TaxAmt: taxamt,
          // BillAmount: Amount - taxamt,
          TotalAmount: Amount,
          GrossTotal: Amount + taxamt,
          ProductRate: item.Price,
        };
      }
      return item;
    });

    setTableData(newData);
    form.setFieldsValue({
      ...form.getFieldsValue(),
      [`Qty${index}`]: qty
    });
  };

  const PrintQuotation = async () => {
    if (segmentValue === "N") {
      if (TableData.some((item) => !item.Qty || parseFloat(item.Qty) < 1)) {
        setMessageType('error');
        setMessageData('Every product must have a quantity of at least 1.');
        return;
      }
    } else {
      if (orderTableData.some((item) => !item.OrderQty || parseFloat(item.OrderQty) < 1)) {
        setMessageType('error');
        setMessageData('Every product must have a quantity of at least 1.');
        return;
      }
    }

    setIsSubmitted(true);

    const total = orderTableData?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.TotalAmount;
    }, 0);
    const totalgst = (orderTableData?.filter(
      (item) => item.TaxName?.toLowerCase() === 'cgst,sgst'
    )?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.TaxAmt;
    }, 0) || 0) / 2;
    const totaligst = orderTableData?.filter(
      (item) => item.TaxName?.toLowerCase() === 'igst'
    )?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.TaxAmt;
    }, 0);

    const totalAmount = orderTableData?.reduce((accumulator, currentValue) => {
      return accumulator + currentValue.TotalAmount;
    }, 0);

    const Type = segmentValue === "N" ?
      AllCustomer?.find(item => item.CustId === SelecAdminUser)?.Type :
      ordersCustomer?.find(item => item.SuppId === selectedOrder)?.LocationType;

    let data1 = transportFormRef.current?.getFieldsValue();
    let data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      CustId: segmentValue === "N" ? SelecAdminUser : selectedOrder,
      TotalAmount: segmentValue === "N" ? TotalBillAmount : totalAmount,
      TaxAmount: segmentValue === "N" ? (TotalCgst + TotalSgst + TotalIgst || 0) : (totalgst + totalgst + totaligst || 0),
      GrandTotal: segmentValue === "N" ? TotalAmount : total,
      VehicleNo: data1?.vehicleNo ? data1?.vehicleNo : null,
      Remarks: '',
      Type,
      ModeOfTransport: selectedMode,
      TransporterId: data1?.transporter ? data1?.transporter : null,
      TransporterName: data1?.transporterName ? data1?.transporterName : null,
      ProductDetails: (segmentValue === "N" ? TableData : orderTableData)?.map((item) => {
        return {
          ProdId: item?.ProdId,
          InwardDtlId: item?.InwardDtlId,
          SinglePc: item?.SinglePc,
          Qty: segmentValue === "N" ? item?.Qty : item?.OrderQty,
          ProductRate: item?.ProductRate,
          TotalAmount: item?.TotalAmount,
          TaxAmount: item?.TaxAmt,
          TaxId: item?.TaxId,
          GrossTotal: item?.TotalAmount,
        };
      }),
      CreatedBy: UserId,
    };

    let response = await dispatch(PostChallan(data)).unwrap();

    if (response?.data?.statusCode == 1) {
      setMessageType('success');
      setMessageData(response?.data?.response);
      transportFormRef?.current?.resetFields();
      formRef?.current?.resetFields();
      setSelecAdminUser();
      setSelTaxType();
      setSelProduct();
      setSelTaxTypeName();
      setTotalBillAmount();
      setTableData([]);
      setTotalCgst();
      setTotalSgst();
      setTotalIgst();
      fetchdata()
      const challanDetail = response?.data?.DeliveryChallanDetails?.[0];
      const orderData = {
        Remarks: challanDetail?.Remarks,
        DCNo: challanDetail?.DCNo,
        DCDate: challanDetail?.DCDate,
        CustMobile: challanDetail?.CustMobile,
        CustName: challanDetail?.CustName,
        TransporterName: challanDetail?.TransporterName,
        ModeOfTransport: challanDetail?.ModeOfTransport,
        TransporterId: challanDetail?.TransporterId,
        ProductDetails: challanDetail?.ProductDetails,
        TotalAmount: challanDetail?.TotalAmount,
        VehicleNo: challanDetail?.VehicleNo,

      };

      setPrintingData([orderData]);
      setSelectedProductName(null)
      setVariants([])
      setOrderTableData([])
      formRef?.current?.setFieldsValue({
        Order: undefined,
        CustId: undefined,
        ProdId: undefined,
      })
    }

    // if (response?.data?.statusCode == 1) {
    //   navigate(`${subDirectory}setting/customer-master/`, {
    //     state: {
    //       Notiffy: {
    //         messageType: 'success',
    //         messageData: response?.data?.response,
    //       },
    //     },
    //   });
    // }
    else {
      setMessageType('error');
      setMessageData(response?.data?.response);
    }
  };

  const PurchaseOrderStyle = `<style>
    @media print {
      @page {
        size: A4;
        margin: 0;
      }
      
      .Quo-Print-Body {
        width: 195mm;
        margin: 0 auto;
        // padding: 10mm;
      }
    }
    
    .Quo-Print-Body {
      margin: 0;
      padding: 10px;
      background: white;
    }
  
    .Quo-Print-Content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height:100%
      max-width: 200mm;
      margin: 0 auto;
      border: 1px solid rgb(170, 164, 164);
      padding: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
      gap:0.5rem;
    
    }
    .Quo-print-Logo{
      width: 50px ;
      height: 50px;
      margin:5px 0 0 5;
     }
    .Quo-Print-ComCus{
    display:flex;
    flex-direction:column;
      justify-content:space-between;
    }
    .Quo-Print-Tabsum{
      display:flex;
      flex-direction:column;
      justify-content:space-between; 
      gap:1rem;
      height:60vh;
    }
    .Quo-Print-Header{
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    
    }

    .Quo-Print-Company{
      display:flex;
      flex-direction:column;
      padding:10px;
      gap:0.1rem;
    }
    .Quo-Print-Cname{
        font-size:25px;
    }
    .Quo-Print-address{
      font-size:22px;
      display:flex;
      flex-wrap:wrap;
      height: max-content !important;
    }
    .Quo-Print-Qno{
      display:flex;
      flex-direction:column;
      padding:10px;
      gap:0.1rem;
    }
    .Quo-Print-Customer{
      display:flex;
      flex-direction:column;
      padding-left:10px;
      gap:0.1rem;
          width: 100%;
            height: max-content !important;
    }
    .Horizondal-line{
      border-bottom: 0.5px solid rgb(170, 164, 164);
    }
    .Quo-Print-Table{
      display:flex;
    }    .Quo-Print-ProTable {
      width: 100%;
      border-collapse: collapse;
      margin-top: 15px;
    }
    
    .Quo-Print-DataRow {
    //   line-height: 2.5rem;
      border-bottom: 1px solid #eee;
    }
    
    .Quo-Print-tableheader {
      background-color: #f8f9fa;
      border-top: 1px solid rgb(170, 164, 164);
      border-bottom: 1px solid rgb(170, 164, 164);
      line-height: 3rem;
    }
    
    .Quo-Print-TableData {
      text-align: right;
      padding: 8px;
      font-size: 20px;
    }
    
    .Quo-Print-TableDataSno {
      text-align: center;
      padding: 8px;
      font-size: 20px;
      width: 60px;
    }

    .Quo-Print-TableDataName {
      text-align: left;
      padding: 8px;
      font-size: 20px;
    }
    
    .Quo-Print-headingData {
      text-align: center;
      padding: 8px;
      font-size: 22px;
      font-weight: bold;
    }
    .Quo-Print-TableDataAmt{
      text-align:right;
      padding-right:5px;
      font-size:20px;
    }
    .Quo-Print-Summary{
      display:flex;
      flex-direction:row;
      justify-content: flex-end;
      
    }
    .Quo-Print-SummTableData{
      text-align:right;
      padding:1px;
      font-size:20px;
      
    }
    .Quo-Print-Total{
      display:flex;
      justify-content:flex-end;
      border:0.5px solid black;
      width:300px;
      margin-right: 10px;
      font-size:20px;
    }
   
 
    }

</style>`;
  const handleSendEmailWithEnteredEmail = async (values) => {
    const record = { ...pendingRecord, CustEmail: values.email };
    await handleEmailClick(pendingOrderDetails, record);
    setiSEmail(false);
    setPendingOrderDetails(null);
    setPendingRecord(null);
    form.resetFields();

  };
  const handlePrint = async () => {
          setIsSubmitted(false);
    const DCstyle = await DCPrintStyleFunction(
      DCPrintTemplateStyle == undefined ? 'Style 13' : DCPrintTemplateStyle);
    const stylesMap = {
      'Style 1': 'DCPrintStyle1',
      'Style 2': 'DCPrintStyle2',
      'Style 3': 'DCPrintStyle3',
      'Style 4': 'DCPrintStyle4',
      'Style 5': 'DCPrintStyle5',
      'Style 6': 'DCPrintStyle6',
      'Style 7': 'DCPrintStyle7',
      'Style 8': 'DCPrintStyle8',
      'Style 9': 'DCPrintStyle9',
      'Style 10': 'DCPrintStyle10',
      'Style 11': 'DCPrintStyle11',
      'Style 12': 'DCPrintStyle12',
      'Style 13': 'DC-Default-Print',
      A4: 'DCPrintStyleA4',
      A5: 'DCPrintStyleA5',
      A4Standard: 'DCPrintStyleA4Standard',
    };

    const selectedStyle =
      stylesMap[
      DCPrintTemplateStyle == undefined ? 'Style 13' : DCPrintTemplateStyle
      ];
    console.log(selectedStyle, DCstyle, 'selectedStyle');
    setTimeout(() => {
      if (isMobile) {
        DCPDFMobilePrint({
          PrintTempData: DCPrintTemplateDtl,
             UserId: UserId,
                     dispatch 
        })
      }
      else {
        printDiv(`${selectedStyle}`, DCstyle);
      }

    }, 100);
  };

  const transporterFn = () => {
    setModal(true);
  };

  const handleEmailClick = async (ProductDetails, record) => {
    // alert("This feature is not available yet. Please contact support for assistance.");
    const orderData = {
      0: { ...record },
      customerName: record?.CustName || '',
      CustName: record?.CustName || '',
      customerAddress: record?.AddressDetails || '',
      Address1: record?.AddressDetails || '',
      customerMobile: record?.CustMobile || '',
      MobileNo: record?.CustMobile || '',
      CustMail: record?.CustEmail,
    };

    // setPrintData(record);

    if (orderData?.CustMail) {
      setTimeout(async () => {
        try {
          const blob = await pdfDiv('DC-Default-Print', PurchaseOrderStyle);

          const payload = {
            fileBlob: blob,
            toEmail: orderData?.CustMail,
            type: 'DeliveryChallan',
            messageTemplatesList: [],
          };

          const res = await dispatch(Emailsend(payload))?.unwrap();

          console.log('✅ API Response:', res?.data || res);

          setMessageData('Email sent successfully');
          setMessageType('success');
        } catch (error) {
          console.error('❌ Email send failed:', error);
          setMessageData('Email failed to send');
          setMessageType('error');
        }
      }, 300);
    } else {
      setPendingOrderDetails(ProductDetails);
      setPendingRecord(record);
      setiSEmail(true);
       setIsSubmitted(false);
    }
  };

  const handleTransportModeChange = (e) => {
    setSelectedMode(e.target.value);
    // Set the value in the transport form using ref
    transportFormRef.current?.setFieldsValue({
      transportationMode: e.target.value,
    });
  };

  const closeDeliveryChallanModel = (e) => {
    let data = transportFormRef.current?.getFieldsValue();

    if (data.lrDate && data.lrDate.format) {
      data.lrDate = data.lrDate.format('YYYY-MM-DD');
    }
    if (data.dateOfSupply && data.dateOfSupply.format) {
      data.dateOfSupply = data.dateOfSupply.format('YYYY-MM-DD');
    }

    console.log(data, 'datadata');
    e.stopPropagation();
    setModal(false);
  };

  const handleOnChangeSegment = (params) => {
    setSegmentValue(params)
    setSelectedProductName(null)
    setVariants([])
    setTableData([])
    setOrderTableData([])
    formRef?.current?.setFieldsValue({
      Order: undefined,
      CustId: undefined,
      ProdId: undefined,
    })
  }

  return (
    <div className="pageOverAll">
      <div className="userPage">
        <div className="userPageContent">
          <Messages
            messageType={messageType}
            messageData={messageData}
            onComplete={onComplete}
          />
          <div className="formName"
            style={{
              display: 'flex',
              justifyContent: 'space-between',
             }}>
            <FormHeader title={'Delivery Challan'} />
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '7px',
                padding: '6px 12px',
                backgroundColor: '#059645',
                borderRadius: '8px',
                color: 'white',
                cursor: 'pointer',
                fontFamily: 'Poppins',
                fontWeight: '400',
                whiteSpace: "nowrap",
                fontSize: "15px"
              }}
              onClick={() => navigate(`${subDirectory}setting/delivery-challan/list`)}
            >
              <FaEye /> <span>View Challans</span>
            </div>
          </div>
          <div className="Quo-formDiv">
            <Form
              ref={formRef}
              className="formDivAnt"
              onFinish={PrintQuotation}
            >
              <div className="formDivS">
                <div className="DeliveryChallan-inputForm">
                  <div style={{ width: "10rem", marginBottom: "1rem" }}>
                    <Segmented
                      options={[{ label: "New", value: "N" }, { label: "Orders", value: "O" }]}
                      value={segmentValue}
                      onChange={handleOnChangeSegment}
                      block
                      size="large"
                      className='segmentData-style'
                    />
                  </div>
                  <div className="DeliveryChellanDetails">

                    {segmentValue === "N" ? <div>
                      <Form.Item
                        name="CustId"
                        rules={[
                          {
                            required: true,
                            message: 'Please Select Customer',
                          },
                        ]}
                      >
                        <DropDowns
                          options={AllCustomer?.map((option) => ({
                            value: option.CustId,
                            label:
                              (option.CustShortName ||
                                option.CustName ||
                                option.CustMobile) + `(${option.Type})`,
                          }))}
                          label={<label class="required">Customer</label>}
                          className="field-DropDown"
                          onChangeFunction={handleAdminUserDropDownChange}
                        />
                      </Form.Item>
                    </div> : <div>
                      <Form.Item
                        name="Order"
                        rules={[
                          {
                            required: true,
                            message: 'Please Select Order',
                          },
                        ]}
                      >
                        <DropDowns
                          options={ordersCustomer?.map((option) => ({
                            label: option.SuppName + (option.SuppMobile === null ? "" : ` - ${option.SuppMobile}`) + (option.LocationType === null ? "" : ` (${option.LocationType})`) + " " + option.PurOrderId.split("-").slice(4).join("-"),
                            value: option.SuppId + "||" + option.PurOrderId
                          }))}
                          label={<label class="required">Orders</label>}
                          className="field-DropDown"
                          onChangeFunction={handleOrderChange}
                        />
                      </Form.Item>
                    </div>}


                    <div className="DeliveryChallanDropDown">
                      <Form.Item
                        name="ProdId"
                        rules={[
                          {
                            message: 'Please Select Product',
                          },
                        ]}
                      >
                        <div className="product-scan sales-quotation">
                          <FloatLabel label={"Product Name"} value={selectedProductName}>
                            <AutoComplete
                              className="field-DropDown"
                              value={selectedProductName}
                              filterOption={(input, option) => {
                                const product = ProductData.find(p => p.ProdId === option.value);
                                const nameMatch = option.label?.toLowerCase().includes(productSearchText?.toLowerCase());
                                const qrMatch = product?.QRCode?.toLowerCase() == productSearchText?.toLowerCase();
                                return nameMatch || qrMatch;
                              }}
                              options={!scanner ? ProductData?.map
                                ((option) => ({
                                  value: option.ProdId,
                                  label: `${option.ProdName} (${option.Size} ${option.UomName})${option?.BrandName ? ` - ${option?.BrandName}` : ''}`
                                })) : []}
                              onSelect={ProductDropDownChange}
                              onChange={handleProductSearch}
                              onKeyDown={(e) => {
                                if (scanner && e.key === "Enter") {
                                  e.preventDefault();
                                }
                              }}
                            >
                            </AutoComplete>
                          </FloatLabel>
                          <Tooltip title={"BarCode/QrCode"} placement={"top"}>
                            <BsUpcScan strokeWidth={0.5} color="#000" style={{ fontSize: "16px", color: scanner ? "#52c41a" : "#888", fontWeight: "600" }} className="product-scan-Icon" onClick={handleScanSearch} />
                          </Tooltip>
                        </div>
                      </Form.Item>

                      {Variants?.length > 1 && (
                        <Form.Item name="VarProdId">
                          <DropDowns
                            options={Variants?.map((option) => ({
                              value: option.ProdIdProdName,
                              label: option.ProdVariantName,
                            }))}
                            label={'Variant Name'}
                            className="field-DropDown"
                            onChangeFunction={(e) =>
                              ProductVariantDropDownChange(e)
                            }
                          />
                        </Form.Item>
                      )}

                      <div
                        className="Transport-Details"
                        style={{ textAlign: 'center' }}
                        onClick={transporterFn}
                      >
                        <div>
                          <IoMdAddCircleOutline size={20} /> Add Transport Details{' '}
                          <FaTruck scale={20} />
                        </div>
                        <DefaultModal
                          title={
                            <div style={{ textAlign: 'center' }}>
                              <FormHeader title={'Transport Details'} />
                            </div>
                          }
                          handleCancel={(e) => {
                            closeDeliveryChallanModel(e);
                          }}
                          open={Modal}
                          width={700}
                          footer={null}
                          children={
                            <div className="transport-details-form">
                              <Form layout="vertical" ref={transportFormRef}>
                                <div style={{ marginBottom: '20px' }}>
                                  <label
                                    style={{
                                      fontSize: '16px',
                                      fontWeight: '500',
                                    }}
                                  >
                                    Transportation Mode
                                  </label>
                                  <div style={{ marginTop: '10px' }}>
                                    <Radio.Group
                                      onChange={handleTransportModeChange}
                                      value={selectedMode}
                                    >
                                      <Radio value="road">Road</Radio>
                                      <Radio value="rail">Rail</Radio>
                                      <Radio value="air">Air</Radio>
                                      <Radio value="notApplicable">
                                        Not Applicable
                                      </Radio>
                                    </Radio.Group>
                                  </div>
                                </div>

                                <div
                                  style={{
                                    display: 'grid',
                                    gridTemplateColumns: '1fr 1fr',
                                    gap: '20px',
                                  }}
                                >
                                  {/* <Form.Item name="lrNumber">
                                    <InputField
                                      label="LR Number"
                                      onChange={(e) =>
                                        transportFormRef.current?.setFieldsValue(
                                          { lrNumber: e.target.value }
                                        )
                                      }
                                    />
                                  </Form.Item>

                                  <Form.Item name="lrDate" label="LR Date">
                                    <DatePicker
                                      style={{ width: '50%' }}
                                      format="DD-MM-YYYY"
                                      onChange={(date) =>
                                        transportFormRef.current?.setFieldsValue(
                                          { lrDate: date }
                                        )
                                      }
                                    />
                                  </Form.Item> */}

                                  <Form.Item name="vehicleNo"
                                    rules={[
                                      {
                                        pattern: /^[A-Z]{2}\d{1,2}[A-Z]{1,2}\d{4}$/,
                                        message: "Please enter a valid vehicle number (e.g., TN10AB1234)",
                                      },
                                    ]}
                                  >
                                    <InputField
                                      label="Vehicle No."
                                      onChange={(e) =>
                                        transportFormRef.current?.setFieldsValue(
                                          { vehicleNo: e.target.value }
                                        )
                                      }
                                      maxLength={10}
                                    />
                                  </Form.Item>

                                  {/* <Form.Item
                                    name="dateOfSupply"
                                    label="Date of Supply"
                                  >
                                    <DatePicker
                                      style={{ width: '50%' }}
                                      format="DD-MM-YYYY"
                                      onChange={(date) =>
                                        transportFormRef.current?.setFieldsValue(
                                          { dateOfSupply: date }
                                        )
                                      }
                                    />
                                  </Form.Item> */}

                                  {/* <Form.Item name="placeOfSupply">
                                    <InputField
                                      label="Place of Supply"
                                      onChange={(e) =>
                                        transportFormRef.current?.setFieldsValue(
                                          { placeOfSupply: e.target.value }
                                        )
                                      }
                                    />
                                  </Form.Item> */}
                                  <Form.Item name="transporterName">
                                    <InputField
                                      label="Transporter Name"
                                      onChange={(e) =>
                                        transportFormRef.current?.setFieldsValue(
                                          { transporterName: e.target.value }
                                        )
                                      }
                                    />
                                  </Form.Item>

                                  <Form.Item name="transporter">
                                    {/* <DropDowns
                                      options={[
                                        { value: 'transporter1', label: 'Transporter 1' },
                                        { value: 'transporter2', label: 'Transporter 2' },
                                      ]}
                                      label="Transporter"
                                      className="field-DropDown"
                                      onChangeFunction={value => transportFormRef.current?.setFieldsValue({ transporter: value })}
                                    /> */}
                                    <InputField
                                      label="Transporter Id"
                                      onChange={(e) =>
                                        transportFormRef.current?.setFieldsValue(
                                          { transporter: e.target.value }
                                        )
                                      }
                                    />
                                  </Form.Item>
                                </div>

                                <div
                                  style={{
                                    marginTop: '20px',
                                    display: 'flex',
                                    flexDirection: 'row-reverse',
                                  }}
                                >
                                  <Buttons
                                    buttonText="SAVE"
                                    color="901D77"
                                    icon={<ArrowRightOutlined />}
                                    handleSubmit={(e) => {
                                      closeDeliveryChallanModel(e);
                                    }}
                                  />
                                </div>
                              </Form>
                            </div>
                          }
                        />
                      </div>
                    </div>
                  </div>

                  <div
                    className="Deliverychallan-table"
                  // style={{
                  //   width: '10px',
                  // }}
                  >
                    {segmentValue === "N" ? <Form form={form} component={false}>
                      <Table
                        bordered
                        dataSource={TableData}
                        columns={columns}
                        rowClassName="editable-row"
                        onRow={(record, index) => ({
                          onClick: () => {
                            edit(record, index);
                          },
                        })}
                        pagination={false}
                      />
                    </Form> :
                      <Table
                        bordered
                        dataSource={orderTableData}
                        columns={ordersColumns}
                      />}

                  </div>
                </div>
              </div>
              <div className="QuosubmitButton"
                style={{ display: 'flex', gap: '2rem', alignItems: 'center' }}>
                <Buttons
                  buttonText="SUBMIT"
                  color="901D77"
                  disabled={addnewAccess}
                  icon={<ArrowRightOutlined />}
                  htmlType={true}
                />
                {isSubmitted && (
                  <>
                    <div>
                      <MdOutlineMail
                        size={39}
                        color="#25D366"
                        style={{ cursor: 'pointer' }}
                        onClick={handleEmailClick}
                        title="Share by Email"
                      />
                    </div>
                    <div>
                      <FaPrint
                        size={32}
                        color="#1292EE"
                        style={{ cursor: 'pointer' }}
                        onClick={handlePrint}
                        title="Print"
                      />
                    </div>
                  </>
                )}
              </div>
            </Form>
          </div>
          <DefaultModal
            width={400}
            open={iSEmail}
            title="User Mail"
            handleCancel={() => setiSEmail(false)}
            footer={false}
            children={
              <div>
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleSendEmailWithEnteredEmail}
                >
                  <Form.Item
                    label="Mail ID"
                    name="email"
                    rules={[
                      { required: true, message: 'Email is required' },
                      { type: 'email', message: 'Enter a valid email address' },
                    ]}
                  >
                    <Input
                      autoComplete="off"
                      placeholder="Enter your email" />
                  </Form.Item>

                  <Button type="primary" htmlType="submit">
                    Submit
                  </Button>
                </Form>
              </div>
            }
          />
          {PrintingData?.length > 0 &&

            <div
              style={{ display: "none" }}

            >
              <DeliveryPrint
                PrintingData1={[PrintingData]}
                DCprinterTemplateStyle={DCPrintTemplateStyle}
                DCPrintTemplateDtl={DCPrintTemplateDtl}
              />
            </div>
          }
        </div>
      </div>
    </div>
  );
};
export default DeliveryChellanForm;