import React, { useCallback, useEffect, useRef, useState } from 'react';
import { AiFillPrinter, AiOutlineCheckSquare } from 'react-icons/ai';
import { useDispatch, useSelector } from 'react-redux';
import { DefaultModal } from '../../../../../Components/Modal/DefaultModal';
import {
  Button,
  Checkbox,
  Input,
  Modal,
  Pagination,
  Switch,
  Tooltip,
} from 'antd';
import {
  getSession,
  printDiv,
  extractLastNumberOrderId,
  ExtractDateFormate,
  dateTimeFormatChange,
} from '../../../../../Services/Others';
import { Tables } from '../../../../../Components/Tables/Table';
import {
  getRePrintDefault,
  postDefaultReprintReason,
  postRePrintReason,
  ReprintDetails,
} from '../../../../../Features/BookingScreen/Customer/addCustomer';
import {
  GlobalprintDatas,
  SelectedPrintTemplate,
  GlobalPrinterMappingDtls,
  getPrinterMappingDetails,
  getPrintSelectionComponentData,
} from '../../../../../Features/ThemeChange/ThemeChange';
import FormHeader from '../../../../../Pages/PageComponents/FormHeader';
import { ArrowRightOutlined } from '@ant-design/icons';
import { PrintStyleFunction } from '../../../../paymentpdfPage/PrintStyleFunction.js';
import moment from 'moment';
import { isMobile } from 'react-device-detect';
import MobilePrint from '../../BookingFunctionality/MobilePrint.jsx';
import '../../../../../Styles/BookingScreen/Components/OtherConponents/Reprint/BSReprint.scss';
import PaymentPdfBooking from '../../../../paymentpdfPage/PaymentPdfBooking.jsx';
import {
  changeBillEditingMode,
  changeEstimateBooking,
  changeHoldOrderDtl,
  changeOrderCardDetails,
  changeOrderType,
  ChangeOverAllDiscEstimate,
  ChangeOverAllDiscSales,
  changePreviousOrderOfferDetail,
  changePreviousOrderPayment,
  changeReorderHoldDetails,
  changeReorderProductDetails,
  ChangeSelectedCustDisable,
  changeSelectedCustId,
  changeSelectedOption,
  changeSelProdWiseEst,
  getAllCustomer,
  getConfigType,
  getCustomerForHold,
  GlobalSalesBillEdit,
  GlobalSelectedCustDisable,
  PreferenceData,
} from '../../../../../Features/BookingScreen/BookingData/BookingData.js';
import { DatePicker, Form } from 'antd';
import { DropDowns } from '../../../../../Components/Forms/DropDown.jsx';
import TextAreaInput from '../../../../../Components/Forms/TextArea.jsx';
import Buttons from '../../../../../Components/Forms/Buttons.jsx';
import { Messages } from '../../../../../Components/Notifications/Messages.jsx';
import { ApplicationPreferences } from '../../../../../Features/BrachLogin/BranchLogin.js';
import { IoEye } from 'react-icons/io5';
const { RangePicker } = DatePicker;
import { MobilePdfPrint } from '../../BookingFunctionality/MobilePdfPrint.js';
import { FaDownload } from 'react-icons/fa';
import { MdEmail } from 'react-icons/md';
import { FaWhatsapp } from 'react-icons/fa';
import {
  MobileMultiPdfPrint,
  PdfProcessingProgress,
} from '../../BookingFunctionality/MobileMultiPdfPrint.jsx';
import { TbSettingsCog } from 'react-icons/tb';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { axiosRetailInstanceData } from '../../../../../Features/AuthenicationToken/AuthenticationToken.js';
import { MdEdit } from "react-icons/md";
import { v4 as uuidv4 } from 'uuid';
import { changeOrderOfferDetail } from '../../../../../Features/Offer/Offer.js';
import { ChangeFullFreeProductList, changeFullOfferAppliedProducts, changeLoyaltyConsumedQuantities } from '../../../../../Features/Offer/Offernew/BookingOffernew.js';
import { ChangeTotalAmount } from '../../../../../Features/ExteraCharges/ExtraCharges.js';

const RetailApiurl = import.meta.env.ENV_API_URL;

function BSReprint({ setOpenModel = () => { } }) {
  const dispatch = useDispatch();
  const queryClient = useQueryClient();
  const appPreferences = useSelector(ApplicationPreferences);
  const bookingTypePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Booking Type'
  )?.PreferenceCatDetails;
  const printerTemplateStyle = useSelector(SelectedPrintTemplate);
  const [message, setMessage] = useState({ type: null, data: null });
  const reprintReasonRef = useRef();
  const [reprint, setReprint] = useState(false);
  const [reprintDetaile, setReprintDetaile] = useState();
  const [table2Data, settable2Data] = useState([]);
  const [reprintReasonModel, setReprintReasonModel] = useState({
    modal: false,
    action: 'without',
    default: true,
  });

  const [SearchText, setSearchText] = useState(null);
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectAll, setSelectAll] = useState(false);
  const [bulkMode, setBulkMode] = useState(false);
  const [loading, setLoading] = useState(false);
  const [reprintData, setReprintData] = useState([]);
  console.log(reprintData, 'reprintData');
  const [reprintReasonList, setReprintReasonList] = useState([]);
  const [isDuplicate, setIsDuplicate] = useState('Original');
  const [BillSearch, setBillSearch] = useState('');
  const [EmailId, setEmailId] = useState('');
  const [emailModalOpen, setEmailModalOpen] = useState(false);
  const [page, setpage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [DefReason, setDefReason] = useState({});
  const SettingDataSelector = useSelector(PreferenceData);
  const salesBillEdit = useSelector(GlobalSalesBillEdit);
  const custDisable = useSelector(GlobalSelectedCustDisable);
  console.log(SettingDataSelector, 'SettingDataSelector');
  const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'mobilea4' &&
      setting?.SettingValue === 'Y'
  );
  const editBill = SettingDataSelector?.[0]?.SettingDtlDetails?.find(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'editbill' &&
      setting?.SettingValue === 'Y'
  );
  const TokenOnly = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
    (i) => i.SettingIdName === 'TokenOnly'
  )?.[0];
  const IndividualToken = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
    (i) => i.SettingIdName === 'AllProductindividualToken'
  )?.[0];
  const Weightasquantity = SettingDataSelector?.[0]?.SettingDtlDetails?.some(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'weightasquantity' &&
      setting?.SettingValue === 'Y'
  );
  const printDatas = useSelector(GlobalprintDatas);
  console.log(printDatas, 'GlobalprintDatas');
  const PrinterDetails = useSelector(GlobalPrinterMappingDtls);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');
  const AuthToken = sessionStorage.getItem('auth');
  const SessionMobileNo = getSession('MobileNo');
  const [dateStrings, setDateStrings] = useState([]);
  // ---- 1. Fetch Function ----
  const fetchData = async ({ queryKey }) => {
    const [_, dates, page] = queryKey;

    const Response = await dispatch(
      ReprintDetails({
        CompId,
        BranchId,
        AppId,
        OrderFromDate: dates?.[0] ?? '',
        OrderToDate: dates?.[1] ?? '',
        PageNumber: page,
      })
    ).unwrap();
    if (Response?.data?.statusCode === 1) {
      return Response?.data?.data;
    } else {
      return [];
    }
  };

  const { data, isLoading, error } = useQuery({
    queryKey: ['reprint', dateStrings, page],
    queryFn: fetchData,
    enabled: true,
    staleTime: 1000 * 60 * 5,
    cacheTime: 1000 * 60 * 30,
    keepPreviousData: true,
    refetchOnMount: 'always',
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
  });

  const { data: countData } = useQuery({
    queryKey: ['searchReprint', SearchText],
    queryFn: searchData,
    enabled: !!SearchText,
    staleTime: 1000 * 60 * 5,
    cacheTime: 1000 * 60 * 30,
    keepPreviousData: true,
    refetchOnMount: 'always',
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
  });

  async function searchData({ queryKey }) {
    const [_, SearchText] = queryKey;

    const res = await axiosRetailInstanceData.get(
      `/rePrint?compId=${CompId}&appId=${AppId}&branchId=${BranchId}&type=B&orderId=${SearchText}`
    );
    if (res?.data?.statusCode == 1) {
      setpage(1);
      return res?.data?.data;
    } else {
      return [];
    }
  }

  const countOfProduct = SearchText
    ? countData?.length
      ? countData?.length
      : 0
    : data?.[0]?.TotalCount;
  console.log(countOfProduct, 'countOfProduct');
  useEffect(() => {
    const commonMasterApiCall = async () => {
      try {
        // queryClient.invalidateQueries(['reprint']);
        const response = await dispatch(
          getConfigType({ TypeName: 'Reprint Reason' })
        ).unwrap();
        if (response.data.statusCode === 1) {
          setReprintReasonList(response?.data?.data);
        } else {
          setMessage({ type: 'error', data: response?.data?.response });
        }
      } catch (error) {
        setMessage({ type: 'error', data: error.message });
      }
    };
    commonMasterApiCall();
    DefaultReprintReason();
  }, []);
  useEffect(() => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      // UserId: UserId,
    };
    dispatch(getPrinterMappingDetails(data)).unwrap();
    const Data1 = { AppId, CompId, BranchId };
    dispatch(getPrintSelectionComponentData(Data1)).unwrap();
  }, []);
  const handleDateChange = (dates, dateStrings) => {
    // setDateRange(dateStrings);
    if (dateStrings[0] && dateStrings[1]) {
      setDateStrings(dateStrings);
      setpage(1);
    }
  };
  const DefaultReprintReason = async () => {
    let data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      Status: 'Y',
    };
    let defaultget = await dispatch(getRePrintDefault(data)).unwrap();
    if (defaultget.data.statusCode === 1) {
      let apiData = defaultget?.data?.data?.[0];
      setDefReason(apiData);
    } else {
      setDefReason({});
      reprintReasonRef?.current?.resetFields();
      setIsDuplicate('Original');
    }
  };

  const reprintReasonDropDownChange = (event) => {
    reprintReasonRef?.current?.setFieldsValue({ Reason: event });
  };
  const HandleReprint = async (reprintData, type) => {
    console.log(type, reprintReasonModel, 'type-reprintReasonModel');
    const PrintLogo = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
      (i) => i.SettingIdName?.toLowerCase() === 'printlogo'
    )?.[0];
    const PrintGreeting = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
      (i) => i.SettingIdName?.toLowerCase() === 'printgreetings'
    )?.[0];
    const EstimateHeader = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
      (i) => i.SettingIdName?.toLowerCase() === 'estimateprintheader'
    )?.[0];
    const SalesMode = SettingDataSelector?.[0]?.SettingDtlDetails?.filter(
      (i) => i.SettingIdName?.toLowerCase() === 'sales mode'
    )?.[0];

    const WithorWithoutToken = type == 'with' ? true : false;
    if (isMobile) {
      if (MobileA4Print) {
        const Tokenthere = TokenOnly?.SettingValue === 'Y';
        const Individual = IndividualToken?.SettingValue === 'Y';
        const PrintGrettingthere = PrintGreeting?.SettingValue === 'Y';
        const Printlogothere = PrintLogo?.SettingValue === 'Y';
        const EstimateHeaderthere = EstimateHeader?.SettingValue === 'Y';
        const SalesModethere = SalesMode?.SettingValue === 'Y';
        const takeAwayPreference = bookingTypePreference?.some(
          (type) =>
            type?.PreferredSubCatName?.toLowerCase() === 'take away' &&
            type?.PreferredStatus === 'Y'
        );

        const orderidlist = reprintData?.map((item) => ({
          OrderId: item.OrderId,
        }));
        const filesJson = JSON.stringify(PrinterDetails);
        const Stylename = printDatas?.StyleName;
        const PrintSize = printDatas?.PageSize ? printDatas?.PageSize : '3inch';
        const isCreditDetailsAvailable = printDatas?.FieldDetails?.some(
          (item) =>
            String(item?.ConfigName || '').toLowerCase() === 'credit details'
        );
        console.log(printDatas, printDatas?.StyleName, 'printDatas');
        var receiptText = '';
        var textEncoded = encodeURI(receiptText);
        var scheme = 'pozoprinter';
        var packageName = 'com.example.pozoprinter';
        window.location.href =
          scheme +
          '://' +
          textEncoded +
          '#Intent;scheme=' +
          scheme +
          ';package=' +
          packageName +
          'AppIdS' +
          AppId +
          'AppIdE' +
          'CompIdS' +
          CompId +
          'CompIdE' +
          'BranchIdS' +
          BranchId +
          'BranchIdE' +
          'UserIdS' +
          UserId +
          'UserIdE' +
          'ApiClientS' +
          RetailApiurl +
          'ApiClientE' +
          'InvoiceOrderIdS' +
          JSON.stringify(orderidlist) +
          'InvoiceOrderIdE' +
          'MobileNoS' +
          SessionMobileNo +
          'MobileNoE' +
          'AuthTokenS' +
          AuthToken +
          'AuthTokenE' +
          'PrintSizeS' +
          PrintSize +
          'PrintSizeE' +
          'PrintTypeS' +
          Stylename +
          'PrintTypeE' +
          'TokenOnlyS' +
          Tokenthere +
          'TokenOnlyE' +
          'AllProductindividualTokenS' +
          Individual +
          'AllProductindividualTokenE' +
          'PrintGreetingsS' +
          PrintGrettingthere +
          'PrintGreetingsE' +
          'PrintLogoS' +
          Printlogothere +
          'PrintLogoE' +
          'ReprintS' +
          true +
          'ReprintE' +
          'WithTokenS' +
          WithorWithoutToken +
          'WithTokenE' +
          'ReprintTextS' +
          isDuplicate +
          'ReprintTextE' +
          'CustomerCreditPrintS' +
          isCreditDetailsAvailable +
          'CustomerCreditPrintE' +
          'EstimatePrintHeaderS' +
          EstimateHeaderthere +
          'EstimatePrintHeaderE' +
          'SalesModeS' +
          SalesModethere +
          'SalesModeE' +
          'TakeAwayPreferenceS' +
          takeAwayPreference +
          'TakeAwayPreferenceE' +
          'IpS' +
          filesJson +
          'IpE' +
          'ConfigurationS' +
          true +
          'ConfigurationE' +
          ';end;';
        // var receiptText = '';
        // var textEncoded = encodeURI(receiptText);
        // var scheme = 'pozoprinter';
        // var packageName = 'com.example.pozoprinter';
        // window.location.href =
        //   scheme +
        //   '://' +
        //   textEncoded +
        //   '#Intent;scheme=' +
        //   scheme +
        //   ';package=' +
        //   packageName +
        //   'AppIdS' +
        //   AppId +
        //   'AppIdE' +
        //   'CompIdS' +
        //   CompId +
        //   'CompIdE' +
        //   'BranchIdS' +
        //   BranchId +
        //   'BranchIdE' +
        //   'UserIdS' +
        //   UserId +
        //   'UserIdE' +
        //   'ApiClientS' +
        //   RetailApiurl +
        //   'ApiClientE' +
        //   'InvoiceOrderIdS' +
        //   reprintData?.[0]?.OrderId +
        //   'InvoiceOrderIdE' +
        //   'MobileNoS' +
        //   SessionMobileNo +
        //   'MobileNoE' +
        //   'AuthTokenS' +
        //   AuthToken +
        //   'AuthTokenE' +
        //   'PrintTypeS' +
        //   printDatas?.PageSize +
        //   'PrintTypeE'
        // ';end;';

        // // MobilePdfPrint()
        // await MobilePdfPrint({
        //   printerTemplateStyle,
        //   printDatas,
        //   PrintOrderDetails: reprintData,       // map table2Data → PrintOrderDetails
        //     PrintComing: 'Reprint'
        // });
      } else {
        MobilePrint(
          appPreferences,
          reprintData,
          '',
          'Reprint',
          SettingDataSelector,
          type
            ? type
            : reprintReasonModel.action === 'with'
              ? 'WithToken'
              : 'WithOutToken'
        );
      }
    } else {
      Print(reprintData, type ? type : reprintReasonModel.action);
    }
    reprintReasonRef?.current?.resetFields();
    setReprintReasonModel({ modal: false, action: 'without', default: true });
  };
  const handleReprintReasonSubmission = async (printdata, type) => {
    console.log(
      reprintReasonRef?.current?.getFieldsValue(),
      'reprintReasonRef?.current?.getFieldsValue(),'
    );
    if (reprintReasonModel.action === 'NoPrint') {
      const checked = reprintReasonRef?.current?.getFieldValue('SetAsDefault');
      const payload = {
        ...reprintReasonRef?.current?.getFieldsValue(),
        SetAsDefault: checked ? 'Y' : 'N',
      };
      const postData = {
        UserId,
        CompId,
        BranchId,
        AppId,
        CreatedBy: UserId,
        SetAsDefault: payload?.SetAsDefault,
        DefaultType: 'Reprint',
        DefaultDetails: [
          {
            Description: payload?.Description,
            Reason: payload?.Reason,
            ReprintType: isDuplicate,
          },
        ],
      };
      const response = await dispatch(
        postDefaultReprintReason(postData)
      ).unwrap();
      if (response.data.statusCode === 1) {
        setReprintReasonModel({
          modal: false,
          action: 'without',
          default: true,
        });
        DefaultReprintReason();
      }
      console.log(postData, 'postDataNoPrint');
    } else {
      let postData;
      if (Object.keys(DefReason)?.length > 0) {
        postData = {
          UserId,
          CompId,
          BranchId,
          AppId,
          BookingId: printdata?.[0]?.SalesId,
          CreatedBy: UserId,
          OrderId: printdata?.[0]?.OrderId,
          Reason: DefReason?.DefaultDetails?.[0]?.Reason,
          Description: DefReason?.DefaultDetails?.[0]?.Description || '',
        };
      } else {
        postData = {
          UserId,
          CompId,
          BranchId,
          AppId,
          BookingId: reprintData?.[0]?.SalesId,
          CreatedBy: UserId,
          OrderId: reprintData?.[0]?.OrderId,
          Reason: reprintReasonRef?.current?.getFieldsValue()?.Reason,
          Description: reprintReasonRef?.current?.getFieldsValue()?.Description,
        };
      }
      console.log(
        postData,
        reprintReasonModel,
        DefReason,
        printdata,
        'postDatapostData'
      );
      try {
        const response = await dispatch(postRePrintReason(postData)).unwrap();
        if (response.data.statusCode === 1) {
          let data =
            Object.keys(DefReason)?.length > 0 ? printdata : reprintData;
          HandleReprint(data, type);
          // setReprintData([]);
        } else {
          setMessage({ type: 'error', data: response?.data?.response });
        }
      } catch (error) {
        setMessage({ type: 'error', data: error.message });
      }
    }
  };

  const Print = async (reprintData, data) => {
    console.log(reprintData, 'reprintDatareprintData');
    const style = await PrintStyleFunction(
      printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle,
      'Reprint'
    );
    const stylesMap = {
      'Style 1': 'PrintStyle1',
      'Style 2': 'PrintStyle2',
      'Style 3': 'PrintStyle3',
      'Style 4': 'PrintStyle4',
      'Style 5': 'PrintStyle5',
      'Style 6': 'PrintStyle6',
      'Style 7': 'PrintStyle7',
      'Style 8': 'PrintStyle8',
      'Style 9': 'PrintStyle9',
      'Style 10': 'PrintStyle10',
      'Style 11': 'PrintStyle11',
      'Style 12': 'PrintStyle12',
      'Style 13': 'RePrint',
      A4: 'PrintStyleA4',
      A5: 'PrintStyleA5',
      A4Standard: 'A4Standard',
      TaxInvoice: 'TaxInvoice',
    };

    const selectedStyle =
      stylesMap[
      printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle
      ];
    if (selectedStyle) {
      if (data === 'without') {
        await Promise.all(
          reprintData?.map(async (orderDetail, index) => {
            await printDiv(`${selectedStyle}-${index}`, style); // Use unique IDs for each print
          })
        );
      } else {
        await Promise.all(
          reprintData?.map(async (orderDetail, index) => {
            await printDiv(`${selectedStyle}-${index}`, style); // Use unique IDs for each print
            if (orderDetail?.BookingTypeName !== 'Dine In') {
              const groupedTokens = orderDetail?.productDetails?.reduce(
                (acc, item, idx) => {
                  if (item.TokenAvailable === 'Y') {
                    if (!item.CounterName) {
                      // If CounterName is null or empty
                      acc[`individual-${idx}-${item.ProdId}`] = [item]; // Unique entry for each null/empty CounterName item
                    } else {
                      if (!acc[item.CounterName]) {
                        acc[item.CounterName] = [];
                      }
                      acc[item.CounterName].push(item); // Group by CounterName
                    }
                  }
                  return acc;
                },
                {}
              );

              // Iterate over grouped tokens and print them
              const tokensToPrint = Object.entries(groupedTokens).map(
                async ([counterName, items], idx) => {
                  // Use the counterName (or unique identifier for individual items) as part of the tokenId
                  const tokenId = `${idx}-${items?.[0]?.ProdId}-${counterName}`;
                  await TokenPrint(tokenId, items); // Pass all grouped items to the print function
                }
              );

              if (tokensToPrint?.length > 0) {
                await Promise.all(tokensToPrint);
              }
            }
          })
        );
      }
      // setReprintData([]);
    }

    ReprintCancel();
  };

  const TokenPrint = async (index) => {
    try {
      console.log(`Starting token print for index ${index}`);

      const stylePrint = `<style> 
      *{
        font-family:Poppins;
      }
    
      .Reprint-body{  
        height: 100%;
        margin: 0vw 0vh;
        padding: 1vw 2vh;
      }
    
      .Re-print-body-Tr {
        text-align: center;
        font-family: Poppins;
      }
      .Re-print-body-Product{
        text-align:left;
        font-size:12px;
        border: 1px solid black;
        border-collapse: collapse;
        font-family: Poppins;
        padding-left:5px;
      }
      .Re-print-body-Rate{
        text-align:right;
          font-size:12px;
          padding-right:5px;
          border: 1px solid black;
          border-collapse: collapse;
          font-family: Poppins;
      }
      .Re-print-Logo{
        width: 50px ;
        height: 50px;
        margin-bottom: -20px;
       }
    
      .Re-print-title {
        font-size: 19px;
        font-weight: 600;
        font-family: Gilroy;
        margin-bottom: -10px;
        text-align:center;
      }
      
      .Re-print-Add {
        font-size: 12px;
        font-family: Poppins;
        margin-bottom: -5px;
      }
      
      .Re-print-GST {
        font-size: 12px;
        font-family: Poppins;
      }
    
      .Re-print-top {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
      }
    
      .Re-print-top2 {
        display: flex;
        width: 90%;
        margin:0px 10px;
        font-family: Gilroy;
        justify-content: space-between;
      }
      .Re-print-top3 {
        display: flex;
        width: 75%;
        margin:0px 30px;
        font-family: Gilroy;
        justify-content: space-between;
        margin-bottom: 5px;
      }
      .Re-print-bold{
        font-size: 8px;
        font-weight: 400;
        font-family: Poppins;
        letter-spacing: 1px;
      }
    
      .Re-print-bold1{
        font-size: 12px;
        font-weight: 600;
        font-family: Poppins;
        letter-spacing: 1px;
      }
      .Re-print-bold2{
        width:100%;
        font-size: 12px;
        font-family: Poppins;
        text-align:center;
      }
    
      .Re-print-Table {
          width: 90%;
          margin:0px 10px;
        }
    
      .Re-print-Table ,.Re-print-th ,.Re-print-td {
          border: 1px solid black;
          border-collapse: collapse;
          font-family: Poppins;
        }
        .Re-print-td
        {
          font-size:12px;
        }
    
      </style>`;

      await printDiv(`TakeawayToken${index}`, stylePrint);
    } catch (error) {
      console.error(`Error printing token for index ${index}:`, error);
    }
  };

  const ReprintCancel = () => {
    setReprint(false);
  };

  const dataSource = data;

  const filteredData = SearchText
    ? countData?.length
      ? countData
      : []
    : dataSource;

  const handlePageChange = (current) => {
    setpage(current);
  };
  function safeRound(amountStr) {
    if (amountStr == null) return '0.00';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    return isNaN(num) ? '0.00' : num.toFixed(2); // return as string with 2 decimals
  }
  const Reprintformdata = () => {
    if (Object.keys(DefReason)?.length > 0) {
      reprintReasonRef?.current?.setFieldsValue({
        ReprintType: DefReason?.DefaultDetails?.[0]?.ReprintType || 'Original',
        Reason: DefReason?.DefaultDetails?.[0]?.Reason, // must match your DropDown option value (ConfigId)
        Description: DefReason?.DefaultDetails?.[0]?.Description,
        SetAsDefault: DefReason?.SetAsDefault === 'Y', // convert "Y"/"N" to boolean
      });
      setIsDuplicate(DefReason?.DefaultDetails?.[0]?.ReprintType || 'Original');
    }
  };
  const columns = [
    {
      title: 'SL NO',
      dataIndex: 'SINO',
      key: 'SINO',
      align: 'center',
      width: '50px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Bill No',
      dataIndex: 'BillNo',
      key: 'BillNo',
      width: '75px',
      render: (text, row) => (
        <a style={{ color: 'black', fontSize: '12px' }}>
          {row?.OrderPaymentDtl?.[0]?.OrderId?.split('-')?.pop()}
        </a>
      ),
    },
    {
      title: 'Order No',
      dataIndex: 'OrderNo',
      key: 'OrderNo',
      width: '75px',
      render: (text, row) => (
        <a style={{ color: 'black', fontSize: '12px' }}>
          {row?.SalesId?.split('-')?.pop()}
        </a>
      ),
    },
    {
      title: 'Customer',
      dataIndex: 'CustSuppName',
      key: 'CustSuppName',
      width: '100px',
      render: (text, row) => (
        <a style={{ color: 'black', fontSize: '12px' }}>
          {row?.CustSuppName || row?.CustomerDetails?.[0]?.MobileNo || '-'}
        </a>
      ),
    },
    // {
    //   title: 'Item Name',
    //   dataIndex: 'ItemName',
    //   key: 'ItemName',
    //   render: (text, row) => (
    //     <a style={{ color: 'black'}}>
    //       {row?.productDetails?.map(
    //         (item, index) =>
    //           (index > 0 ? ',' : '') +
    //           item.ProdName +
    //           ' ' +
    //           item.Size +
    //           ' ' +
    //           item.UomName
    //       )}
    //     </a>
    //   ),
    // },

    {
      title: 'Date',
      dataIndex: 'Date',
      key: 'Date',
      width: '100px',
      align: 'right',
      render: (text, row) => (
        <a style={{ color: 'black', fontSize: '12px' }}>
          {ExtractDateFormate(row.SalesDate)}
        </a>
      ),
    },
    {
      title: 'Products',
      dataIndex: 'productDetails',
      render: (text, row) => {
        const items = row?.productDetails || [];
        const visible = items
          .slice(0, 2)
          .map((item) => `${item.ProdName} ${item.Size} ${item.UomName}`);
        const hidden = items
          .slice(2)
          .map((item) => `${item.ProdName} ${item.Size} ${item.UomName}`);

        return (
          <>
            {visible.join(', ')}
            {hidden.length > 0 && (
              <Tooltip
                trigger={isMobile ? 'click' : 'hover'}
                title={hidden.join(', ')}
              >
                <span style={{ color: 'blue', cursor: 'pointer' }}>
                  {' '}
                  +{hidden.length} more
                </span>
              </Tooltip>
            )}
          </>
        );
      },
    },
    {
      title: 'View',
      key: 'OrderDetails',
      dataIndex: 'OrderDetails',
      align: 'center',
      render: (text, row) => (
        <IoEye
          style={{ color: '#1292EE', fontSize: '25px', cursor: 'pointer' }}
          onClick={() => {
            settable2Data([row]);
            setReprintData([row]);
            setReprint(true);
          }}
        />
      ),
    },
    // ...(editBill ? [
    {
      title: 'Edit Bill',
      key: 'EditBill',
      dataIndex: 'EditBill',
      align: 'center',
      render: (text, row) => (
        <MdEdit
          style={{ color: '#1292EE', fontSize: '25px', cursor: 'pointer' }}
          onClick={async (e) => await handleEditBill(e, row)}
        />
      ),
    }
    // ] : [])
    ,
    {
      title: () => (
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: '8px',
          }}
        >
          <span>PRINT RECEIPT</span>
          {UserType !== 'Employee' && (
            <AiOutlineCheckSquare
              style={{
                cursor: 'pointer',
                fontSize: '18px',
                color: bulkMode ? 'blue' : 'black',
              }}
              onClick={() => {
                setBulkMode(!bulkMode);
                setSelectedRows([]); // reset when toggling
                setReprintData([]);
                setSelectAll(false);
              }}
            />
          )}
          {bulkMode && (
            <input
              type="checkbox"
              checked={selectAll}
              onChange={(e) => {
                const checked = e.target.checked;
                setSelectAll(checked);
                if (checked) {
                  setSelectedRows(dataSource); // ✅ all rows selected
                  setReprintData(dataSource);
                } else {
                  setSelectedRows([]);
                  setReprintData([]);
                }
              }}
            />
          )}
        </div>
      ),
      dataIndex: 'PRINTRECEIPT',
      key: 'PRINTRECEIPT',
      align: 'center',
      width: '100px',
      render: (text, row) => {
        if (bulkMode) {
          const isChecked = selectedRows.some((r) => r.SalesId === row.SalesId);
          return (
            <input
              type="checkbox"
              checked={isChecked}
              onChange={(e) => {
                if (e.target.checked) {
                  setSelectedRows((prev) => [...prev, row]); // ✅ store full row object
                  setReprintData((prev) => [...prev, row]);
                } else {
                  setSelectedRows((prev) =>
                    prev.filter((r) => r.SalesId !== row.SalesId)
                  );
                  setReprintData((prev) =>
                    prev.filter((r) => r.SalesId !== row.SalesId)
                  );
                  setSelectAll(false);
                }
              }}
            />
          );
        }

        // 👇 normal behavior (your print buttons)
        return (
          <div className="reprint-btn-wrapper">
            {/* ✅ Always visible icon */}

            {/* Conditional buttons/icons */}
            {row?.productDetails?.some(
              (item) => item.TokenAvailable === 'Y'
            ) ? (
              <div className="reprint-btn-wrapper">
                <button
                  className="Re-Print-Button"
                  onClick={async () => {
                    setReprintData([row]);
                    if (Object.keys(DefReason)?.length > 0) {
                      handleReprintReasonSubmission([row], 'without');
                    } else {
                      setReprintReasonModel({
                        modal: true,
                        action: 'without',
                        default: false,
                      });
                    }
                  }}
                >
                  <AiFillPrinter className="BSC1Payment-icon" />
                  Bill Without Token
                </button>
                <button
                  className="Re-Print-Button"
                  onClick={() => {
                    setReprintData([row]);
                    if (Object.keys(DefReason)?.length > 0) {
                      handleReprintReasonSubmission([row], 'with');
                    } else {
                      setReprintReasonModel({
                        modal: true,
                        action: 'with',
                        default: false,
                      });
                    }
                  }}
                >
                  <AiFillPrinter className="BSC1Payment-icon" />
                  Bill With Token
                </button>
              </div>
            ) : (
              <AiFillPrinter
                style={{ fontSize: '22px', cursor: 'pointer' }}
                onClick={() => {
                  setReprintData([row]);
                  if (Object.keys(DefReason)?.length > 0) {
                    handleReprintReasonSubmission([row], 'without');
                  } else {
                    setReprintReasonModel({
                      modal: true,
                      action: 'without',
                      default: false,
                    });
                  }
                }}
              />
            )}
          </div>
        );
      },
    },
  ];
  const columns2 = [
    {
      title: 'SI NO',
      dataIndex: 'SINO',
      key: 'SINO',
      align: 'center',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{index + 1}</a>
      ),
    },
    {
      title: 'Item',
      dataIndex: 'ProdName',
      key: 'Item',
    },
    {
      title: 'Qty',
      dataIndex: 'SalesQty',
      key: 'Qty',
      align: 'right',
    },
    {
      title: 'Rate',
      dataIndex: 'Rate',
      key: 'Rate',
      align: 'right',
      render: (rate) => <span>{safeRound(rate)}</span>,
    },
    {
      title: 'Price',
      dataIndex: 'TotalAmt',
      key: 'Price',
      align: 'right',
      render: (Price) => <span>{safeRound(Price)}</span>,
    },
  ];

  const handleToggle = (checked) => {
    setIsDuplicate(checked ? 'Duplicate' : 'Original');
    console.log('Reprint type:', checked ? 'Duplicate' : 'Original');
  };
  console.log(reprintData, 'aaaaaaaaaaaaaaaaaaaa');
  const handleDownload = async () => {
    await MobilePdfPrint({
      printerTemplateStyle,
      printDatas,
      PrintOrderDetails: reprintData, // map table2Data → PrintOrderDetails
      PrintComing: 'download',
    });
  };

  const handleEmail = () => {
    setEmailModalOpen(true);
  };

  const handleSendEmail = async () => {
    try {
      if (selectedRows.length === 0) {
        setLoading(true);

        const result = await MobilePdfPrint({
          printerTemplateStyle,
          printDatas,
          PrintOrderDetails: reprintData,
          PrintComing: 'email',
          emailId: EmailId,
          dispatch,
        });

        if (result?.data?.status === 1) {
          setEmailModalOpen(false); // ✅ Close modal
          setEmailId(''); // ✅ Reset email input (optional)
          setLoading(false);
        }
      } else {
        mutiplePrint('email');
      }
    } catch (err) {
      console.error('❌ Email error:', err);
    }
  };

  const handleWhatsApp = async () => {
    await MobilePdfPrint({
      printerTemplateStyle,
      printDatas,
      PrintOrderDetails: reprintData, // map table2Data → PrintOrderDetails
      PrintComing: 'whatsapp',
      UserId: UserId,
      dispatch,
    });
  };

  const [processingProgress, setProcessingProgress] = useState(0);
  const [isProcessing, setIsProcessing] = useState(false);

  const mutiplePrint = async (printType) => {
    setIsProcessing(true);
    setProcessingProgress(0);

    const result = await MobileMultiPdfPrint({
      printerTemplateStyle,
      printDatas,
      PrintOrderDetails: selectedRows,
      setPrintOrderDetails: setReprintData,
      PrintComing: printType,
      emailId: EmailId,
      UserId: UserId,
      dispatch,
      onProgress: (progress) => setProcessingProgress(progress),
    });

    setIsProcessing(false);

    if (printType === 'email') {
      if (result?.data?.status === 1) {
        setEmailModalOpen(false);
        setEmailId('');
        setSelectedRows([]);
        setSelectAll(false);
        setBulkMode(false);
      } else {
        setSelectedRows([]);
        setSelectAll(false);
        setBulkMode(false);
      }
    } else {
      setSelectedRows([]);
      setSelectAll(false);
      setBulkMode(false);
    }
  };

  const onComplete = useCallback(() => {
    setMessage({ type: null, data: null });
  }, []);

  function Debounce(fn, delay) {
    let timer;
    return function (...args) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn(...args);
      }, delay);
    };
  }
  const searchOrderIDFn = (value) => {
    setSearchText(value);
  };
  const debouncedSearch = useCallback(Debounce(searchOrderIDFn, 500), []);

  console.log(table2Data, 'table2Datadfnfjd');

  const totalSalesQty = table2Data?.[0]?.productDetails?.reduce((acc, item) => {
    const isWeightScale = item?.ScaleType === 'weight';

    if (isWeightScale) {
      return acc + (
        Weightasquantity
          ? Math.round(Number(item?.SalesQty || item?.OrderQty || 0))
          : 1
      );
    }

    return acc + Math.round(Number(item?.SalesQty || item?.OrderQty || 0));
  }, 0)

  const widthOutTexAmt = table2Data?.[0]?.TaxDetails?.reduce(
    (sum, item) => sum + (item?.WithOutTaxAmount || 0),
    0
  );

  const handleEditBill = async (e, orderDtls) => {
    setOpenModel(e);
    dispatch(changeBillEditingMode(true));
    const {
      productDetails,
      ExtraChargeDetails,
      CustSuppId,
      OrderOfferDetails,
      RefDetails,
      OrderId,
      OrderType,
      OverallDisc,
      OrderPaymentDtl,
    } = orderDtls;
    const updated = productDetails?.map((item) => ({
      ...item,
      Offer: item?.OfferAmt,
      localId: uuidv4(),
      OfferMode: item?.OfferMode ? item?.OfferMode?.trim() : null,
      VariantAvailableFrom: item?.AvailableFrom || null,
      VariantAvailableTo: item?.AvailableTo || null,
      OrderQty: item?.SalesQty,
      OrderRate: item?.Rate,
      // TotalAmt: formatAmount((item.TotalAmt - item.OfferValue)),
    }));

    if (RefDetails?.[0]?.FreeProdList) {
      dispatch(ChangeFullFreeProductList(RefDetails[0]?.FreeProdList));
    }

    if (RefDetails?.[0]?.OfferAppliedProductList) {
      dispatch(
        changeFullOfferAppliedProducts(
          RefDetails[0]?.OfferAppliedProductList
        )
      );
    }



    if (CustSuppId) {
      let res = await dispatch(
        getCustomerForHold({
          CompId: CompId,
          AppId: AppId,
          branchId: BranchId,
          OrderId: OrderId,
        })
      ).unwrap();

      if (res?.data?.statusCode !== 1) {
        res = await dispatch(
          getAllCustomer({
            CompId: CompId,
            AppId: AppId,
            branchId: BranchId,
          })
        ).unwrap();
      }

      if (res?.data?.statusCode === 1) {

        const loyaltyFreeProductOfferApplied = (RefDetails?.[0]?.OfferAppliedProductList || [])?.filter(
          (off) =>
            off?.FreeProductsList?.OfferMode === 'L' &&
            off?.TableUniqueName === 'FreeProduct'
        );

        const customerDetails = res?.data?.data?.find(
          (item) => item.CustId === CustSuppId
        );

        if (customerDetails) {
          const { CustId, CustName, CustMobile, LoyaltyPointsDetail, TotalLoyaltyPoints } = customerDetails;
          const data = {
            CustId: CustId,
            CustName: CustName,
            label: CustName ? CustName : CustMobile,
            value: CustMobile,
            LoyaltyPointsDetail: LoyaltyPointsDetail,
            TotalLoyaltyPoints: TotalLoyaltyPoints
          };

          dispatch(changeOrderOfferDetail([...OrderOfferDetails]));
          dispatch(changeSelectedOption(data));
          await dispatch(ChangeSelectedCustDisable(true));

          if (loyaltyFreeProductOfferApplied?.length > 0) {
            const loyaltyProdQuantities = {};

            loyaltyFreeProductOfferApplied.forEach((off) => {
              const freeProdDtls = off?.FreeProductsList;
              const freeProdOfferId =
                freeProdDtls?.ProdVariantDetails?.[0]?.StockDetails?.[0]
                  ?.ProdOfferId;

              const key = [
                freeProdDtls?.OfferId,
                freeProdDtls?.FreeProdId,
                freeProdDtls?.FreeProdVariantName,
                freeProdOfferId,
              ].join('|');

              loyaltyProdQuantities[key] = freeProdDtls?.FreeQty || 0;
            });

            if (Object.keys(loyaltyProdQuantities).length > 0) {
              dispatch(changeLoyaltyConsumedQuantities(loyaltyProdQuantities));
            }

            console.log(loyaltyProdQuantities, 'loyaltyProdQuantities');
          }
        }

      }
    }
    await dispatch(changeOrderType('Hold'));
    await dispatch(changeHoldOrderDtl(true));
    await dispatch(changeReorderHoldDetails(orderDtls));
    await dispatch(changeReorderProductDetails(updated));
    await dispatch(changeSelectedCustId(CustSuppId));
    await dispatch(ChangeTotalAmount(ExtraChargeDetails));
    await dispatch(changePreviousOrderPayment(OrderPaymentDtl));
    await dispatch(changePreviousOrderOfferDetail(OrderOfferDetails));
    dispatch(changeOrderCardDetails(updated));
    let temp = updated?.filter((item) => item.OrderType === 'E')
      .map((item) => item.InwardDtlId + ' ' + item.BookingTypeName);
    await dispatch(changeSelProdWiseEst(temp));

    if (OrderType === 'E') {
      await dispatch(changeEstimateBooking('OvrAllEst'));
      await dispatch(ChangeOverAllDiscEstimate(parseFloat(OverallDisc)));
    } else {
      await dispatch(changeEstimateBooking('Sales'));
      await dispatch(ChangeOverAllDiscSales(parseFloat(OverallDisc)));
    }
  }

  return (
    <>
      <div>
        {/* Your existing JSX */}

        {/* Add the progress component */}
      </div>

      {reprintData?.length > 0 &&
        selectedRows.length > 0 &&
        reprintData?.map((orderDetail, index) => (
          <div style={{ display: 'none' }}>
            <PaymentPdfBooking
              index={index}
              table2Data={orderDetail}
              singleData2={orderDetail?.productDetails}
              ReprintType={isDuplicate}
              orderId={
                orderDetail?.OrderId &&
                extractLastNumberOrderId(
                  orderDetail?.OrderId,
                  orderDetail?.FYStatus
                )
              }
              CreatedDate={orderDetail?.CreatedDate}
              PaymentStatus={reprintData?.[0]?.OrderPaymentDtl}
              Preference={SettingDataSelector}
              printDatas={printDatas}
            />
          </div>
        ))}
      <Messages
        messageType={message.type}
        messageData={message.data}
        onComplete={onComplete}
      />
      <div style={{ width: '100%' }}>
        <div className="bsreprintmodaltable-flex">
          <div>
            {selectedRows.length > 0 && (
              <div className="action-icons-reprint">
                <FaDownload
                  onClick={() => mutiplePrint('download')}
                  className="icon-download"
                />
                <MdEmail onClick={() => handleEmail()} className="icon-email" />
                <FaWhatsapp
                  onClick={() => mutiplePrint('whatsapp')}
                  className="icon-whatsapp"
                />
              </div>
            )}
            <RangePicker
              placeholder={['Start Date', 'End Date']}
              format="YYYY-MM-DD"
              onChange={handleDateChange}
            />
          </div>
          <div className="bsreprintmodaltable-search">
            <input
              type="text"
              placeholder="Search Bill No..."
              // value={SearchText}
              onChange={(e) => {
                debouncedSearch(e.target.value);
              }}
            />
          </div>
          <TbSettingsCog
            style={{ fontSize: '22px', cursor: 'pointer', marginRight: '8px' }}
            onClick={() => {
              setReprintReasonModel({
                modal: true,
                action: 'NoPrint',
                default: true,
              });
              Reprintformdata();
            }}
          />
        </div>
        {/* <div className="Re-Print-table"> */}
        <div className="bsreprintmodaltable">
          <Tables
            columns={columns}
            data={filteredData}
          // pagination={handlePageChange}
          />
          {countOfProduct > 10 && (
            <Pagination
              className="producttablepagination"
              current={page}
              total={countOfProduct}
              pageSize={10}
              onChange={handlePageChange}
              showSizeChanger={false}
              // showQuickJumper={true}
              showTotal={(total) =>
                `Total ${countOfProduct ? countOfProduct : 0} items`
              }
            />
          )}{' '}
        </div>
        <DefaultModal
          title={
            <div className="Holdmodel-title">
              <FormHeader title={'Reprint Reason'} />
            </div>
          }
          open={reprintReasonModel.modal}
          footer={false}
          children={
            <>
              <Form
                ref={reprintReasonRef}
                onFinish={handleReprintReasonSubmission}
                initialValues={{
                  ReprintType:
                    DefReason?.DefaultDetails?.[0]?.ReprintType || 'Original',
                  Reason: DefReason?.DefaultDetails?.[0]?.Reason,
                  Description: DefReason?.DefaultDetails?.[0]?.Description,
                  SetAsDefault: DefReason?.SetAsDefault === 'Y',
                }}
              >
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '1rem' }}>
                  <Form.Item
                    name="ReprintType"
                    initialValue="Original"
                    style={{ marginBottom: 0 }}
                  >
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '0.5rem',
                      }}
                    >
                      <Switch
                        checkedChildren="Duplicate"
                        unCheckedChildren="Original"
                        defaultChecked={false} // default Original
                        value={isDuplicate != 'Original'}
                        onChange={handleToggle}
                      />
                    </div>
                  </Form.Item>
                  <Form.Item
                    name="Reason"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Reprint reason Type',
                      },
                    ]}
                  >
                    <DropDowns
                      options={reprintReasonList?.map((option) => ({
                        value: option.ConfigId,
                        label: option.ConfigName,
                      }))}
                      label={
                        <label className="required">Reprint reason Type</label>
                      }
                      className="field-DropDown-Emp"
                      onChangeFunction={(e) => reprintReasonDropDownChange(e)}
                      valueData={
                        DefReason?.DefaultDetails?.[0]?.Reason ||
                        reprintReasonRef.current?.getFieldValue('Reason')
                      }
                    />
                  </Form.Item>
                  <Form.Item name="Description">
                    <TextAreaInput
                      autoComplete="off"
                      label={<label>Description..</label>}
                      defaultValue={
                        DefReason?.DefaultDetails?.[0]?.Description ||
                        reprintReasonRef.current?.getFieldValue('Description')
                      }
                      isOnChange={
                        reprintReasonRef.current?.getFieldValue('Description')
                          ? true
                          : false
                      }
                    />
                  </Form.Item>
                  {reprintReasonModel.default == true && (
                    <>
                      {/* ✅ Checkbox for Set as Default */}
                      <Form.Item
                        name="SetAsDefault"
                        valuePropName="checked" // important for checkbox binding
                      >
                        <Checkbox>Set as Default</Checkbox>
                      </Form.Item>
                    </>
                  )}
                </div>
                <div
                  style={{
                    width: '100%',
                    display: 'flex',
                    justifyContent: 'flex-end',
                  }}
                >
                  <Buttons
                    buttonText="SUBMIT"
                    color="901D77"
                    icon={<ArrowRightOutlined />}
                  />
                </div>
              </Form>
            </>
          }
          handleCancel={() => {
            setReprintData([]);
            setReprintReasonModel({ modal: false, action: 'without' });
          }}
        />
        <DefaultModal
          title={
            <div className="Holdmodel-title">
              <FormHeader title={'Order Details'} />
            </div>
          }
          open={reprint}
          footer={null}
          children={
            <>
              <div className="Re-Print-Container">
                <div className="Re-Print-table">
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      marginBottom: '10px',
                    }}
                  >
                    <div className="action-icons-reprint">
                      <FaDownload
                        onClick={handleDownload}
                        className="icon-download"
                      />
                      <MdEmail onClick={handleEmail} className="icon-email" />
                      <FaWhatsapp
                        onClick={handleWhatsApp}
                        className="icon-whatsapp"
                      />
                    </div>
                    <div
                      style={{
                        display: 'inline-block',
                        marginTop: '8px',
                        padding: '4px 10px',
                        fontSize: '16px',
                        fontWeight: 600,
                        color: '#333',
                        backgroundColor: '#eef2f7',
                        borderRadius: '12px',
                      }}
                    >
                      {dateTimeFormatChange(table2Data?.[0]?.SalesDate)}
                    </div>
                  </div>

                  <Tables
                    columns={columns2}
                    data={table2Data?.[0]?.productDetails}
                    dataSource={table2Data?.[0]?.productDetails}
                  />
                </div>

                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <div
                    style={{
                      maxWidth: '350px',
                      width: '100%',
                      marginTop: '8px',
                      padding: '8px 10px',
                      fontSize: '14px',
                    }}
                  >
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        padding: '6px 0',
                      }}
                    >
                      <span style={{ fontWeight: 500 }}>Total Qty</span>
                      <span style={{ fontWeight: 600 }}>{totalSalesQty}</span>
                    </div>
                    {widthOutTexAmt > 0 && (
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          padding: '6px 0',
                        }}
                      >
                        <span style={{ fontWeight: 500 }}>WithOut Tax Amt</span>
                        <span style={{ fontWeight: 600 }}>
                          ₹ {Number(widthOutTexAmt).toFixed(2)}
                        </span>
                      </div>
                    )}

                    {table2Data?.[0]?.TaxAmount > 0 && (
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          padding: '6px 0',
                        }}
                      >
                        <span style={{ fontWeight: 500 }}>Tax Amt</span>
                        <span style={{ fontWeight: 600 }}>
                          ₹ {table2Data?.[0]?.TaxAmount}
                        </span>
                      </div>
                    )}

                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        borderTop: '1px dashed #ccc',
                        fontSize: '15px',
                        fontWeight: 700,
                      }}
                    >
                      <span>Total Net Amt</span>
                      <span>₹ {table2Data?.[0]?.NetAmount}</span>
                    </div>
                  </div>
                </div>

                {reprintData?.length > 0 &&
                  reprintData?.map((orderDetail, index) => (
                    <div style={{ display: 'none' }}>
                      <PaymentPdfBooking
                        index={index}
                        table2Data={orderDetail}
                        singleData2={orderDetail?.productDetails}
                        ReprintType={isDuplicate}
                        orderId={
                          orderDetail?.OrderId &&
                          extractLastNumberOrderId(
                            orderDetail?.OrderId,
                            orderDetail?.FYStatus
                          )
                        }
                        CreatedDate={orderDetail?.CreatedDate}
                        PaymentStatus={reprintData?.[0]?.OrderPaymentDtl}
                        Preference={SettingDataSelector}
                        printDatas={printDatas}
                      />
                    </div>
                  ))}
              </div>
            </>
          }
          handleCancel={ReprintCancel}
        />

        <Modal
          title="Send Email"
          open={emailModalOpen}
          onCancel={() => setEmailModalOpen(false)}
          footer={null}
        >
          {loading && <div className="loader"></div>}
          <Input
            placeholder="Enter recipient email"
            value={EmailId}
            onChange={(e) => setEmailId(e.target.value)}
            style={{ marginBottom: '16px' }}
          />
          <Button
            type="primary"
            onClick={handleSendEmail}
            disabled={loading}
            block
          >
            {loading ? 'Sending...' : 'Send Email'}
          </Button>

          <PdfProcessingProgress
            progress={processingProgress}
            isProcessing={isProcessing}
          />
        </Modal>
        {!emailModalOpen && (
          <PdfProcessingProgress
            progress={processingProgress}
            isProcessing={isProcessing}
          />
        )}
      </div>
      {reprintData?.length > 0 &&
        reprintData?.map((orderDetail, index) => (
          <div style={{ display: 'none' }}>
            <PaymentPdfBooking
              index={index}
              table2Data={orderDetail}
              singleData2={orderDetail?.productDetails}
              ReprintType={isDuplicate}
              orderId={
                orderDetail?.OrderId &&
                extractLastNumberOrderId(
                  orderDetail?.OrderId,
                  orderDetail?.FYStatus
                )
              }
              CreatedDate={orderDetail?.CreatedDate}
              PaymentStatus={reprintData?.[0]?.OrderPaymentDtl}
              Preference={SettingDataSelector}
              printDatas={printDatas}
            />
          </div>
        ))}
    </>
  );
}

export default BSReprint;
