import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
import {
  dateFormatChange,
  dateFormatChange1,
  extractLastNumber,
  extractLastNumberOrderId,
  getSession,
} from '../../Services/Others';
import {
  ApplicationPreferences,
  getBranchDetail,
} from '../../Features/BrachLogin/BranchLogin';
import PrintStyle1 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle1';
import PrintStyle2 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle2';
import PrintStyle3 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle3';
import PrintStyle4 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle4';
import PrintStyle5 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle5';
import PrintStyle6 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle6';
import PrintStyle7 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle7';
import PrintStyle8 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle8';
import PrintStyle9 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle9';
import PrintStyle10 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle10';
import PrintStyle11 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle11';
import PrintStyle12 from '../BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle12';
import { SelectedPrintTemplate } from '../../Features/ThemeChange/ThemeChange';
import PrintA4Style11 from '../BookingScreen/PrintTemplates/A4/PrintA4Style11';
import PrintA5Style11 from '../BookingScreen/PrintTemplates/A4/PrintStyleA5';
import A4Standard from '../BookingScreen/PrintTemplates/A4/A4Standard';
import TaxInvoice from '../BookingScreen/PrintTemplates/A4/TaxInvoice';
import { settingDataSelector } from '../../Features/PreferenceMaster/PreferenceMaster';
import { PreferenceData } from '../../Features/BookingScreen/BookingData/BookingData';

const PaymentPdfBooking = ({
  index,
  orderId,
  CreatedDate,
  singleData2,
  table2Data,
  PaymentStatus,
  Preference,
  printDatas,
  ReprintType,
}) => {
  const MembershipApplied = table2Data?.OrderOfferDetails?.find(
    (i) => i.TableName === 'MemberShip'
  );
  let PaymentStatusSuccess = PaymentStatus?.filter(
    (ps) => ps.PaymentStatus === 'S'
  );
  const isEditedBill = PaymentStatus?.some(payment => {
    const type = payment?.AdjustmentType?.toLowerCase();
    return (
      (type === 'extra' || type === 'refund') &&
      payment?.BeforeAdjustment != null &&
      payment?.AfterAdjustment != null
    );
  });
  const lastTransaction = PaymentStatus?.find(
    (ps) => ps.PaymentStatus === 'S' && ps?.LastOrderTran === 'Y'
  )
  console.log(singleData2?.filter(data => data?.EditTokenAvailable !== 'N'), "singleData2")
  const ExtraChargeTotal = table2Data?.ExtraChargeDetails?.reduce(
    (accumulator, currentObject) => {
      return accumulator + currentObject.TotalAmt;
    },
    0
  );
  let PrintLogo = Preference?.[0]?.SettingDtlDetails?.filter(
    (i) => i.SettingIdName === 'PrintLogo'
  )?.[0];
  let PrintGreeting = Preference?.[0]?.SettingDtlDetails?.filter(
    (i) => i.SettingIdName === 'PrintGreetings'
  )?.[0];
  let SalesModePref = Preference?.[0]?.SettingDtlDetails?.filter(
    (i) => i.SettingIdName === 'Sales Mode'
  )?.[0];
  const Weightasquantity = Preference?.[0]?.SettingDtlDetails?.some(
    (setting) =>
      setting?.SettingIdName?.toLowerCase() === 'weightasquantity' &&
      setting?.SettingValue === 'Y'
  );
  const dispatch = useDispatch();
  const BranchId = getSession('BranchId');
  const Date1 = dateFormatChange1(table2Data?.SalesDate);
  console.log(Date1, 'CreatedDate', CreatedDate);

  const [BranchLogo, setBranchLogo] = useState(null);
  const [BranchAddress, setBranchAddress] = useState();
  const [BranchCity, setBranchCity] = useState();
  const [BranchZip, setBranchZip] = useState();
  const CashierName = getSession('userName');
  const printerTemplateStyle = useSelector(SelectedPrintTemplate);
  console.log(printerTemplateStyle, "printerTemplateStyle")
  const appPreferences = useSelector(ApplicationPreferences);
  const SettingData = useSelector(PreferenceData);
  const estimatePrintHeader =
    SettingData?.[0]?.SettingDtlDetails?.find(
      (setting) =>
        setting?.SettingIdName?.toLowerCase() === 'estimateprintheader'
    )?.SettingValue === 'Y';
  const bookingTypePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Booking Type'
  )?.PreferenceCatDetails;
  const PackageDetails = table2Data?.PackageDtl;
  const dinePreference = bookingTypePreference?.find(
    (type) =>
      type?.PreferredSubCatName?.toLowerCase() === 'dine in' &&
      type?.PreferredStatus === 'Y'
  );
  const takeAwayPreference = bookingTypePreference?.find(
    (type) =>
      type?.PreferredSubCatName?.toLowerCase() === 'take away' &&
      type?.PreferredStatus === 'Y'
  );
  const commonModulePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Common Module'
  )?.PreferenceCatDetails;
  const sportsAppPreference = commonModulePreference?.find(
    (preference) =>
      preference?.PreferredSubCatName === 'SportsApp' &&
      preference?.PreferredStatus === 'Y'
  );
  const branchLogo = table2Data?.CompLogo;

  // const TotalCal= singleData2?.map((item) =>(item.Price))
  const productsData = table2Data?.productDetails || [];
  const offers = table2Data?.OrderOfferDetails || [];

  let TotalOfferAmount = 0;

  // Calculate SalesWiseOffers total amount
  offers.forEach((offer) => {
    if (offer.TableName === 'SalesWiseOffers') {
      TotalOfferAmount += offer.OfferAmount;
    }
  });
  const hasMappedOffer = offers.some((offer) =>
    ['ItemWiseOffers', 'BundleOffers', 'QuantityWiseOffers'].includes(
      offer.TableName
    )
  );

  if (hasMappedOffer) {
    const productTotal = productsData?.reduce(
      (acc, item) =>
        acc + (item?.Type != 'C' ? item.OfferAmt : item.OfferValue || 0),
      0
    );
    TotalOfferAmount += productTotal;
  } else {
    const Combothere = productsData?.filter((item) => item?.Type == 'C');
    const CombothereTotal = Combothere?.reduce(
      (acc, item) => acc + (item.OfferValue || 0),
      0
    );
    TotalOfferAmount += CombothereTotal;
  }
  // useEffect(() => {
  //   fetchBranchData();
  // }, []);
  // const fetchBranchData = async () => {
  //   const response = await dispatch(
  //     getBranchDetail({ BrId: BranchId })
  //   ).unwrap();
  //   if (response?.data?.statusCode === 1) {
  //     setBranchAddress(response?.data?.data?.[0]?.Address1);
  //     setBranchCity(response?.data?.data?.[0]?.City);
  //     setBranchZip(response?.data?.data?.[0]?.Zip);
  //     setBranchLogo(response?.data?.data?.[0]?.CompLogo);
  //   } else {
  //     setBranchAddress();
  //     setBranchCity();
  //     setBranchZip();
  //     setBranchLogo();
  //   }
  // };

  let Companystate =
    table2Data?.AddressDetails?.[0]?.State?.toLowerCase() || null;
  let Customerstate =
    table2Data?.CustomerDetails?.[0]?.State?.toLowerCase() || null;
  let Samestate =
    Companystate && Customerstate
      ? Companystate == Customerstate
        ? true
        : false
      : true;
  console.log(Samestate, 'Samestate');
  //  const singleData2GST = OrderDetails?.[0]?.TaxDetails?.filter(item => item.TaxIdName === "CGST,SGST")
  let totalQuantityFilter = table2Data?.productDetails?.map(
    (item) => item?.SalesQty || item?.OrderQty
  );
  const totalQuantity = table2Data?.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);
  let OrderDetailGST =
    table2Data?.TaxDetails?.filter(
      (item) => item.TaxIdName?.toLowerCase() === 'cgst,sgst'
    ) || [];
  let OrderDetailIGST =
    table2Data?.TaxDetails?.filter(
      (item) => item.TaxIdName?.toLowerCase() === 'igst'
    ) || [];
  console.log(OrderDetailGST, 'OrderDetailGST');
  // If same state, push GST data into IGST but rename TaxIdName
  if (!Samestate) {
    const converted = OrderDetailGST.map((item) => ({
      ...item,
      TaxIdName: 'igst',
    }));

    OrderDetailIGST = [...OrderDetailIGST, ...converted]; // ✅ works
    OrderDetailGST = []; // ✅ works
  }
  console.log(OrderDetailIGST, 'OrderDetailIGST');
  const OrderDetailVAT = table2Data?.TaxDetails?.filter(
    (item) => item.TaxIdName?.toLowerCase() === 'vat'
  );
  const TakeawayData = table2Data?.productDetails?.filter(
    (item) => item.BookingTypeName?.toLowerCase() === 'takeaway'
  );
  const TakeawayTotalOfferAmt = TakeawayData?.reduce(
    (accumulator, currentValue) => accumulator + currentValue.OfferAmt,
    0
  );

  const DineInData = table2Data?.productDetails?.filter(
    (item) => item.BookingTypeName?.toLowerCase() === 'dine in'
  );
  const DineinTotalOfferAmt = DineInData?.reduce(
    (accumulator, currentValue) => accumulator + currentValue.OfferAmt,
    0
  );
  const TakeawayTotal = TakeawayData?.reduce(
    (accumulator, currentValue) => accumulator + currentValue.TotalAmt,
    0
  );
  const DineInTotal = DineInData?.reduce(
    (accumulator, currentValue) => accumulator + currentValue.TotalAmt,
    0
  );
  const aggregatedPayments = PaymentStatusSuccess?.filter(
    (ps) => ps.PaymentStatus === 'S'
  )?.reduce((acc, paymentdata) => {
    const paymentType = paymentdata?.PaymentTypeName;
    const amount = Number(paymentdata?.Amount);

    if (acc[paymentType]) {
      acc[paymentType] += amount;
    } else {
      acc[paymentType] = amount;
    }

    return acc;
  }, {});
  console.log(aggregatedPayments, 'aggregatedPayments');
  const imageUrlToBase64 = async (url) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    } catch (error) {
      console.error('Error fetching or converting image:', error);
      throw error;
    }
  };

  // Usage in your component
  const [base64Image, setBase64Image] = useState(null);
  const [conversionError, setConversionError] = useState(null);

  // Call the function to convert the image URL to base64
  useEffect(() => {
    async function fetchImage() {
      try {
        const base64 = await imageUrlToBase64(BranchLogo);
        setBase64Image(base64);
      } catch (error) {
        setConversionError(error.message || 'Error converting image');
      }
    }
    if (BranchLogo) {
      fetchImage();
    }
  }, [BranchLogo]);
  const to12Hour = (timeStr) => {
    if (!timeStr) return '';
    let [h, m] = timeStr.split(':');
    h = parseInt(h, 10);
    const suffix = h >= 12 ? 'PM' : 'AM';
    h = h % 12 || 12;
    return `${h}:${m}${suffix}`;
  };

  const getAdjustmentLabel = (type) => {
    switch (type?.toUpperCase()) {
      case 'REFUND':
        return 'Returned Item Amount';
      case 'EXTRA':
        return 'Additional Amount';
      case 'DISCOUNT':
        return 'Discount Applied';
      case 'ROUND_OFF':
        return 'Round Off';
      default:
        return 'Adjustment Amount';
    }
  };

  return (
    <>
      <div className="Reprint-body" id={`RePrint-${index}`}>
        {!estimatePrintHeader && table2Data?.OrderType === 'E' ? (
          ''
        ) : (
          <div className="Re-print-top">
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                gap: '1rem',
              }}
            >
              <div>
                {branchLogo && PrintLogo?.SettingValue === 'Y' ? (
                  <img
                    src={branchLogo}
                    alt="Base64 Image"
                    className="Re-print-Logo"
                    onError={(e) => console.error('Image error:', e)}
                  />
                ) : null}
              </div>
              <div>
                <p
                  className="Re-print-titlesale"
                  style={{
                    fontSize: '16px',
                    padding: 0,
                    fontWeight: 600,
                  }}
                >
                  {table2Data?.BrName}
                </p>
                {table2Data?.AddressDetails?.length > 0 && (
                  <p className="Re-print-Add">
                    {table2Data?.AddressDetails?.[0]?.Address1 &&
                      table2Data?.AddressDetails?.[0]?.Address1}{' '}
                    ,
                    {table2Data?.AddressDetails?.[0]?.City &&
                      table2Data?.AddressDetails?.[0]?.Zip &&
                      table2Data?.AddressDetails?.[0]?.City +
                      '- ' +
                      table2Data?.AddressDetails?.[0]?.Zip}
                  </p>
                )}

                {table2Data?.BrGSTIN && (
                  <p
                    className="Re-print-GST"
                    style={{
                      fontSize: '10px',
                      margin: '5px 0 0 0',
                      padding: 0,
                    }}
                  >
                    GSTIN: {table2Data?.BrGSTIN}
                  </p>
                )}
                {table2Data?.BrMobile && <p style={{ fontSize: '9px', margin: '7px 0 0 0', padding: 0 }}>
                  Mobile:+91 {table2Data?.BrMobile}
                </p>}
              </div>
            </div>
          </div>
        )}
        <div className="Re-print-top">
          {table2Data?.OrderType === 'E' ? (
            <div
              style={{
                display: 'flex',
              }}
            >
              <p
                style={{
                  fontSize: '14px',
                  margin: '2px 0 0 0',
                  padding: 0,
                  fontWeight: 600,
                }}
              >
                Estimate
              </p>
              <p
                style={{
                  display: 'flex',
                  fontSize: '14px',
                  margin: '2px 0 0 0',
                  padding: 0,
                  fontWeight: 600,
                  justifyContent: 'flex-end',
                }}
              >
                {SalesModePref?.SettingValue == 'Y' &&
                  `(${table2Data?.SalesMode ? table2Data?.SalesMode : 'R'})`}
              </p>
            </div>
          ) : (
            <div
              style={{
                display: 'flex',
              }}
            >
              <p
                style={{
                  display: 'flex',
                  fontSize: '14px',
                  margin: '2px 0 0 0',
                  padding: 0,
                  fontWeight: 600,
                  textAlign: 'center',
                }}
              >
                {PaymentStatusSuccess?.length === 1
                  ? PaymentStatusSuccess?.[0]?.PaymentTypeName + ' Bill'
                  : 'Bill'}
              </p>
              <p
                style={{
                  display: 'flex',
                  fontSize: '14px',
                  margin: '2px 0 0 0',
                  padding: 0,
                  fontWeight: 600,
                  justifyContent: 'flex-end',
                }}
              >
                {SalesModePref?.SettingValue == 'Y' &&
                  `(${table2Data?.SalesMode ? table2Data?.SalesMode : 'R'})`}
              </p>
            </div>
          )}
        </div>

        <div className="Re-print-top2">
          <div className="Re-print-bold1">
            Bill No:
            {table2Data?.OrderId &&
              extractLastNumberOrderId(
                table2Data?.OrderId,
                table2Data?.FYStatus
              )}
          </div>
          <div className="Re-print-bold1">Date:{Date1}</div>
        </div>
        {TakeawayData?.length > 0 && (
          <>
            {takeAwayPreference && (
              <div
                style={{
                  margin: '10px 0',
                  padding: '10px 0',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  fontSize: '12px',
                  height: '20px',
                }}
              >
                <p>TakeAway </p>
              </div>
            )}
            <table className="Re-print-Table">
              <thead className="Re-print-th">
                <tr>
                  <th className="Re-print-td">S.No</th>
                  <th className="Re-print-td">Item</th>
                  <th className="Re-print-td">Qty</th>
                  <th className="Re-print-td">Rate</th>
                  {TakeawayTotalOfferAmt > 0 && (
                    <th className="Re-print-td">Dis</th>
                  )}
                  {table2Data?.OrderType !== 'E' && (
                    <th className="Re-print-td">Tax %</th>
                  )}
                  {/* <th className='Re-print-td'>Extra Charges</th> */}
                  <th className="Re-print-td">Amt</th>
                </tr>
              </thead>

              <tbody>
                {TakeawayData?.map((item, index) => {
                  return (
                    <tr className="Re-print-body-Tr">
                      <td className="Re-print-td">{index + 1}</td>

                      <td className="Re-print-body-Product">
                        {item?.ProdName}

                        {PackageDetails?.filter(
                          (pkg) => pkg.ProdId === item.ProdId
                        ).length > 0 ? (
                          <div>
                            {PackageDetails?.filter(
                              (pkg) => pkg.ProdId === item.ProdId
                            )?.map((pkg, index) => (
                              <span key={index} style={{ display: 'block' }}>
                                {pkg.ParcelCount} PCS {pkg.ParcelQty} PACK (
                                {pkg.ParcelType})
                              </span>
                            ))}
                            <span>
                              (
                              {item?.SinglePc === 'Y'
                                ? 'PCS'
                                : item?.Type !== 'C'
                                  ? item?.UomName
                                  : 'COMBO'}
                              ) &nbsp;{' '}
                              {item?.BrandName !== null ? item?.BrandName : ''}
                              &nbsp;
                              {item?.ProductIdentifierDtls?.length > 0
                                ? item?.ProductIdentifierDtls.filter(
                                  (items) =>
                                    items.SerialNumber &&
                                    items.SerialNumber !== ''
                                ).map((a, i) => (
                                  <div key={i}>{a.SerialNumber}</div>
                                ))
                                : ''}
                              {item?.ProductIdentifierDtls?.length > 0
                                ? item?.ProductIdentifierDtls.filter(
                                  (id) => id.IMEI1 !== '' || id.IMEI2 !== ''
                                ).map((id, i) => {
                                  const imei1 = id.IMEI1 || '';
                                  const imei2 = id.IMEI2 || '';
                                  return (
                                    <div key={i}>
                                      {[imei1, imei2]
                                        .filter(Boolean)
                                        .join(',')}
                                    </div>
                                  );
                                })
                                : ''}
                            </span>
                          </div>
                        ) : (
                          <span>
                            ({item?.Size ? item?.Size : '1'}{' '}
                            {item?.SinglePc === 'Y'
                              ? 'PCS'
                              : item?.Type !== 'C'
                                ? item?.UomName
                                : 'COMBO'}
                            ) &nbsp;{' '}
                            {item?.BrandName !== null ? item?.BrandName : ''}
                            &nbsp;
                            {item?.ProductIdentifierDtls?.length > 0
                              ? item?.ProductIdentifierDtls.filter(
                                (items) =>
                                  items.SerialNumber &&
                                  items.SerialNumber !== ''
                              ).map((a, i) => (
                                <div key={i}>{a.SerialNumber}</div>
                              ))
                              : ''}
                            {item?.ProductIdentifierDtls?.length > 0
                              ? item?.ProductIdentifierDtls.filter(
                                (id) => id.IMEI1 !== '' || id.IMEI2 !== ''
                              ).map((id, i) => {
                                const imei1 = id.IMEI1 || '';
                                const imei2 = id.IMEI2 || '';
                                return (
                                  <div key={i}>
                                    {[imei1, imei2].filter(Boolean).join(',')}
                                  </div>
                                );
                              })
                              : ''}
                          </span>
                        )}

                        {sportsAppPreference &&
                          `(${to12Hour(item?.AvailableFrom)}  - ${to12Hour(item?.AvailableTo)})`}
                      </td>
                      <td className="Re-print-body-Rate">{item?.SalesQty}</td>
                      <td className="Re-print-body-Rate">{item?.Rate}</td>
                      {TakeawayTotalOfferAmt > 0 && (
                        <td className="Re-print-body-Rate">
                          {item?.Type != 'C'
                            ? item?.OfferAmt || 0
                            : item?.OfferValue || 0}
                        </td>
                      )}
                      {table2Data?.OrderType !== 'E' ? (
                        <td className="Re-print-td">
                          {item?.ProdTaxPercentage}
                        </td>
                      ) : (
                        ''
                      )}
                      {/* <td className="Re-print-body-Rate">{table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.[0]?.TotalAmt?
                  table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.map(item=>item.ExtraChargeType+':'+item.TotalAmt).join(','):0}</td> */}
                      <td className="Re-print-body-Rate">
                        {/* {table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.[0]?.TotalAmt?
                  table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.map(item=>item.TotalAmt)?.reduce(
                    (accumulator, currentValue) => accumulator + currentValue,
                    0,
                  ) +item?.TotalAmt:item?.TotalAmt} */}
                        {item?.Type != 'C'
                          ? item?.TotalAmt - item?.OfferAmt || 0
                          : item?.TotalAmt - item?.OfferValue || 0}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </>
        )}
        {DineInData?.length > 0 && (
          <>
            <div
              style={{
                margin: 0,
                padding: 0,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                fontSize: '12px',
              }}
            >
              {' '}
              Dine In{' '}
            </div>
            <table className="Re-print-Table">
              <thead className="Re-print-th">
                <tr>
                  <th className="Re-print-td">S.No</th>
                  <th className="Re-print-td">Item</th>
                  <th className="Re-print-td">Qty</th>
                  <th className="Re-print-td">Rate</th>
                  {DineinTotalOfferAmt > 0 && (
                    <th className="Re-print-td">Dis</th>
                  )}
                  {table2Data?.OrderType !== 'E' && (
                    <th className="Re-print-td">Tax %</th>
                  )}
                  {/* <th className='Re-print-td'>Extra Charges</th> */}
                  <th className="Re-print-td">Amt</th>
                </tr>
              </thead>

              <tbody>
                {DineInData?.map((item, index) => {
                  return (
                    <tr className="Re-print-body-Tr">
                      <td className="Re-print-td">{index + 1}</td>
                      <td className="Re-print-body-Product">
                        {item?.ProdName} ({item?.Size ? item?.Size : '1'}{' '}
                        {item?.SinglePc == 'Y'
                          ? 'PCS'
                          : item?.Type != 'C'
                            ? item?.UomName
                            : 'COMBO'}
                        ) &nbsp;{' '}
                        {item?.BrandName !== null ? item?.BrandName : ''}
                      </td>
                      <td className="Re-print-body-Rate">{item?.SalesQty}</td>
                      <td className="Re-print-body-Rate">{item?.Rate}</td>
                      {DineinTotalOfferAmt > 0 && (
                        <td className="Re-print-body-Rate">
                          {item?.Type != 'C'
                            ? item?.OfferAmt || 0
                            : item?.OfferValue || 0}
                        </td>
                      )}
                      {table2Data?.OrderType !== 'E' ? (
                        <td className="Re-print-td">
                          {item?.ProdTaxPercentage}
                        </td>
                      ) : (
                        ''
                      )}
                      {/* <td className="Re-print-body-Rate">{table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.[0]?.TotalAmt?
                  table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.map(item=>item.ExtraChargeType+':'+item.TotalAmt).join(','):0}</td> */}
                      <td className="Re-print-body-Rate">
                        {/* {table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.[0]?.TotalAmt?
                  table2Data?.ExtraChargeDetails?.filter(data=>item?.ProdId==data?.ProdId)?.map(item=>item.TotalAmt)?.reduce(
                    (accumulator, currentValue) => accumulator + currentValue,
                    0,
                  ) +item?.TotalAmt:item?.TotalAmt} */}
                        {item?.Type != 'C'
                          ? item?.TotalAmt - item?.OfferAmt || 0
                          : item?.TotalAmt - item?.OfferValue || 0}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </>
        )}
        <div
          style={{
            border: '0.01px dashed black',
            margin: '10px 0 5px 10px',
            width: '90%',
          }}
        />
        <div
          style={{
            display: 'flex',
            flexWrap: 'wrap',
            gap: '0.5rem',
            justifyContent: 'space-around',
            width: '90%',
            alignItems: 'center',
            margin: '10px 0 5px 10px',
          }}
        >
          <p style={{ margin: 0, padding: 0, fontSize: '12px' }}>
            {' '}
            Items:{totalQuantityFilter?.length}
          </p>
          <p style={{ margin: 0, padding: 0, fontSize: '12px' }}>
            {' '}
            Qty:{totalQuantity}
          </p>
          {ExtraChargeTotal > 0 && (
            <p style={{ margin: 0, padding: 0, fontSize: '12px' }}>
              {' '}
              Extra Charges:{ExtraChargeTotal}
            </p>
          )}
          {(TotalOfferAmount > 0 || table2Data?.OverallDisc > 0) && (
            <p style={{ margin: 0, padding: 0, fontSize: '12px' }}>
              Off :
              {Number(TotalOfferAmount + table2Data?.OverallDisc).toFixed(2)}
            </p>
          )}
          {/* {table2Data?.OverallDisc > 0 && <p style={{ margin: 0, padding: 0, fontSize: "12px" }}>Discount :{Number(table2Data?.OverallDisc).toFixed(2)}</p>} */}
          {/* <p style={{ margin: 0, padding: 0, fontSize: "12px" }}>Amount :{Number(table2Data?.NetAmount).toFixed(2)}</p> */}
        </div>
        {table2Data?.BookingTypeName === 'DineIn,TakeAway' && (
          <div
            style={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: '0.5rem',
              justifyContent: 'space-around',
              width: '90%',
              alignItems: 'center',
              margin: '10px 0 5px 10px',
            }}
          >
            <p style={{ margin: 0, padding: 0, fontSize: '12px' }}>
              {' '}
              Dine-In: &nbsp;{Number(DineInTotal).toFixed(2)}
            </p>
            <p style={{ margin: 0, padding: 0, fontSize: '12px' }}>
              {' '}
              TakeAway: &nbsp;{Number(TakeawayTotal).toFixed(2)}
            </p>
          </div>
        )}
        <div
          style={{
            border: '0.01px dashed black',
            margin: '10px 0 5px 10px',
            width: '90%',
          }}
        />

        {table2Data?.OrderType === 'E' ? (
          ''
        ) : (
          <div>
            {((OrderDetailGST?.length > 0 && OrderDetailGST?.[0]?.TaxAmt > 0) ||
              (OrderDetailIGST?.length > 0 &&
                OrderDetailIGST?.[0]?.TaxAmt > 0) ||
              (OrderDetailVAT?.length > 0 &&
                OrderDetailVAT?.[0]?.TaxAmt > 0)) &&
              table2Data?.NetAmount !== 0 && (
                <>
                  <div>
                    <p
                      style={{
                        margin: 0,
                        padding: 0,
                        fontSize: '12px',
                        textAlign: 'center',
                      }}
                    >
                      --------- GST Breakup Details -----------
                    </p>
                    {OrderDetailGST?.length > 0 &&
                      OrderDetailGST?.[0]?.TaxAmt > 0 && (
                        <table style={{ width: '90%' }}>
                          <tr>
                            <td
                              style={{ fontSize: '10px', textAlign: 'center' }}
                            ></td>
                            <td
                              style={{ fontSize: '10px', textAlign: 'center' }}
                            >
                              Taxable Amount
                            </td>
                            <td
                              style={{ fontSize: '10px', textAlign: 'center' }}
                            >
                              CGST
                            </td>
                            <td
                              style={{ fontSize: '10px', textAlign: 'center' }}
                            >
                              SGST
                            </td>
                            <td
                              style={{ fontSize: '10px', textAlign: 'center' }}
                            >
                              Total Amount
                            </td>
                          </tr>
                          {OrderDetailGST?.map((item) => (
                            <tr>
                              <td
                                style={{ fontSize: '10px', textAlign: 'right' }}
                              >
                                {item?.TaxPercentage} %
                              </td>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                {Number(item.WithOutTaxAmount).toFixed(2)}
                              </td>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                {Number(item.CGST).toFixed(2)}
                              </td>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                {Number(item.SGST).toFixed(2)}
                              </td>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                {Number(item.TotalAmt).toFixed(2)}
                              </td>
                            </tr>
                          ))}
                        </table>
                      )}

                    {OrderDetailIGST?.length > 0 &&
                      OrderDetailIGST?.[0]?.TaxAmt > 0 && (
                        <>
                          <div
                            style={{
                              border: '0.01px dashed black',
                              margin: '10px 0 5px 10px',
                              width: '90%',
                            }}
                          ></div>
                          <table style={{ width: '90%' }}>
                            <tr>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                Taxable Amount
                              </td>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                IGST ({OrderDetailIGST?.[0]?.TaxPercentage}%)
                              </td>

                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                Total Amount
                              </td>
                            </tr>
                            {OrderDetailIGST?.map((item) => (
                              <tr>
                                <td
                                  style={{
                                    fontSize: '10px',
                                    textAlign: 'center',
                                  }}
                                >
                                  {Number(item.WithOutTaxAmount).toFixed(2)}
                                </td>
                                <td
                                  style={{
                                    fontSize: '10px',
                                    textAlign: 'center',
                                  }}
                                >
                                  {Number(item.TaxAmt).toFixed(2)}
                                </td>

                                <td
                                  style={{
                                    fontSize: '10px',
                                    textAlign: 'center',
                                  }}
                                >
                                  {Number(item.TotalAmt).toFixed(2)}
                                </td>
                              </tr>
                            ))}
                          </table>
                        </>
                      )}
                    {OrderDetailVAT?.length > 0 &&
                      OrderDetailVAT?.[0]?.TaxAmt > 0 && (
                        <>
                          <div
                            style={{
                              border: '0.01px dashed black',
                              margin: '10px 0 5px 10px',
                              width: '90%',
                            }}
                          ></div>
                          <table style={{ width: '90%' }}>
                            <tr>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                Taxable Amount
                              </td>
                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                VAT ({OrderDetailVAT?.[0]?.TaxPercentage}%)
                              </td>

                              <td
                                style={{
                                  fontSize: '10px',
                                  textAlign: 'center',
                                }}
                              >
                                Total Amount
                              </td>
                            </tr>
                            {OrderDetailVAT?.map((item) => (
                              <tr>
                                <td
                                  style={{
                                    fontSize: '10px',
                                    textAlign: 'center',
                                  }}
                                >
                                  {Number(item.WithOutTaxAmount).toFixed(2)}
                                </td>
                                <td
                                  style={{
                                    fontSize: '10px',
                                    textAlign: 'center',
                                  }}
                                >
                                  {Number(item.TaxAmt).toFixed(2)}
                                </td>

                                <td
                                  style={{
                                    fontSize: '10px',
                                    textAlign: 'center',
                                  }}
                                >
                                  {Number(item.TotalAmt).toFixed(2)}
                                </td>
                              </tr>
                            ))}
                          </table>
                        </>
                      )}
                  </div>

                  <div
                    style={{
                      border: '0.01px dashed black',
                      margin: '10px 0 5px 10px',
                      width: '90%',
                    }}
                  ></div>
                </>
              )}
          </div>
        )}

        <div
          style={{
            display: 'flex',
            justifyContent: 'space-evenly',
            marginTop: '5px',
          }}
        >
          <p
            style={{
              marginTop: '5px',
              padding: 0,
              fontSize: '17px',
              fontWeight: '600',
            }}
          >
            {PaymentStatusSuccess?.length === 1
              ? PaymentStatusSuccess?.[0]?.PaymentTypeName
              : 'Split'}{' '}
            &nbsp;Payment : &nbsp;{Number(table2Data?.NetAmount).toFixed(2)}
            /-{' '}
          </p>
        </div>

        {table2Data?.CustomerDetails?.length > 0 && (
          <div
            style={{
              border: '0.01px dashed black',
              margin: '10px 0 5px 10px',
              width: '90%',
            }}
          ></div>
        )}
        {table2Data?.CustomerDetails?.length > 0 && (
          <div
            style={{
              fontSize: '12px',
              fontWeight: '600',
              lineHeight: '18px',
              marginLeft: '10px',
              padding: 0,
            }}
          >
            {(() => {
              const c = table2Data.CustomerDetails[0];
              const items = [];

              if (PaymentStatusSuccess?.[0]?.PaymentTypeName === 'Credit') {
                if (c.OldCreditBal !== 0) {
                  items.push({
                    label:
                      c.OldCreditBal > 0 ? 'Advance Amount' : 'Opening Balance',
                    value: Math.abs(c.OldCreditBal).toFixed(2),
                  });
                }
              }

              if (c.CurrentCreditBal !== 0) {
                items.push({
                  label:
                    c.CurrentCreditBal > 0
                      ? 'Current Advance Amount'
                      : 'Current Balance Amount',
                  value: Math.abs(c.CurrentCreditBal).toFixed(2),
                });
              }

              return items.map((i, idx) => (
                <p
                  key={idx}
                  style={{
                    width: '90%',
                    display: 'grid',
                    gridTemplateColumns: '4fr  1fr 1fr',
                    // gridTemplateColumns: "auto auto auto",
                    margin: 0,
                    padding: 0,
                  }}
                >
                  <span style={{ textAlign: 'left' }}>{i.label}</span>
                  <span style={{ textAlign: 'center' }}>:</span>
                  <span style={{ textAlign: 'right' }}>{i.value}</span>
                </p>
              ));
            })()}
          </div>
        )}

        {table2Data?.CustomerDetails?.length > 0 && (
          <div
            style={{
              border: '0.01px dashed black',
              margin: '10px 0 5px 10px',
              width: '90%',
            }}
          ></div>
        )}

        {(PaymentStatusSuccess?.length > 1 && !isEditedBill) && (
          <>
            {/* <p>Split Payment:</p> */}
            {Object.keys(aggregatedPayments)?.map((paymentType) => (
              <div
                key={paymentType}
                style={{ margin: 0, padding: 0, fontSize: '12px' }}
              >
                {paymentType}: {aggregatedPayments[paymentType].toFixed(2)}
              </div>
            ))}
          </>
        )}
        {isEditedBill && lastTransaction && (
          <div style={{
            width: '90%', marginTop: '2px',
            marginLeft: '10px',
            paddingTop: '2px', display: 'flex', justifyContent: 'center', alignItems: 'center',
            flexDirection: 'column', borderTop: '1px dashed #ccc'
          }}>
            <div
              style={{
                fontSize: '12px',
                width: '70%'
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: '#333' }}>Bill Gross Amount</span>
                <strong>{(lastTransaction?.BeforeAdjustment || 0).toFixed(2)}</strong>
              </div>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  marginTop: '4px',
                  fontWeight: 600,
                  color:
                    lastTransaction?.AdjustmentType === 'REFUND'
                      ? '#d32f2f'
                      : '#2e7d32',
                }}
              >
                <span>{'Adjustment Amount'}</span>
                <span>
                  {lastTransaction?.AdjustmentType === 'REFUND' ? '-' : '+'}
                  {(lastTransaction?.Amount || 0).toFixed(2)}
                </span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: '#333' }}>Net Bill Amount</span>
                <strong>{(lastTransaction?.AfterAdjustment || 0).toFixed(2)}</strong>
              </div>
            </div>
          </div>
        )}
        {table2Data?.CustSuppName && (
          <div>
            <p
              style={{
                marginLeft: '10px',
                padding: 0,
                fontSize: '12px',
                fontWeight: '600',
              }}
            >
              Customer: {table2Data?.CustSuppName}
            </p>
          </div>
        )}
        {CashierName && (
          <div>
            <p
              style={{
                marginLeft: '10px',
                padding: 0,
                fontSize: '12px',
                fontWeight: '600',
              }}
            >
              Cashier Name: {CashierName}
            </p>
          </div>
        )}

        {table2Data?.BookingTypeName === 'Dine In' &&
          table2Data?.SalesTableLinkDetails?.[0]?.WaiterName && (
            <div>
              <p
                style={{
                  marginLeft: '10px',
                  padding: 0,
                  fontSize: '12px',
                  fontWeight: '600',
                }}
              >
                Captain Name:{' '}
                {table2Data?.SalesTableLinkDetails?.[0]?.WaiterName}
              </p>
            </div>
          )}
        <h6 style={{ textAlign: 'center', marginTop: '5px' }}>
          YOUR ORDER NO:{' '}
          {table2Data?.SalesId && extractLastNumber(table2Data?.SalesId)}
        </h6>
        {PrintGreeting?.SettingValue === 'Y' && (
          <p className="Re-print-bold2">Thank You Visit Again</p>
        )}
      </div>
      {table2Data && (
        <div style={{ display: 'none' }}>
          {printerTemplateStyle === 'Style 1' && (
            <PrintStyle1
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 2' && (
            <PrintStyle2
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              // base64Image={base64Image}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 3' && (
            <PrintStyle3
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 4' && (
            <PrintStyle4
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 5' && (
            <PrintStyle5
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 6' && (
            <PrintStyle6
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 7' && (
            <PrintStyle7
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 8' && (
            <PrintStyle8
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 9' && (
            <PrintStyle9
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 10' && (
            <PrintStyle10
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 11' && (
            <PrintStyle11
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'Style 12' && (
            <PrintStyle12
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'A4' && (
            <PrintA4Style11
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'A5' && (
            <PrintA5Style11
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'A4Standard' && (
            <A4Standard
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              sportsAppPreference={sportsAppPreference}
              MembershipApplied={MembershipApplied}
            />
          )}
          {printerTemplateStyle === 'TaxInvoice' && (
            <TaxInvoice
              index={index}
              ExtraChargeTotal={ExtraChargeTotal}
              Date1={Date1}
              base64Image={branchLogo}
              BranchAddress={BranchAddress}
              BranchCity={BranchCity}
              BranchZip={BranchZip}
              CashierName={CashierName}
              totalQuantity={totalQuantity}
              OrderDetailGST={OrderDetailGST}
              OrderDetailIGST={OrderDetailIGST}
              OrderDetailVAT={OrderDetailVAT}
              table2Data={table2Data}
              totalQuantityFilter={totalQuantityFilter}
              PaymentStatus={PaymentStatus}
              PrintLogo={PrintLogo}
              PrintGreeting={PrintGreeting}
              printDatas={printDatas}
              SalesModePref={SalesModePref}
              ReprintType={ReprintType}
            />
          )}
        </div>
      )}

      {/* Token print */}
      {Object.entries(
        singleData2?.filter(data => data?.EditTokenAvailable !== 'N')?.reduce((acc, item, idx) => {
          if (item.TokenAvailable === 'Y') {
            if (!item.CounterName) {
              // For null or empty CounterName, print each item individually
              acc[`individual-${idx}-${item.ProdId}`] = [item];
            } else {
              if (!acc[item.CounterName]) {
                acc[item.CounterName] = [];
              }
              acc[item.CounterName].push(item); // Group by CounterName
            }
          }
          return acc;
        }, {})
      ).map(([counterName, items], index) => (
        <div style={{ display: 'none' }} key={index}>
          <div
            className="Reprint-body"
            id={`TakeawayToken${index}-${items?.[0]?.ProdId}-${counterName}`}
          >
            <div className="Re-print-top">
              <p className="Re-print-title">{items[0]?.BrName}</p>
              <p className="Re-print-title">Token</p>
            </div>
            <div className="Re-print-top2">
              <p className="Re-print-bold">Bill No:&nbsp;{orderId}</p>
              <p className="Re-print-bold">{Date1}</p>
            </div>
            <table className="Re-print-Table">
              <thead className="Re-print-th">
                <tr>
                  <th className="Re-print-td">S.No</th>
                  <th className="Re-print-td">Item</th>
                  <th className="Re-print-td">Qty</th>
                  <th className="Re-print-td">Rate</th>
                  <th className="Re-print-td">Price</th>
                </tr>
              </thead>
              <tbody>
                {items.map((item, idx) => (
                  <tr className="Re-print-body-Tr" key={idx}>
                    <td className="Re-print-td">{idx + 1}</td>
                    <td className="Re-print-body-Product">{item.ProdName}</td>
                    <td className="Re-print-body-Rate">{item?.EditTokenAvailable === 'Y' ? item?.EditTokenQty : item.SalesQty}</td>
                    <td className="Re-print-body-Rate">{item.Rate}</td>
                    <td className="Re-print-body-Rate">{((item?.EditTokenAvailable === 'Y' ? item?.EditTokenQty : item.SalesQty) * item.Rate) - ((item?.EditTokenAvailable === 'Y' ? (item?.OfferAmt / item?.EditTokenQty) : item?.OfferAmt))}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ))}
    </>
  );
};

export default PaymentPdfBooking;
