import React from 'react';
import { useSelector } from 'react-redux';
import { GlobalPritdummyData } from '../../../../Features/ThemeChange/ThemeChange';
import { isMobile } from 'react-device-detect';
import { extractLastNumberOrderId } from '../../../../Services/Others';
import moment from 'moment';
import { settingDataSelector } from '../../../../Features/PreferenceMaster/PreferenceMaster';
import { PreferenceData } from '../../../../Features/BookingScreen/BookingData/BookingData';

const TaxInvoice = ({
  index,
  table2Data,
  Date1,
  CashierName,
  totalQuantity,
  OrderDetailGST,
  OrderDetailIGST,
  OrderDetailVAT,
  PaymentStatus,
  ReprintType,
  printDatas,
}) => {
  const GlobaldummyData = useSelector(GlobalPritdummyData);
  const SettingData = useSelector(PreferenceData);
  const estimatePrintHeader =
    SettingData?.[0]?.SettingDtlDetails?.find(
      (setting) =>
        setting?.SettingIdName?.toLowerCase() === 'estimateprintheader'
    )?.SettingValue === 'Y';
  let BillName = printDatas?.PrintHdrName;
  let companyColour = printDatas?.PrintHdrColor ?? '#00000';
  // Function to convert number to words
  const numberToWords = (num) => {
    const a = [
      '',
      'One',
      'Two',
      'Three',
      'Four',
      'Five',
      'Six',
      'Seven',
      'Eight',
      'Nine',
      'Ten',
      'Eleven',
      'Twelve',
      'Thirteen',
      'Fourteen',
      'Fifteen',
      'Sixteen',
      'Seventeen',
      'Eighteen',
      'Nineteen',
    ];
    const b = [
      '',
      '',
      'Twenty',
      'Thirty',
      'Forty',
      'Fifty',
      'Sixty',
      'Seventy',
      'Eighty',
      'Ninety',
    ];

    if (num === 0) return 'Zero';
    if (num < 20) return a[num];
    if (num < 100)
      return b[Math.floor(num / 10)] + (num % 10 ? ' ' + a[num % 10] : '');
    if (num < 1000)
      return (
        a[Math.floor(num / 100)] +
        ' Hundred' +
        (num % 100 ? ' and ' + numberToWords(num % 100) : '')
      );
    if (num < 100000)
      return (
        numberToWords(Math.floor(num / 1000)) +
        ' Thousand' +
        (num % 1000 ? ' ' + numberToWords(num % 1000) : '')
      );
    if (num < 10000000)
      return (
        numberToWords(Math.floor(num / 100000)) +
        ' Lakh' +
        (num % 100000 ? ' ' + numberToWords(num % 100000) : '')
      );
    if (num < 1000000000)
      return (
        numberToWords(Math.floor(num / 10000000)) +
        ' Crore' +
        (num % 10000000 ? ' ' + numberToWords(num % 10000000) : '')
      );

    return 'Number too large';
  };
  // Helper to format date as 7-Aug-2025
  function formatDateToDDMMMYYYY(dateStr) {
    console.log(dateStr, 'dateStrdateStr');
    if (!dateStr) return '';
    const date = new Date(dateStr);
    if (isNaN(date)) return dateStr; // fallback if invalid date
    const day = date.getDate();
    const month = date.toLocaleString('en-US', { month: 'short' });
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
  }
  function removeTimeFromDate(dateStr) {
    if (!dateStr) return '';
    // Split on ":" — first part will be "DD-MM-YYYY"
    const parts = dateStr.split(':');
    return parts[0] || dateStr;
  }
  console.log(
    Date1,
    moment(Date1).format('DD-MMM-YYYY'),
    'datadatadatadatadatadata'
  );
  // Extract data from table2Data - mapping from A4Standard structure
  const invoiceData = {
    // Company Details - mapped from A4Standard
    companyName: table2Data?.CompName || table2Data?.BrName || '',
    companyspecname: table2Data?.AppSpecificName || '',
    companyAddress: {
      address1: table2Data?.AddressDetails?.[0]?.Address1 || '',
      address2: table2Data?.AddressDetails?.[0]?.Address2 || '',
      city: table2Data?.AddressDetails?.[0]?.City || '',
      state: table2Data?.AddressDetails?.[0]?.State || '',
      zip: table2Data?.AddressDetails?.[0]?.Zip || '',
    },
    companyGSTIN: table2Data?.CompGSTIN || table2Data?.BrGSTIN || '',
    companyEmail: table2Data?.CompanyEmail || table2Data?.BrEmail || '',
    companyMobile: table2Data?.BrMobile || '',
    companyMobile2: table2Data?.BrMobile2 || '',

    // Invoice Details - mapped from A4Standard
    invoiceNo: table2Data?.OrderId
      ? extractLastNumberOrderId(table2Data?.OrderId, table2Data?.FYStatus)
      : '',
    invoiceDate: moment(Date1).format('DD-MMM-YYYY'),

    // Customer Details - mapped from A4Standard CustomerDetails array
    customerName:
      table2Data?.CustomerDetails?.[0]?.CustSuppName ||
      table2Data?.CustSuppName ||
      '',
    customerMobile:
      table2Data?.CustomerDetails?.[0]?.MobileNo || table2Data?.MobileNo || '',
    customerGSTIN:
      table2Data?.CustomerDetails?.[0]?.CustGSTNo ||
      table2Data?.CustGSTIN ||
      '',
    customerAddress: {
      address1: table2Data?.CustomerDetails?.[0]?.Address1 || '',
      address2: table2Data?.CustomerDetails?.[0]?.Address2 || '',
      state: table2Data?.CustomerDetails?.[0]?.State || '',
    },

    // Product Details - mapped from A4Standard productDetails
    productDetails: table2Data?.productDetails || [],

    // Totals - mapped from A4Standard
    totalAmount: Number(table2Data?.BillAmount || table2Data?.TotalAmt),
    taxAmount: Number(OrderDetailGST),
    grandTotal: Number(table2Data?.NetAmount || table2Data?.GrandTotal),
    totalBillAmount: Number(
      table2Data?.BillAmount || table2Data?.NetAmount || 0
    ),
    // Bank Details - mapped from A4Standard
    bankDetails: table2Data?.BankDetails?.[0] || null,
  };

  let PageSize = printDatas?.PageSize;

  const TakeawayData = table2Data?.productDetails?.filter(
    (item) => item.BookingTypeName?.toLowerCase() === 'takeaway'
  );
  const DineInData = table2Data?.productDetails?.filter(
    (item) => item.BookingTypeName?.toLowerCase() === 'dine in'
  );
  let PaymentStatusSuccess = PaymentStatus?.filter(
    (ps) => ps.PaymentStatus === 'S'
  );
  // Calculate GST/IGST totals
  const cgstTotal =
    OrderDetailGST && OrderDetailGST.length > 0
      ? Number(
          OrderDetailGST?.reduce((sum, item) => sum + (item.CGST || 0), 0)
        )?.toFixed(2)
      : 0;
  const sgstTotal =
    OrderDetailGST && OrderDetailGST.length > 0
      ? Number(
          OrderDetailGST?.reduce((sum, item) => sum + (item.SGST || 0), 0)
        )?.toFixed(2)
      : 0;
  const igstTotal =
    OrderDetailIGST && OrderDetailIGST.length > 0
      ? Number(
          OrderDetailIGST?.reduce((sum, item) => sum + (item.TaxAmt || 0), 0)
        )?.toFixed(2)
      : 0;

  // Calculate round off value
  const roundOffValue =
    Number(invoiceData.grandTotal) -
    (Number(invoiceData.totalBillAmount) +
      Number(cgstTotal) +
      Number(sgstTotal) +
      Number(igstTotal));
  const roundOffEstimateValue = Number(invoiceData.grandTotal);
  console.log(
    Number(invoiceData.totalBillAmount),
    cgstTotal,
    sgstTotal,
    igstTotal,
    'roundoff vaules'
  );
  function RoundOffFun(amount) {
    const roundedAmount = Math.round(amount);
    const roundOffValue = parseFloat((roundedAmount - amount).toFixed(2));
    // const symbol = roundOffValue > 0 ? '+' : ''; // Add "+" symbol for positive values ${symbol}
    console.log(
      'Rounded Amount:',
      roundedAmount,
      'Round Off Value:',
      roundOffValue
    );
    return `${roundOffValue.toFixed(2)}`;
  }

  console.log('=== DEBUG INFO ===');
  console.log('table2Data?.productDetails:', table2Data?.productDetails);
  console.log('GlobaldummyData:', GlobaldummyData);
  console.log('TakeawayData:', TakeawayData);
  console.log('DineInData:', DineInData);
  console.log('PageSize:', PageSize);

  // Allow up to 10 items per page
  const chunkSize =
    table2Data?.OrderType !== 'E'
      ? isMobile
        ? 7
        : PageSize == 'A5'
          ? 9
          : 8
      : isMobile
        ? 10
        : PageSize == 'A5'
          ? 12
          : 11;
  let dataSource = [];

  // Simplified data source logic - always use all product details
  dataSource = table2Data?.productDetails || [];

  // Ensure dataSource is always an array
  if (!Array.isArray(dataSource)) {
    dataSource = [];
  }

  console.log(
    'Final DataSource:',
    dataSource,
    'Length:',
    dataSource.length,
    'ChunkSize:',
    chunkSize
  );

  const paginatedChunks = [];

  // Always create at least one chunk, even if empty
  if (dataSource.length === 0) {
    paginatedChunks.push([]);
  } else {
    // Split data into chunks
    for (let i = 0; i < dataSource.length; i += chunkSize) {
      const chunk = dataSource.slice(i, i + chunkSize);
      paginatedChunks.push(chunk);
    }
  }

  const lastChunkRows =
    paginatedChunks.length > 0
      ? paginatedChunks[paginatedChunks.length - 1].length
      : 0;
  // If last page has more than 6 items, move footer to new page
  const shouldFooterBeOnNewPage = lastChunkRows === chunkSize;

  // If footer should be on new page, add an empty chunk for footer-only page
  if (shouldFooterBeOnNewPage && paginatedChunks.length > 0) {
    paginatedChunks.push([]); // Empty chunk for footer-only page
  }
  console.log(
    'Paginated Chunks:',
    paginatedChunks.length,
    'Chunks:',
    paginatedChunks.map((chunk, i) => `Chunk ${i}: ${chunk.length} items`)
  );
  console.log('Should footer be on new page:', shouldFooterBeOnNewPage);
  return (
    <div
      id={`TaxInvoice-${index}`}
      style={{
        fontFamily: 'Arial, sans-serif',
        fontSize: '12px',
        lineHeight: '1.2',
        color: '#000',
        maxWidth: '210mm',
        margin: '0 auto',
        padding: '10mm',
        backgroundColor: 'white',
      }}
    >
      {paginatedChunks?.map((dataChunk, chunkIndex) => (
        <div
          key={chunkIndex}
          className={
            isMobile
              ? `invoice-wrapper container pdf-page`
              : `invoice-wrapper container print-chunk${chunkIndex > 0 ? ' print-page-break' : ''}`
          }
          style={{
            display: 'flex',
            flexDirection: 'column',
            // justifyContent: ((chunkIndex === paginatedChunks.length - 1) && (!shouldFooterBeOnNewPage)) ? "space-between" : "",
            height: isMobile ? '275mm' : PageSize == 'A5' ? '130mm' : '245mm',
            marginBottom: '0',
            pageBreakAfter:
              chunkIndex < paginatedChunks.length - 1 ? 'always' : 'auto',
          }}
        >
          {renderInvoiceContent(dataChunk, chunkIndex)}
        </div>
      ))}
    </div>
  );

  function renderInvoiceContent(dataChunk, chunkIndex) {
    console.log(
      `Rendering page ${chunkIndex + 1}, chunk has ${dataChunk.length} items:`,
      dataChunk
    );

    const isFirstPage = chunkIndex === 0;
    const isLastPage = chunkIndex === paginatedChunks.length - 1;
    const isFooterOnlyPage =
      isLastPage && dataChunk.length === 0 && shouldFooterBeOnNewPage;
    const isLastDataChunk =
      chunkIndex ===
      paginatedChunks.length - 1 - (shouldFooterBeOnNewPage ? 1 : 0);
    const shouldShowTaxDetails = isLastDataChunk && dataChunk.length > 0;
    console.log(
      `Page ${chunkIndex + 1}: isFirstPage=${isFirstPage}, isLastPage=${isLastPage}, isFooterOnlyPage=${isFooterOnlyPage},datachunkslength=${dataChunk.length}`
    );

    return (
      <>
        {/* Header - Only on first page */}
        {isFirstPage && (
          <>
            <div
              style={{
                textAlign: 'center',
                marginBottom: '10px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <div></div>
              <h2 style={{ margin: '0', fontSize: '20px', fontWeight: '700' }}>
                {table2Data?.OrderType === 'E'
                  ? 'Estimate'
                  : BillName
                    ? BillName
                    : 'TAX INVOICE'}
              </h2>
              <div>
                <div style={{ fontSize: '10px', marginTop: '2px' }}>
                  {ReprintType == 'Duplicate'
                    ? '(DUPLICATE FOR RECIPIENT)'
                    : '(ORIGINAL FOR RECIPIENT)'}
                </div>
              </div>
            </div>
          </>
        )}

        {/* Main Container - Always show */}
        <div style={{ border: '1px solid #000' }}>
          {/* Top Section - Company and Invoice Details - Only on first page */}
          {isFirstPage && (
            <div style={{ display: 'flex', width: '100%' }}>
              {/* Left - Company Details */}
              <div
                style={{
                  width: '50%',
                  borderRight: '1px solid #000',
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                {!estimatePrintHeader && table2Data?.OrderType === 'E' ? (
                  ''
                ) : (
                  <div
                    style={{
                      // flex: '1',
                      padding: '10px',

                      fontSize: '11px',
                      textAlign: 'left',
                    }}
                  >
                    <div
                      style={{
                        fontWeight: '700',
                        fontSize: '15px',
                        color: companyColour,
                      }}
                    >
                      {invoiceData.companyName}
                    </div>
                    <div style={{ fontSize: '12px' }}>
                      {invoiceData.companyspecname}
                    </div>
                    <div>{invoiceData.companyAddress.address1}</div>
                    <div>{invoiceData.companyAddress.address2}</div>
                    <div>
                      {invoiceData.companyAddress.city}{' '}
                      {invoiceData.companyAddress.zip
                        ? ` - ${invoiceData.companyAddress.zip}`
                        : ''}
                    </div>
                    <div>{invoiceData.companyAddress.state}</div>
                    {invoiceData.companyGSTIN && (
                      <div style={{ fontWeight: '700', fontSize: '12px' }}>
                        GSTIN/UIN: {invoiceData.companyGSTIN}
                      </div>
                    )}
                    {/* <div>State Name: Tamil Nadu, Code: 33</div> */}
                    {invoiceData.companyEmail && (
                      <div>E-Mail: {invoiceData.companyEmail}</div>
                    )}
                    {invoiceData.companyMobile && (
                      <div>
                        Mobile: +91 {invoiceData.companyMobile}
                        {invoiceData.companyMobile2
                          ? `, ${invoiceData.companyMobile2}`
                          : ''}
                      </div>
                    )}
                  </div>
                )}
                {/* Buyer Details */}
                <div
                  style={{
                    padding: '10px',
                    borderTop: '1px solid #000',

                    fontSize: '11px',
                    minHeight: '60px',
                    textAlign: 'left',
                  }}
                >
                  <div style={{ marginBottom: '5px' }}>Buyer (Bill to)</div>
                  <div style={{ fontWeight: '700', fontSize: '15px' }}>
                    {invoiceData.customerName}
                  </div>
                  {invoiceData.customerAddress.address1 && (
                    <div>{invoiceData.customerAddress.address1}</div>
                  )}
                  {invoiceData.customerAddress.address2 && (
                    <div>{invoiceData.customerAddress.address2}</div>
                  )}
                  {invoiceData.customerMobile && (
                    <div>Mobile: {invoiceData.customerMobile}</div>
                  )}
                  {(invoiceData.customerGSTIN && table2Data?.OrderType !== 'E') && (
                    <div style={{ fontWeight: '700', fontSize: '15px' }}>
                      GSTIN/UIN: {invoiceData.customerGSTIN}
                    </div>
                  )}
                  {invoiceData.customerAddress.state && (
                    <div>State Name: {invoiceData.customerAddress.state}</div>
                  )}
                </div>
              </div>

              {/* Right - Invoice Details */}
              <div style={{ flex: '1', fontSize: '10px' }}>
                {/* Invoice No and Date */}
                <div
                  style={{ display: 'flex', borderBottom: '1px solid #000' }}
                >
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      borderRight: '1px solid #000',
                      textAlign: 'left',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Invoice No.</div>
                    <div style={{ fontWeight: '700', fontSize: '15px' }}>
                      {invoiceData.invoiceNo}
                    </div>
                  </div>
                  <div
                    style={{ flex: '1', paddingLeft: '3px', textAlign: 'left' }}
                  >
                    <div>Dated</div>
                    <div style={{ fontWeight: '700', fontSize: '15px' }}>
                      {invoiceData.invoiceDate}
                    </div>
                  </div>
                </div>

                {/* Delivery Note and Payment Terms */}
                <div
                  style={{
                    display: 'flex',
                    borderBottom: '1px solid #000',
                    textAlign: 'left',
                    minHeight: '25px',
                  }}
                >
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      borderRight: '1px solid #000',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Delivery Note</div>
                    <div></div>
                  </div>
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      textAlign: 'left',
                      minHeight: '25px',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Mode/Terms of Payment</div>
                    <div></div>
                  </div>
                </div>

                {/* Reference and Other References */}
                <div
                  style={{
                    display: 'flex',
                    borderBottom: '1px solid #000',
                    textAlign: 'left',
                    minHeight: '25px',
                  }}
                >
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      borderRight: '1px solid #000',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Reference No. & Date</div>
                    <div></div>
                  </div>
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      textAlign: 'left',
                      minHeight: '25px',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Other References</div>
                    <div></div>
                  </div>
                </div>

                {/* Buyer's Order */}
                <div
                  style={{
                    display: 'flex',
                    borderBottom: '1px solid #000',
                    textAlign: 'left',
                    minHeight: '25px',
                  }}
                >
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      borderRight: '1px solid #000',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Buyer's Order No.</div>
                    <div></div>
                  </div>
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      textAlign: 'left',
                      minHeight: '25px',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Dated</div>
                    <div></div>
                  </div>
                </div>

                {/* Dispatch Details */}
                <div
                  style={{ display: 'flex', borderBottom: '1px solid #000' }}
                >
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      borderRight: '1px solid #000',
                      textAlign: 'left',
                      minHeight: '25px',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Dispatch Doc No.</div>
                    <div></div>
                  </div>
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      textAlign: 'left',
                      minHeight: '25px',
                    }}
                  >
                    <div style={{ fontSize: '9px' }}>Delivery Note Date</div>
                    <div></div>
                  </div>
                </div>

                {/* Dispatched through and Destination */}
                <div
                  style={{
                    display: 'flex',
                    borderBottom: '1px solid #000',
                    minHeight: '25px',
                  }}
                >
                  <div
                    style={{ flex: '1', paddingLeft: '3px', textAlign: 'left' }}
                  >
                    <div style={{ fontSize: '9px' }}>Dispatched through</div>
                    <div></div>
                  </div>
                  <div
                    style={{
                      flex: '1',
                      paddingLeft: '3px',
                      borderLeft: '1px solid #000',
                      minHeight: '25px',
                    }}
                  >
                    <div style={{ fontSize: '9px', textAlign: 'left' }}>
                      Destination
                    </div>
                    <div></div>
                  </div>
                </div>

                {/* Terms of Delivery */}
                <div
                  style={{
                    padding: '8px 6px',
                    textAlign: 'left',
                    minHeight: '35px',
                  }}
                >
                  <div style={{ fontSize: '9px' }}>Terms of Delivery</div>
                  <div></div>
                </div>
              </div>
            </div>
          )}

          {/* Continuation header for non-first pages */}
          {!isFirstPage && (
            <div
              style={{
                textAlign: 'center',
                marginBottom: '10px',
                padding: '5px',
              }}
            >
              <h3 style={{ margin: '0', fontSize: '16px', fontWeight: '700' }}>
                {isFooterOnlyPage ? 'Tax Invoice' : 'Tax Invoice '}
              </h3>
              <div style={{ fontSize: '10px' }}>
                Invoice No: {invoiceData.invoiceNo}
              </div>
            </div>
          )}

          {/* Items Table - Show only if there are items or not a footer-only page */}
          {(dataChunk.length > 0 || !isFooterOnlyPage) && (
            <div
              style={{
                // borderBottom: isLastPage ? '1px solid #000' : 'none',
                minHeight: table2Data?.OrderType !== 'E' ? '250px' : '350px',
              }}
            >
              {/* Table Header */}
              <div
                style={{
                  display: 'grid',
                  gridTemplateColumns: '5% 40% 12% 11% 16% 8% 16%',
                  fontSize: '10px',
                  // borderRight: '1px solid #000',
                  borderBottom: '1px solid #000',
                  borderTop: '1px solid #000',
                }}
              >
                <div
                  style={{
                    padding: '8px 4px',
                    borderRight: '1px solid #000',
                    textAlign: 'center',
                  }}
                >
                  SL.No
                </div>
                <div
                  style={{
                    padding: '8px 4px',
                    borderRight: '1px solid #000',
                    textAlign: 'center',
                  }}
                >
                  Description of Goods
                </div>
                <div
                  style={{
                    padding: '8px 4px',
                    borderRight: '1px solid #000',
                    textAlign: 'center',
                  }}
                >
                  HSN/SAC
                </div>
                <div
                  style={{
                    padding: '8px 4px',
                    borderRight: '1px solid #000',
                    textAlign: 'center',
                  }}
                >
                  Quantity
                </div>
                <div
                  style={{
                    padding: '8px 4px',
                    borderRight: '1px solid #000',
                    textAlign: 'center',
                  }}
                >
                  Rate
                </div>
                {/* <div style={{ padding: '8px 4px', borderRight: '1px solid #000', textAlign: 'center' }}>per</div> */}
                <div style={{ padding: '8px 4px', textAlign: 'center' }}>
                  Amount
                </div>
              </div>

              {/* Table Rows - Dynamic data from dataChunk */}
              {dataChunk && dataChunk.length > 0 ? (
                <>
                  {dataChunk?.map((item, index) => (
                    <div
                      key={index}
                      style={{
                        display: 'grid',
                        gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                        // borderRight: '1px solid #000',
                      }}
                    >
                      <div
                        style={{
                          padding: '4px 4px',
                          borderRight: '1px solid #000',
                          textAlign: 'center',
                          fontWeight: '700',
                        }}
                      >
                        {chunkIndex * chunkSize + index + 1}
                      </div>
                      <div
                        style={{
                          padding: '4px 4px',
                          borderRight: '1px solid #000',
                        }}
                      >
                        <div
                          style={{
                            fontWeight: '700',
                            marginBottom: '2px',
                            textAlign: 'left',
                            fontSize: '15px',
                          }}
                        >
                          {item.ProdName || 'Product Name'}
                        </div>
                        {item.BrandName && (
                          <div
                            style={{
                              fontSize: '12px',
                              fontWeight: '700',
                              textAlign: 'left',
                            }}
                          >
                            {item.BrandName}{' '}
                          </div>
                        )}
                        {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>
                              );
                            })
                          : ''}
                      </div>
                      <div
                        style={{
                          padding: '4px 4px',
                          borderRight: '1px solid #000',
                          textAlign: 'center',
                        }}
                      >
                        {item.HSN || ''}
                      </div>
                      <div
                        style={{
                          padding: '4px 4px',
                          borderRight: '1px solid #000',
                          textAlign: 'center',
                          fontWeight: '700',
                          fontSize: '15px',
                        }}
                      >
                        {item.SalesQty || 1} {item.UomName || 'NOS'}
                      </div>
                      <div
                        style={{
                          padding: '4px 4px',
                          borderRight: '1px solid #000',
                          textAlign: 'right',
                        }}
                      >
                        {Number(
                          table2Data?.OrderType !== 'E'
                            ? item.Rate - item.ProdTaxAmt
                            : item.Rate || 0
                        ).toLocaleString('en-IN', {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        })}
                      </div>
                      {/* <div style={{ padding: '8px 4px', borderRight: '1px solid #000', textAlign: 'center' }}>{item.UomName || 'NOS'}</div> */}
                      <div
                        style={{
                          padding: '4px 4px',
                          textAlign: 'right',
                          fontWeight: '700',
                          fontSize: '15px',
                        }}
                      >
                        {Number(
                          table2Data?.OrderType !== 'E'
                            ? item.WithoutTaxRate
                            : item.TotalAmt || 0
                        ).toLocaleString('en-IN', {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        })}
                      </div>
                    </div>
                  ))}
                  {/* Tax summary */}
                  {shouldShowTaxDetails && (
                    <>
                      {/* Total without tax amount */}
                      <div
                        style={{
                          display: 'grid',
                          gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                          // borderRight: '1px solid #000',
                          fontSize: '15px',
                          minHeight: '22px',
                        }}
                      >
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div
                          style={{
                            padding: '6px 6px',
                            textAlign: 'right',
                            borderRight: '1px solid #000',
                          }}
                        ></div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        {/* <div style={{ borderRight: '1px solid #000'}}></div> */}
                        <div
                          style={{
                            padding: '6px 6px',
                            textAlign: 'right',
                            borderTop: '1px solid #000',
                            fontSize: '15px',
                          }}
                        >
                          ₹{' '}
                          {Number(
                            table2Data?.OrderType !== 'E'
                              ? invoiceData?.totalBillAmount
                              : invoiceData?.grandTotal
                          ).toLocaleString('en-IN', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2,
                          })}
                        </div>
                      </div>
                      {table2Data?.OrderType !== 'E' && (
                        <>
                          {/* CGST */}
                          {OrderDetailGST && OrderDetailGST.length > 0 && (
                            <>
                              <div
                                style={{
                                  display: 'grid',
                                  gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                                  // borderRight: '1px solid #000',
                                  fontSize: '11px',
                                  fontWeight: '700',
                                  minHeight: '22px',
                                }}
                              >
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                <div
                                  style={{
                                    padding: '6px 6px',
                                    textAlign: 'right',
                                    borderRight: '1px solid #000',
                                  }}
                                >
                                  CGST
                                </div>
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                {/* <div style={{ borderRight: '1px solid #000'}}></div> */}
                                <div
                                  style={{
                                    padding: '6px 6px',
                                    textAlign: 'right',
                                  }}
                                >
                                  {OrderDetailGST && OrderDetailGST.length > 0
                                    ? Number(
                                        OrderDetailGST?.reduce(
                                          (sum, item) => sum + (item.CGST || 0),
                                          0
                                        )
                                      ).toLocaleString('en-IN', {
                                        minimumFractionDigits: 2,
                                        maximumFractionDigits: 2,
                                      })
                                    : '0.00'}
                                </div>
                              </div>
                              {/* SGST */}
                              <div
                                style={{
                                  display: 'grid',
                                  gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                                  // borderRight: '1px solid #000',
                                  fontSize: '11px',
                                  fontWeight: '700',
                                  minHeight: '22px',
                                }}
                              >
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                <div
                                  style={{
                                    padding: '6px 6px',
                                    textAlign: 'right',
                                    borderRight: '1px solid #000',
                                  }}
                                >
                                  SGST
                                </div>
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                <div
                                  style={{ borderRight: '1px solid #000' }}
                                ></div>
                                {/* <div style={{ borderRight: '1px solid #000'}}></div> */}
                                <div
                                  style={{
                                    padding: '6px 6px',
                                    textAlign: 'right',
                                  }}
                                >
                                  {OrderDetailGST && OrderDetailGST.length > 0
                                    ? Number(
                                        OrderDetailGST?.reduce(
                                          (sum, item) => sum + (item.SGST || 0),
                                          0
                                        )
                                      ).toLocaleString('en-IN', {
                                        minimumFractionDigits: 2,
                                        maximumFractionDigits: 2,
                                      })
                                    : '0.00'}
                                </div>
                              </div>
                            </>
                          )}
                          {/* IGST */}
                          {OrderDetailIGST && OrderDetailIGST.length > 0 && (
                            <div
                              style={{
                                display: 'grid',
                                gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                                // borderRight: '1px solid #000',
                                fontSize: '11px',
                                fontWeight: '700',
                                minHeight: '22px',
                              }}
                            >
                              <div
                                style={{ borderRight: '1px solid #000' }}
                              ></div>
                              <div
                                style={{
                                  padding: '6px 6px',
                                  textAlign: 'right',
                                  borderRight: '1px solid #000',
                                }}
                              >
                                IGST
                              </div>
                              <div
                                style={{ borderRight: '1px solid #000' }}
                              ></div>
                              <div
                                style={{ borderRight: '1px solid #000' }}
                              ></div>
                              <div
                                style={{ borderRight: '1px solid #000' }}
                              ></div>
                              {/* <div style={{ borderRight: '1px solid #000'}}></div> */}

                              <div
                                style={{
                                  padding: '6px 6px',
                                  textAlign: 'right',
                                }}
                              >
                                {OrderDetailIGST && OrderDetailIGST.length > 0
                                  ? Number(
                                      OrderDetailIGST?.reduce(
                                        (sum, item) => sum + (item.TaxAmt || 0),
                                        0
                                      )
                                    ).toLocaleString('en-IN', {
                                      minimumFractionDigits: 2,
                                      maximumFractionDigits: 2,
                                    })
                                  : '0.00'}
                              </div>
                            </div>
                          )}
                        </>
                      )}
                      {/* Rounding Off */}
                      <div
                        style={{
                          display: 'grid',
                          gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                          // borderRight: '1px solid #000',
                          // borderBottom: '1px solid #000',
                          fontSize: '11px',
                          fontWeight: '700',
                          minHeight: '22px',
                        }}
                      >
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div
                          style={{
                            padding: '6px 6px',
                            textAlign: 'right',
                            borderRight: '1px solid #000',
                          }}
                        >
                          ROUNDING OFF
                        </div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        {/* <div style={{ borderRight: '1px solid #000'}}></div> */}
                        <div style={{ padding: '6px 6px', textAlign: 'right' }}>
                          {RoundOffFun(
                            table2Data?.OrderType !== 'E'
                              ? roundOffValue
                              : roundOffEstimateValue
                          )}
                        </div>
                      </div>
                      {Array.from({
                        length: chunkSize - dataChunk.length,
                      })?.map((_, idx) => (
                        <div
                          key={`empty-${idx}`}
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                            // borderRight: '1px solid #000',

                            minHeight: '32px', // Adjust height as needed for your design
                            fontSize: '10px',
                          }}
                        >
                          <div
                            style={{
                              padding: '4px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            &nbsp;
                          </div>
                          <div
                            style={{
                              padding: '4px 4px',
                              borderRight: '1px solid #000',
                            }}
                          >
                            &nbsp;
                          </div>
                          <div
                            style={{
                              padding: '4px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            &nbsp;
                          </div>
                          <div
                            style={{
                              padding: '4px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            &nbsp;
                          </div>
                          <div
                            style={{
                              padding: '4px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            &nbsp;
                          </div>
                          {/* <div style={{ padding: '8px 4px', borderRight: '1px solid #000', textAlign: 'center' }}>&nbsp;</div> */}
                          <div
                            style={{ padding: '4px 4px', textAlign: 'right' }}
                          >
                            &nbsp;
                          </div>
                        </div>
                      ))}
                      {/* Total */}
                      <div
                        style={{
                          display: 'grid',
                          gridTemplateColumns: '5% 40% 12% 11% 16% 16%',
                          // borderRight: '1px solid #000',
                          borderBottom: '1px solid #000',
                          borderTop: '1px solid #000',

                          minHeight: '30px',
                        }}
                      >
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div
                          style={{
                            padding: '8px 6px',
                            textAlign: 'right',
                            fontSize: '12px',
                            borderRight: '1px solid #000',
                          }}
                        >
                          Total
                        </div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        <div
                          style={{
                            padding: '8px 3px',
                            textAlign: 'center',
                            borderRight: '1px solid #000',
                            fontWeight: '700',
                          }}
                        >
                          {totalQuantity ||
                            invoiceData.productDetails?.reduce(
                              (sum, item) => sum + (item.SalesQty || 0),
                              0
                            ) ||
                            0}{' '}
                          NOS
                        </div>
                        <div style={{ borderRight: '1px solid #000' }}></div>
                        {/* <div style={{ borderRight: '1px solid #000'}}></div> */}
                        <div
                          style={{
                            padding: '8px 6px',
                            textAlign: 'right',
                            fontWeight: '700',
                            fontSize: '15px',
                          }}
                        >
                          ₹{' '}
                          {Number(invoiceData.grandTotal).toLocaleString(
                            'en-IN',
                            {
                              minimumFractionDigits: 2,
                              maximumFractionDigits: 2,
                            }
                          )}
                        </div>
                      </div>
                    </>
                  )}
                </>
              ) : (
                // Show empty row when no data
                <div
                  style={{
                    display: 'grid',
                    gridTemplateColumns: '5% 40% 12% 10% 12% 8% 13%',
                    // borderBottom: '1px solid #000',
                    borderLeft: '1px solid #000',
                    borderRight: '1px solid #000',
                    fontSize: '10px',
                    minHeight: '40px',
                  }}
                >
                  <div
                    style={{
                      padding: '8px 4px',
                      borderRight: '1px solid #000',
                      textAlign: 'center',
                      fontWeight: '700',
                    }}
                  >
                    -
                  </div>
                  <div
                    style={{
                      padding: '8px 4px',
                      borderRight: '1px solid #000',
                      textAlign: 'center',
                    }}
                  >
                    No items to display
                  </div>
                  <div
                    style={{
                      padding: '8px 4px',
                      borderRight: '1px solid #000',
                      textAlign: 'center',
                    }}
                  >
                    -
                  </div>
                  <div
                    style={{
                      padding: '8px 4px',
                      borderRight: '1px solid #000',
                      textAlign: 'center',
                    }}
                  >
                    -
                  </div>
                  <div
                    style={{
                      padding: '8px 4px',
                      borderRight: '1px solid #000',
                      textAlign: 'center',
                    }}
                  >
                    -
                  </div>
                  <div
                    style={{
                      padding: '8px 4px',
                      borderRight: '1px solid #000',
                      textAlign: 'center',
                    }}
                  >
                    -
                  </div>
                  <div style={{ padding: '8px 4px', textAlign: 'center' }}>
                    -
                  </div>
                </div>
              )}
            </div>
          )}
          {/* Tax summary - Only on last page */}

          {/* Footer content - Only on last page */}
          {isLastPage && (
            <>
              {/* Amount in Words */}
              <div
                style={{
                  padding: '8px 10px',
                  borderBottom: '1px solid #000',
                  fontSize: '11px',
                  display: 'flex',
                  justifyContent: 'space-between',
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'flex-start',
                    flexDirection: 'column',
                  }}
                >
                  <div style={{ marginBottom: '3px' }}>
                    Amount Chargeable (in words)
                  </div>
                  <div style={{ fontWeight: '700', fontSize: '16px' }}>
                    INR {numberToWords(Math.floor(invoiceData.grandTotal))} Only
                  </div>
                </div>
                <p>E. & O.E</p>
              </div>

              {table2Data?.OrderType !== 'E' && (
                <>
                  {/* Tax Breakdown Table */}
                  <div style={{ borderBottom: '1px solid #000' }}>
                    {OrderDetailGST && OrderDetailGST.length > 0 ? (
                      <>
                        {/* Tax Table Header - Main Headers */}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '12% 15% 18% 18% 15% 22%',
                            borderBottom: '1px solid #000',
                            fontSize: '9px',
                          }}
                        >
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            HSN/SAC
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Taxable Value
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            CGST
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            SGST/UTGST
                          </div>
                          <div
                            style={{ padding: '6px 4px', textAlign: 'center' }}
                          >
                            Tax Amount
                          </div>
                        </div>

                        {/* Tax Table Sub-Headers */}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '12% 15% 9% 9% 9% 9% 15% 22%',
                            borderBottom: '1px solid #000',
                            fontSize: '8px',
                          }}
                        >
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Rate
                          </div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Amount
                          </div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Rate
                          </div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Amount
                          </div>
                          <div
                            style={{ padding: '4px 2px', textAlign: 'center' }}
                          ></div>
                        </div>

                        {/* Tax Table Rows - Dynamic from OrderDetailGST */}
                        {OrderDetailGST?.map((taxItem, index) => (
                          <div
                            key={index}
                            style={{
                              display: 'grid',
                              gridTemplateColumns:
                                '12% 15% 9% 9% 9% 9% 15% 22%',
                              borderBottom: '1px solid #000',
                              fontSize: '9px',
                              minHeight: '20px',
                            }}
                          >
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'center',
                                fontWeight: '700',
                              }}
                            >
                              {taxItem.HSN || ''}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'right',
                              }}
                            >
                              {Number(
                                taxItem.WithOutTaxAmount || 0
                              ).toLocaleString('en-IN', {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2,
                              })}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'center',
                              }}
                            >
                              {taxItem.TaxPercentage
                                ? taxItem.TaxPercentage / 2 + '%'
                                : '0%'}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'right',
                              }}
                            >
                              {Number(taxItem.CGST || 0).toLocaleString(
                                'en-IN',
                                {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                }
                              )}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'center',
                              }}
                            >
                              {taxItem.TaxPercentage
                                ? taxItem.TaxPercentage / 2 + '%'
                                : '0%'}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'right',
                              }}
                            >
                              {Number(taxItem.SGST || 0).toLocaleString(
                                'en-IN',
                                {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                }
                              )}
                            </div>
                            <div style={{ padding: '4px', textAlign: 'right' }}>
                              {Number(
                                (taxItem.CGST || 0) + (taxItem.SGST || 0)
                              ).toLocaleString('en-IN', {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2,
                              })}
                            </div>
                          </div>
                        ))}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '12% 15% 9% 9% 9% 9% 15% 22%',
                            fontSize: '9px',
                            fontWeight: '700',
                            minHeight: '22px',
                          }}
                        >
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Total
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {OrderDetailGST && OrderDetailGST.length > 0
                              ? Number(
                                  OrderDetailGST?.reduce(
                                    (sum, item) =>
                                      sum + (item.WithOutTaxAmount || 0),
                                    0
                                  )
                                ).toLocaleString('en-IN', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })
                              : '0.00'}
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {OrderDetailGST && OrderDetailGST.length > 0
                              ? Number(
                                  OrderDetailGST?.reduce(
                                    (sum, item) => sum + (item.CGST || 0),
                                    0
                                  )
                                ).toLocaleString('en-IN', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })
                              : '0.00'}
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {OrderDetailGST && OrderDetailGST.length > 0
                              ? Number(
                                  OrderDetailGST?.reduce(
                                    (sum, item) => sum + (item.SGST || 0),
                                    0
                                  )
                                ).toLocaleString('en-IN', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })
                              : '0.00'}
                          </div>
                          <div
                            style={{ padding: '6px 4px', textAlign: 'right' }}
                          >
                            {OrderDetailGST && OrderDetailGST.length > 0
                              ? Number(
                                  OrderDetailGST?.reduce(
                                    (sum, item) =>
                                      sum + (item.CGST || 0) + (item.SGST || 0),
                                    0
                                  )
                                ).toLocaleString('en-IN', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })
                              : '0.00'}
                          </div>
                        </div>
                      </>
                    ) : OrderDetailIGST && OrderDetailIGST.length > 0 ? (
                      <>
                        {/* Tax Table Header - Main Headers */}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '22% 21% 18%  21% 18%',
                            borderBottom: '1px solid #000',
                            fontSize: '9px',
                          }}
                        >
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            HSN/SAC
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Taxable Value
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            IGST
                          </div>
                          <div
                            style={{ padding: '6px 4px', textAlign: 'center' }}
                          >
                            Tax Amount
                          </div>
                        </div>
                        {/* Tax Table Sub-Headers */}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '22% 21% 9% 9%  21% 18%',
                            borderBottom: '1px solid #000',
                            fontSize: '8px',
                          }}
                        >
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Rate
                          </div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Amount
                          </div>

                          <div
                            style={{ padding: '4px 2px', textAlign: 'center' }}
                          ></div>
                        </div>
                        {/* Tax Table Rows - Dynamic from OrderDetailGST */}
                        {OrderDetailIGST?.map((taxItem, index) => (
                          <div
                            key={index}
                            style={{
                              display: 'grid',
                              gridTemplateColumns: '22% 21% 9% 9%  21% 18%',
                              borderBottom: '1px solid #000',
                              fontSize: '9px',
                              minHeight: '20px',
                            }}
                          >
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'center',
                                fontWeight: '700',
                              }}
                            >
                              {taxItem.HSN || ''}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'right',
                              }}
                            >
                              {Number(
                                taxItem.WithOutTaxAmount || 0
                              ).toLocaleString('en-IN', {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2,
                              })}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'center',
                              }}
                            >
                              {taxItem.TaxPercentage
                                ? taxItem.TaxPercentage + '%'
                                : '0%'}
                            </div>
                            <div
                              style={{
                                padding: '4px',
                                borderRight: '1px solid #000',
                                textAlign: 'right',
                              }}
                            >
                              {Number(taxItem.TaxAmt || 0).toLocaleString(
                                'en-IN',
                                {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                }
                              )}
                            </div>
                            <div style={{ padding: '4px', textAlign: 'right' }}>
                              {Number(taxItem.TaxAmt || 0).toLocaleString(
                                'en-IN',
                                {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                }
                              )}
                            </div>
                          </div>
                        ))}{' '}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '22% 21% 9% 9%  21% 18%',
                            fontSize: '9px',
                            fontWeight: '700',
                            minHeight: '22px',
                          }}
                        >
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Total
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {OrderDetailIGST && OrderDetailIGST.length > 0
                              ? Number(
                                  OrderDetailIGST?.reduce(
                                    (sum, item) =>
                                      sum + (item.WithOutTaxAmount || 0),
                                    0
                                  )
                                ).toLocaleString('en-IN', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })
                              : '0.00'}
                          </div>

                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {OrderDetailIGST && OrderDetailIGST.length > 0
                              ? Number(
                                  OrderDetailIGST?.reduce(
                                    (sum, item) => sum + (item.TaxAmt || 0),
                                    0
                                  )
                                ).toLocaleString('en-IN', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })
                              : '0.00'}
                          </div>
                          <div
                            style={{ padding: '6px 4px', textAlign: 'right' }}
                          >
                            {OrderDetailIGST && OrderDetailIGST.length > 0
                              ? Number(
                                  OrderDetailIGST?.reduce(
                                    (sum, item) => sum + (item.TaxAmt || 0),
                                    0
                                  )
                                ).toLocaleString('en-IN', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })
                              : '0.00'}
                          </div>
                        </div>
                      </>
                    ) : (
                      <>
                        {/* Tax Table Header - Main Headers */}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '12% 15% 18% 18% 15% 22%',
                            borderBottom: '1px solid #000',
                            fontSize: '9px',
                          }}
                        >
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            HSN/SAC
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Taxable Value
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            CGST
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            SGST/UTGST
                          </div>
                          <div
                            style={{ padding: '6px 4px', textAlign: 'center' }}
                          >
                            Tax Amount
                          </div>
                        </div>

                        {/* Tax Table Sub-Headers */}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '12% 15% 9% 9% 9% 9% 15% 22%',
                            borderBottom: '1px solid #000',
                            fontSize: '8px',
                          }}
                        >
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Rate
                          </div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Amount
                          </div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Rate
                          </div>
                          <div
                            style={{
                              padding: '4px 2px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Amount
                          </div>
                          <div
                            style={{ padding: '4px 2px', textAlign: 'center' }}
                          ></div>
                        </div>

                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '12% 15% 9% 9% 9% 9% 15% 22%',
                            borderBottom: '1px solid #000',
                            fontSize: '9px',
                            minHeight: '20px',
                          }}
                        >
                          <div
                            style={{
                              padding: '4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                              fontWeight: '700',
                            }}
                          >
                            -
                          </div>
                          <div
                            style={{
                              padding: '4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            0.00
                          </div>
                          <div
                            style={{
                              padding: '4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            0%
                          </div>
                          <div
                            style={{
                              padding: '4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            0.00
                          </div>
                          <div
                            style={{
                              padding: '4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            0%
                          </div>
                          <div
                            style={{
                              padding: '4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            0.00
                          </div>
                          <div style={{ padding: '4px', textAlign: 'right' }}>
                            0.00
                          </div>
                        </div>
                        {/* Tax Table Total */}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '12% 15% 9% 9% 9% 9% 15% 22%',
                            fontSize: '9px',
                            fontWeight: '700',
                            minHeight: '22px',
                          }}
                        >
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          >
                            Total
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {'0.00'}
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {'0.00'}
                          </div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'center',
                            }}
                          ></div>
                          <div
                            style={{
                              padding: '6px 4px',
                              borderRight: '1px solid #000',
                              textAlign: 'right',
                            }}
                          >
                            {'0.00'}
                          </div>
                          <div
                            style={{ padding: '6px 4px', textAlign: 'right' }}
                          >
                            {'0.00'}
                          </div>
                        </div>
                      </>
                    )}
                  </div>

                  {/* Tax Amount in Words */}
                  <div
                    style={{
                      padding: '3px 5px',
                      fontSize: '11px',
                    }}
                  >
                    <div>
                      Tax Amount (in words):{' '}
                      <span style={{ fontWeight: '700' }}>
                        INR{' '}
                        {numberToWords(
                          Math.floor(
                            invoiceData.taxAmount ||
                              OrderDetailGST?.reduce(
                                (sum, item) =>
                                  sum + (item.CGST || 0) + (item.SGST || 0),
                                0
                              ) ||
                              Number(
                                OrderDetailIGST?.reduce(
                                  (sum, item) => sum + (item.TaxAmt || 0),
                                  0
                                )
                              ) ||
                              0
                          )
                        )}{' '}
                        Only
                      </span>
                    </div>
                  </div>
                </>
              )}
              {/* Bank Details and Signature */}
              <div
                style={{ display: 'flex', minHeight: '120px', width: '100%' }}
              >
                {/* Declaration */}
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'flex-end',
                    width: '50%',
                  }}
                >
                  <div
                    style={{
                      padding: '8px 10px',
                      fontSize: '11px',
                    }}
                  >
                    <div
                      style={{
                        marginBottom: '3px',
                        fontSize: '12px',
                        borderBottom: '1px solid #000',
                        width: 'max-content',
                      }}
                    >
                      Declaration
                    </div>
                    <div>
                      We declare that this invoice shows the actual price of the
                      goods described and that all particulars are true and
                      correct.
                    </div>
                  </div>
                </div>

                {/* Signature Section */}
                <div
                  style={{
                    flex: '1',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                    alignItems: 'flex-start',
                    width: '50%',
                  }}
                >
                  {/* Bank Details */}
                  <div
                    style={{
                      flex: '1',
                      padding: '5px',
                      fontSize: '11px',
                      textAlign: 'left',
                    }}
                  >
                    {!estimatePrintHeader && table2Data?.OrderType === 'E' ? (
                      ''
                    ) : (
                      <div style={{ marginBottom: '3px', fontSize: '12px' }}>
                        Company's Bank Details
                      </div>
                    )}
                    {!estimatePrintHeader && table2Data?.OrderType === 'E' ? (
                      ''
                    ) : (
                      <div>
                        <div>
                          <span>A/c Holder's Name:</span>
                          <span style={{ fontWeight: '700' }}>
                            {' '}
                            {invoiceData.companyName}
                          </span>
                        </div>
                        <div>
                          <span>Bank Name:</span>
                          <span style={{ fontWeight: '700' }}>
                            {' '}
                            {invoiceData.bankDetails?.BankName || ''}
                          </span>
                        </div>
                        <div>
                          <span>A/c No.:</span>{' '}
                          <span style={{ fontWeight: '700' }}>
                            {invoiceData.bankDetails?.AccountNo || ''}
                          </span>
                        </div>
                        <div>
                          <span>Branch & IFS Code:</span>{' '}
                          <span style={{ fontWeight: '700' }}>
                            {invoiceData.bankDetails?.BankBranch || ''} &{' '}
                            {invoiceData.bankDetails?.IFSCCode || ''}
                          </span>
                        </div>
                        {invoiceData.bankDetails?.SWIFTCode && (
                          <div>
                            <span style={{ fontWeight: '700' }}>
                              SWIFT Code:
                            </span>
                            <span style={{ fontWeight: '600' }}>
                              {' '}
                              {invoiceData.bankDetails?.SWIFTCode || ''}
                            </span>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                  <div
                    style={{
                      borderTop: '1px solid #000',
                      borderLeft: '1px solid #000',
                      width: isMobile ? '100%' : '92%',
                      padding: '15px',
                    }}
                  >
                    {!estimatePrintHeader && table2Data?.OrderType === 'E' ? (
                      ''
                    ) : (
                      <div
                        style={{
                          fontSize: '11px',
                          fontWeight: '700',
                          marginBottom: '10px',
                          textAlign: 'right',
                        }}
                      >
                        for {invoiceData.companyName}
                      </div>
                    )}
                    <div
                      style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'right',
                        marginBottom: '10px',
                      }}
                    >
                      <div
                        style={{
                          width: '70px',
                          height: '30px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          marginBottom: '5px',
                        }}
                      >
                        <div
                          style={{
                            fontSize: '8px',
                            textAlign: 'center',
                            fontWeight: '700',
                            lineHeight: '1.1',
                          }}
                        >
                          {/* <div>DD</div>
                  <div>TECHNOLOGIES</div>
                  <div>ELECTRONICS</div> */}
                        </div>
                      </div>
                      <div style={{ fontSize: '10px', textAlign: 'right' }}>
                        Authorised Signatory
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </>
          )}
        </div>

        {/* Footer - Only on last page */}
        {isLastPage && (
          <div
            style={{
              textAlign: 'center',
              fontSize: '10px',
              padding: '8px',
            }}
          >
            <div>This is a Computer Generated Invoice</div>
          </div>
        )}
      </>
    );
  }
};

export default TaxInvoice;
