import React, { useEffect, useState } from 'react';
import {
  Descriptions,
  Badge,
  Layout,
  Row,
  Col,
  Card,
  Button,
  Spin,
  Input,
} from 'antd';
import './documents.css';
import {
  ContainerLoadingStatus,
  GlobalStatus,
  InvoiceCategoriesEnum,
  ModeOfExportEnum,
  TaxCategoriesEnum,
  UomEnum,
} from '@gtpl/shared-models/common-models';
import { componentRequest, ExporterDataInput } from '@gtpl/shared-models/logistics';
import {
  PlantInvoiceDetailsModel,
  PlantInvoiceDetailsRequest,
  FactoriesInput,
  UnitsOfWeightInput,
  CrrencySymbols,
  ConditionsRequest,
} from '@gtpl/shared-models/sale-management';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { useLocation } from 'react-router-dom';
import { PrinterOutlined } from '@ant-design/icons';
let converter = require('number-to-words');
import { numberToWords } from 'amount-to-words';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import moment from 'moment';
import { ToWords } from 'to-words';
import { SaleOrderDetails } from '@gtpl/pages/sale-management/sale-components/sale-order-detail-view-grid';
import stampImage from './stamp.png';
import signature from './signature.png';
import { GlobalPriceChartService } from '@gtpl/shared-services/masters';
import { ContainerRegisterService } from '@gtpl/shared-services/logistics';

const toWords = new ToWords({
  localeCode: 'en-US',
});

/* eslint-disable-next-line */
export interface CustomsInvoiceProps {
  saleOrderId: number;
  showStuffingCertificate: boolean; 
}

export function CustomsInvoice(props: CustomsInvoiceProps) {
  let location = useLocation();
  const salOrderService = new SaleOrderService();
  const [plantDetails, setPlantDetails] = useState<PlantInvoiceDetailsModel>();
  const soId = location.state;
  const [remarksData, setRemarksData] = useState<string>(undefined);
  const { TextArea } = Input;
  // const [showStuffingCertificate]
  const defaultDeclaration =
    'WE INTEND TO CLAIM REWARDS UNDER REMISSION OF DUTIES  OR  TAXES ON EXPORT PRODUSTS';
  const [mainData, setMainData] = useState<any[]>([]);
  const globalPriceService = new GlobalPriceChartService();
  const [span, setSpan] = useState(1);
  const [conditionRes, setConditionRes] = useState([]);
  const containerRegisterService = new ContainerRegisterService();
  const [cvdDetails,setCvdDetails]=useState<any>()
  const [mpfDetails,setMpfDetails]=useState<any>()
  const [tariffDetails,setTariffDetails]=useState<any>()

// console.log(plantDetails?.deliveryTerms.includes('DDP'));

  let totalCases = 0;
  let totalLbWeight = 0;
  let totalGrossWeight = 0;
  let totalFrozenWeight = 0;
  let netWeightInKgs = 0;
  let netWeightInLbs = 0;
  let totalAmount = 0;
  let itemsTotalAmount = 0;
  let grossWeightInKg;
  let frozenWeightInKg;
  let antiDumping;
  let fob;
  let subTotal;
  let cvdVal;
  let mpfVal;
  let tariffVal;

  useEffect(() => {
    getAntiDumpingPrice();
  }, []);

  const getAntiDumpingPrice = () => {
    globalPriceService
      .getAntiDumpingPrice()
      .then((res) => {
        if (res.status) {
          setMainData(res.data);
        } else {
          setMainData([]);
        }
      })
      .catch((err) => {
        setMainData([]);
      });
  };

  // useEffect(()=>{
  //   getCvdRatesForCustomsInvoice()
    
  // },[])

//   useEffect(() => {
//   getCvdRatesForCustomsInvoice();
// }, []);

// const getCvdRatesForCustomsInvoice = () => {
//   getComponentRate("CVD", setCvdDetails);
//   getComponentRate("MPF & HARBOUR MAINTAINCE", setMpfDetails);
//   getComponentRate("RECIPROCAL TARIFF", setTariffDetails);
// };
  // const getCvdRatesForCustomsInvoice=()=>{
  //   containerRegisterService.getCvdRatesForCustomsInvoice().then((res)=>{
  //       if(res.status){
  //         setCvdDetails(res.data.find(e=>e.component === 'CVD'))
  //           setMpfDetails(res.data.find(e=>e.component === 'MPF & HARBOUR MAINTAINCE'))
  //           setTariffDetails(res.data.find(e=>e.component === 'RECIPROCAL TARIFF'))


  //       }else{
  //           setCvdDetails(undefined)
  //       }
  //   })
  // }
// const getComponentRate = (component, setter) => {
//   const req = new componentRequest(component); // pass the component name
//   containerRegisterService.getCvdRatesForCustomsInvoice(req).then((res) => {
//     if (res.status) {
//       const matchedRate = res.data.find((e) => e.component === component);
//       setter(matchedRate ?? null); // in case not found, set null
//       console.log(matchedRate,setter,'seteeeeeeeeeeeeeeeeeee');
      
//     } else {
//       setter(null);
//     }
//   })
// };
  const getCvdValue = (cvdRates, invoiceDate) => {
    // console.log(cvdRates,'cvdratesssssssss');
    
    if (!cvdRates?.length || !invoiceDate) return null;
  
    const invoiceTime = new Date(invoiceDate).getTime();
  
    // Find the matching CVD record based on invoiceDate
    let selectedCvd = cvdRates?.find(({ effective_from, created_at }) => {
      const effectiveTime = new Date(effective_from).getTime();
      const createdTime = new Date(created_at).getTime();
      // console.log(effectiveTime,'effectiveTime');
      // console.log(createdTime,'createdTime');
      return invoiceTime >= effectiveTime && invoiceTime <= createdTime;
    });
  // console.log(selectedCvd,'!selectedCvd');
  
    // If no match found, select the one with the latest created_at
    if (!selectedCvd) {
      // console.log(cvdRates?.reduce((latest, current) =>
      //   new Date(current?.created_at) > new Date(latest.created_at) ? current : latest
      // , cvdRates[0]),'oooooooooo');
      // console.log(cvdRates,'pppppppppdddd');
      
      selectedCvd = cvdRates?.[0];
    }
  // console.log(selectedCvd.price,'seeeeeeee');
  
    return selectedCvd ? Number(selectedCvd?.price) : 0;
  };
  

  const getData = (saleOrderId) => {
    const reqObj = new PlantInvoiceDetailsRequest(1);
    salOrderService
      .getPlantInvoiceDetails(new PlantInvoiceDetailsRequest(saleOrderId))
      .then((res) => {
        if (res.status) {
          setPlantDetails(res.data);
          const invoiceDate = res.data.invoiceDate;
          const fetchComponentRate = (component, setter) => {
            // console.log(component,'pppppppppppp');
            
            
            const req = new componentRequest(component);
            containerRegisterService.getCvdRatesForCustomsInvoice(req).then((cvdRes) => {
              if (cvdRes.status) {
              // console.log(cvdRes.data,'pppppppppppp');
              // console.log(cvdRes.data.filter(e => e.component === component),'iiiiiiiiiiii');
              
              const filteredRates = cvdRes.data.filter(e => e.component === component);
              const value = getCvdValue(filteredRates, invoiceDate);
              // console.log(Number(value),'vallllllllllllllll');
              
              setter(value);
            }
          });
        };

        // Fetching all 3 components individually
        fetchComponentRate("CVD", setCvdDetails);
        fetchComponentRate("MPF & HARBOUR MAINTAINCE", setMpfDetails);
        fetchComponentRate("RECIPROCAL TARIFF", setTariffDetails);



          res.data.gradeInfo.map((res) =>
            res.info.filter((val) => val.itemCode != null)
          );
          const request = new ConditionsRequest();
          request.country = res.data.country;
          request.frozenWeight = res.data.frozenWeight;
          request.grossWeight = res.data.grossWeight;
          request.notifyParty = res.data.notifyPartyOne;
          request.deliveryTerms = res.data.deliveryTerms;
          request.buyer = res.data.endCustomerName;
          request.buyerAddress = plantDetails?.saleOrderItems[0]?.buyerAddress;
          request.deliveryAddress =
            plantDetails?.saleOrderItems[0]?.deliveryaddress;
          // request.netWeight=
          salOrderService.getConditionsBasedLogistics(request).then((res) => {
            if (res.status) {
              setConditionRes(res.data);
            }
          });
        } else {
          if (res.intlCode) {
            setPlantDetails(undefined);
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setPlantDetails(undefined);
      });
  };

  // const groupedData: Array<Array<any>> = Object.values(plantDetails.saleOrderItems.reduce((acc, rec) => {
  //   const imCode = rec.productDescription + rec.productDescription || 'undefined';
  //   acc[imCode] = acc[imCode] || [];
  //   acc[imCode].push(rec);

  //   return acc;
  // }, {}));
  useEffect(() => {
    if (props.saleOrderId) {
      getData(props.saleOrderId);
    }
  }, [props.saleOrderId]);
  let exporterDetails = ExporterDataInput;
  const idToFind = plantDetails?.isInvoiced === "YES" 
    ? plantDetails?.exporterId 
    : plantDetails?.unitId;
    const exporterData = exporterDetails.find(item => item.value === idToFind);
    const processingId= plantDetails?.processingUnit;

    const processingData = exporterDetails.find(
      (item) => item.value === processingId
    );
  let exporterPlant = FactoriesInput;
  const exportersPlant = exporterPlant.find(
    (item) => item.id == processingId
  )

  const handleRemarks = (value) => {
    setRemarksData(value);
  };
  let unitInput = FactoriesInput;
  const unitsData = FactoriesInput.find(
    (item) => item.id == plantDetails?.unitId
  );
  const tableData = () => {
    const tableDataArray = [];
    for (const data of plantDetails?.saleOrderItems) {
      const tableDataArray = data;
    }
  };

  let spanVal = 0;
  let adjustSpan = 0;
  const rowSpanValue = Number(Math.round(plantDetails?.gradeInfo?.length / 2));
  if (
    plantDetails?.gradeInfo?.length % 2 !== 0 &&
    plantDetails?.gradeInfo?.length > 1
  ) {
    spanVal = Number(Math.round(plantDetails?.gradeInfo?.length / 2));
    adjustSpan = Number(Math.round(plantDetails?.gradeInfo?.length / 2)) - 1;
  } else if (plantDetails?.gradeInfo?.length === 1) {
    spanVal = 1;

    adjustSpan = 1;
  } else {
    spanVal = Number(Math.round(plantDetails?.gradeInfo?.length / 2));
    adjustSpan = Number(Math.round(plantDetails?.gradeInfo?.length / 2));
  }


  let totalContainersRowSpan = 0;
  let containerProductLevelRowSpan = new Map<number, number>(); // map of array_index_of_product => no of rows in it
  plantDetails?.gradeInfo?.forEach((g, prodIndex) => {
    let prodRowCount = 0;
    g?.info?.forEach((r, i) => {
      // incre,ent the total row span for every record
      totalContainersRowSpan++;
      prodRowCount++;
    });
    containerProductLevelRowSpan.set(prodIndex, prodRowCount);
  });
  const copiedContainerRowSpan = totalContainersRowSpan;

  const sealNoRowPortionSpan = totalContainersRowSpan / 2;

  const lhsContent = [];
  const rhsContent = [];

  function ConstrunctLhsContent(plantDetails: PlantInvoiceDetailsModel) {
    lhsContent.push(
      <>
        <b>Exporter:</b> <br />
        <h4>
          {exporterData?.company ? exporterData?.company : ''}
          <br />
          {exporterData?.addressOne ? exporterData?.addressOne + ',' : ''}
          <br />
          {exporterData?.addressTwo
            ? exporterData?.addressTwo + ' - ' + exporterData?.postalCode
            : ''}
          <br />
          {exporterData?.state + ', ' + exporterData?.country}
          <br />
         
          {exporterData?.phoneNumber? 
          <>PHONE:{exporterData?.phoneNumber}
          <br />
          </>:''}
          {exporterData?.faxNo!=null? <>FAX:{exporterData?.faxNo}</>:''}
          <br/>
          GSTIN: {exporterData?.GSTNumber}
          <br />
          USFDA REGN NO: {exporterData?.usfdaRegNo}
        </h4>
      </>
    );

    {
      plantDetails?.consigneeAddress != undefined ||
      plantDetails?.consignee != null ? (
        lhsContent.push(
          <>
            <b>
              <u>Consignee:</u>
            </b>
            <br />
            {plantDetails?.consignee}
            {plantDetails?.consignee ? ':' : ''}
            <br />
            {plantDetails?.consigneeAddress?.split(',')}
            <br />
            {plantDetails?.country ? plantDetails?.country : ''}
          </>
        )
      ) : (
        <></>
      );
    }

    {
      conditionRes?.[0]?.importerDetails === true ? (
        lhsContent.push(
          <>
            <b>Importer of record:</b>
            <div><h4>
              {exporterData?.company ? exporterData?.company : ''}
            </h4></div>
            <div>{exporterData?.addressOne + ','}</div>
           <div> {exporterData?.addressTwo
              ? exporterData?.addressTwo + ' - ' + exporterData?.postalCode
              : ''}</div>
            <div> {exporterData?.state + ', ' + exporterData?.country}
            </div>
            PHONE:{exporterData?.phoneNumber}
            <br />
            {exporterData?.faxNo!=null? <>FAX:{exporterData?.faxNo}</>:''}
            <br/>
            <b>Import On Record: </b>
            {plantDetails?.country === 'USA'
              ? exporterData?.importerOfRecord
              : ''}
          </>
        )
      ) : (
        <></>
      );
    }


    rhsContent.push(
      <>
        <b>Invoice No: </b>
        {plantDetails?.invoiceNumber}
      </>
    );

    rhsContent.push(
      <>
        <b>Invoice Date: </b>
        {plantDetails?.invoiceDate
          ? moment(plantDetails?.invoiceDate).format('DD-MM-YYYY')
          : ''}
      </>
    );

    rhsContent.push(
      <>
        <b>Place Of Supply: </b>{' '}
        {(plantDetails?.saleOrderItems[0]?.destinationDetails
          ?
            plantDetails?.saleOrderItems[0]?.destinationDetails?.toUpperCase()
          : '') +
          ',' +
          (plantDetails?.country ? plantDetails?.country : '')}
      </>
    );

    rhsContent.push(
      <>
        <b>Tax is payable On Reverse Charge : NO</b>
      </>
    );

    // rhsContent.push(
    //   <>
    //     <b>GST NO: </b>
    //     {exporterData?.GSTNumber}
    //   </>
    // );

    rhsContent.push(
      <>
        <b>
          Exporter's Ref
          <br />
          IE Code{' '}
        </b>{' '}
        {exporterData?.ieCode}
      </>
    );

    // {
    //   conditionRes?.[0]?.duplicateBuyer === true ? (
    //     rhsContent.push(
    //       <>
    //         {plantDetails?.consigneeAddress != undefined ||
    //         plantDetails?.consignee != null ? (
    //           <b>{plantDetails?.endCustomerName === "HIGH LINER FOODS INC" ? "Ship To:" : "Buyer:"} </b>
    //         ) : (
    //           <b>Buyer & Consignee:</b>
    //         )}
    //         <br />
    //         {conditionRes?.[0]?.duplicateBuyerAddress
    //           ? conditionRes?.[0]?.duplicateBuyerAddress
    //           : plantDetails?.saleOrderItems[0]?.buyerAddress}
    //       </>
    //     )
    //   ) : (
    //     <></>
    //   );
    // }

    rhsContent.push(
      <>
          <b>{plantDetails?.endCustomerName != "HIGH LINER FOODS INC" ? !conditionRes?.[0]?.duplicateBuyer? "BUYER :" :" ULTIMATE Buyer:": "SHIP TO:"} </b>
        
        <br />
        {plantDetails?.endCustomerName}
        {plantDetails?.endCustomerName ? ':' : ''}
        <br />
        {plantDetails?.saleOrderItems[0]?.buyerAddress?.split(',')}
        <br />
        {plantDetails?.country ? plantDetails?.country:''}
      </>
    );

    {
      conditionRes?.[0]?.notifyPartyParam === true ? (
        rhsContent.push(
          <>
            <b>Notify Party:</b>
            {plantDetails.notifyPartyOne != null ? (
              <>
                {/* <u>Notify party 1</u> */}
                <br />
                <b>{plantDetails?.notifyPartyOne?.split('\n')[0]}</b>
                <br />
                {plantDetails?.notifyPartyOne?.split('\n')[1]}
                <br />
                {plantDetails?.notifyPartyOne?.split('\n')[2]}
                <br />
                {plantDetails?.notifyPartyOne?.split('\n')[3]}
                <br />
              </>
            ) : (
              ''
            )}
            {plantDetails.notifyPartyTwo != null ? (
              <>
                {/* <u>Notify party 2</u> */}
                <br />
                <b>{plantDetails?.notifyPartyTwo?.split('\n')[0]}</b>
                <br />
                {plantDetails?.notifyPartyTwo?.split('\n')[1]}
                <br />
                {plantDetails?.notifyPartyTwo?.split('\n')[2]}
                <br />
                {plantDetails?.notifyPartyTwo?.split('\n')[3]}
                <br />
                <br />
              </>
            ) : (
              ''
            )}
            {plantDetails.notifyPartyThree != null ? (
              <>
                {/* <u>Notify party 3</u> */}
                <br />
                  <b>{plantDetails?.notifyPartyThree?.split('\n')[0]}</b>
                  <br />
                  {plantDetails?.notifyPartyThree?.split('\n')[1]}
                  <br />
                  {plantDetails?.notifyPartyThree?.split('\n')[2]}
                  <br />
                  {plantDetails?.notifyPartyThree?.split('\n')[3]}
                <br />
                <br />
              </>
            ) : (
              ''
            )}
            {plantDetails.notifyPartyFour != null ? (
              <>
                {/* <u>Notify party 4</u> */}
                <br />
                <b>{plantDetails?.notifyPartyFour?.split('\n')[0]}</b>
                <br />
                {plantDetails?.notifyPartyFour?.split('\n')[1]}
                <br />
                {plantDetails?.notifyPartyFour?.split('\n')[2]}
                <br />
                {plantDetails?.notifyPartyFour?.split('\n')[3]}
                <br />
                <br />
              </>
            ) : (
              ''
            )}
          </>
        )
      ) : (
        <></>
      );
    }

    {
      plantDetails?.htsInfo?.[0]?.htsCode != null ||
      plantDetails?.htsInfo?.[0]?.htsCode != undefined ? (
        rhsContent.push(
          <>
            <b>HTS Code : </b>
            {plantDetails?.htsInfo.map((e) => e.htsCode).join(',')}
          </>
        )
      ) : (
        <></>
      );
    }

    rhsContent.push(
      <>
      <b>{conditionRes?.[0]?.terms} : </b>
      {conditionRes?.[0]?.terms === "SHIPPMENT TERMS"
        ? `${plantDetails?.shipmentTerms}, ${plantDetails?.deliveryTerms}`
        : plantDetails?.deliveryTerms}
    </>
    
    );
    {
      plantDetails?.saleOrderItems[0]?.buyerAddress.replace(/,/g, '') !=
      plantDetails?.saleOrderItems[0]?.deliveryaddress.replace(/,/g, '') ? (
        rhsContent.push(
          <>
            <b>
              <u>Shipp to:</u>
            </b>
            {plantDetails?.saleOrderItems[0]?.deliveryaddress}
          </>
        )
      ) : (
        <></>
      );
    }
  }
  console.log(ConstrunctLhsContent(plantDetails));

  const uniqueSizes = new Set();

plantDetails?.gradeInfo.forEach(g => {
  g.info.forEach(r => {
    uniqueSizes.add(`${r.minGrade}/${r.maxGrade}`);
  });
});
const sizeString = Array.from(uniqueSizes).join(', ');

  let lhsCount = lhsContent.length;
  let rhsCount = rhsContent.length;
  const lhsRowSpanMap = new Map<number, number>();
  const lhsRowSpanCopyMap = new Map<number, number>();
  const blockSpanSize = Math.round(rhsCount / lhsCount);
  const blockSpanSizeRem = Math.round(rhsCount % lhsCount);
  let rowNumber = 1;
  let index=0; //1
  let fulfilledCount = 0;
  while (lhsCount > 0) {
    if(index === 0) {
    lhsRowSpanMap.set(rowNumber, blockSpanSize);//1,5 
    lhsRowSpanCopyMap.set(rowNumber, blockSpanSize);//1 ,5 
    fulfilledCount = blockSpanSize;//5
  } else {
    const remaing = rhsCount - fulfilledCount;//9-5=4
    const breakDownVal = Math.round( remaing / lhsCount);//4/3=1
    lhsRowSpanMap.set(rowNumber, breakDownVal);//1,5 | 2,1
    lhsRowSpanCopyMap.set(rowNumber, breakDownVal);//1 ,5 | 2,1
    fulfilledCount =blockSpanSize+ breakDownVal;
    
  }
    index++;//1
    rowNumber++;//2
    lhsCount--;//1
  }

  // lhsRowSpanMap.set(1, blockSpanSize + blockSpanSizeRem);
  // lhsRowSpanCopyMap.set(1, blockSpanSize + blockSpanSizeRem);
  let lhsPrintingRowNumber = 1;
  let lhsPrintingIndexNumber = 0;

  // const getCssFromComponent = (fromDoc, toDoc) => {
  //   Array.from(fromDoc.styleSheets).forEach((styleSheet: any) => {
  //     if (styleSheet.cssRules) { // true for inline styles
  //       const newStyleElement = toDoc.createElement('style');
  //       Array.from(styleSheet.cssRules).forEach((cssRule: any) => {
  //         newStyleElement.appendChild(toDoc.createTextNode(cssRule.cssText));
  //       });
  //       toDoc.head.appendChild(newStyleElement);
  //     }
  //   });
  // };

  const getCssFromComponent = (fromDoc: Document, toDoc: Document) => {
    Array.from(fromDoc.styleSheets).forEach((styleSheet: CSSStyleSheet) => {
      try {
        if (styleSheet?.cssRules) { // true for inline styles and same-origin stylesheets
          const newStyleElement = toDoc.createElement("style");
          Array.from(styleSheet.cssRules).forEach((cssRule: CSSRule) => {
            newStyleElement.appendChild(toDoc.createTextNode(cssRule.cssText));
          });
          toDoc.head.appendChild(newStyleElement);
        }
      } catch (e) {
        console.warn("Could not access stylesheet rules for", styleSheet.href, e);
      }
    });
  };
  
  const printOrder = () => {
    const divContents = document.getElementById('printme').innerHTML;
    const secondPageContents = document.getElementById('secondPage').innerHTML;
    const element = window.open('', '', 'height=700, width=1024');
  
    element.document.write(`
      <html>
        <head>
          <style>
            @media print {
              .page-break {
                page-break-before: always;
              }
      
              .no-page-break {
                page-break-inside: avoid;
              }
      
              #printme, #secondPage, #thirdPage, #forthPage {
                page-break-after: always;
              }
      
              /* Add this rule to ensure text is not transformed */
              body, div, p, span, b, h1, h2, h3, h4, h5, h6 {
                text-transform: none;
              }
      
              /* Vertically center content */
              #secondPage {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                height: 100vh;
                text-align: center;
                font-weight: bold;
              }
                .rhombus{
                  width:40px !important;
                  height:40px !important;
                }
            }
          </style>
        </head>
        <body>
          <div id="printme">${divContents}</div>
          <div id="secondPage" class="page-break">${secondPageContents}</div>
        </body>
      </html>
    `);
  
    getCssFromComponent(document, element.document);
    element.document.close();
    setTimeout(() => {
      element.print();
      element.close(); // to close window when click on cancel/Save
    }, 1000);
  };
  let totalInvoiceAmount = 0;

  const hasBundelCategory = plantDetails?.gradeInfo?.some(e => 
    e.info.some(val => val?.bundelCategory === true)
  );  return (
    <div>
<div style={{ textAlign: 'right' }}>
  <Button onClick={printOrder} style={{ backgroundColor: '#87CEEB', color: 'white' }}>
    <PrinterOutlined /> Print
  </Button>
</div>
      <br />
      {plantDetails ? (
        <html>
          <head></head>
          <br />
          <body >
         <div id="printme">
            <br></br>
            <table
              className={'ta-b styleInfo'}
              style={{ width: '100%' }}
              id="table-to-xls"
            >
              <tr>
                <td
                  className={'ta-b'}
                  colSpan={9}
                  style={{
                    textAlign: 'center',
                    fontSize: '12px',
                    lineHeight: '12px',
                    paddingTop: '10px',
                  }}
                >
                  <h1>CUSTOMS INVOICE</h1>
                </td>
              </tr>
              {plantDetails?.isTaxApplicable === 'YES' ? (
                <tr>
                  <td
                    className={'ta-b'}
                    colSpan={9}
                    style={{ textAlign: 'center' }}
                  >
                    <h2>
                      "SUPPLY MEANT FOR EXPORT UNDER LETTER OF UNDERTAKING WITH
                      PAYMENT OF IGST"
                    </h2>
                  </td>
                </tr>
              ) : (
                <tr>
                  <td
                    className={'ta-b'}
                    colSpan={9}
                    style={{ textAlign: 'center' }}
                  >
                    <h2>
                      "SUPPLY MEANT FOR EXPORT UNDER LETTER OF UNDERTAKING WITHOUT
                      PAYMENT OF IGST"
                    </h2>
                  </td>
                </tr>
              )}
              {rhsContent.map((r, i) => {
                let currRowSpanConsumption = lhsRowSpanMap.get(
                  lhsPrintingRowNumber
                ); // 3
                let currRowSpanReducedCons = lhsRowSpanCopyMap.get(
                  lhsPrintingRowNumber
                ); // 3/2
                lhsRowSpanCopyMap.set(
                  lhsPrintingRowNumber,
                  currRowSpanReducedCons - 1
                ); // 2/1

                if (Number(currRowSpanReducedCons) - 1 === 0) {
                  lhsPrintingIndexNumber++;
                  lhsPrintingRowNumber++;
                }

                return (
                  <>
                    <style>
                      {
                        `
                        .rhombus{
                          width:70px;
                          border:2px solid black;
                          height:70px;
                          transform:rotate(340deg) skew(45deg) scaleY(cos(45deg)); 
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          margin: 0 auto;
                        }
                        .rhombus div {
                          transform: rotate(45deg);
                          font-size:larger;
                        }
             
                        `
                      }
                    </style>
                    <tr>
                      <td
                        colSpan={5}
                        className={'ta-b'}
                        rowSpan={currRowSpanConsumption}
                        style={{
                          display:
                            currRowSpanConsumption === currRowSpanReducedCons
                              ? ''
                              : 'none',
                        }}
                      >
                        {lhsContent[lhsPrintingIndexNumber]}
                      </td>
                      <td className={'ta-b'} colSpan={5}>
                        {r}
                      </td>
                    </tr>
                  </>
                );
              })}
             

              <tr>
                <td
                  className={'ta-b'}
                  colSpan={9}
                  style={{
                    textAlign: 'center',
                  }}
                >
                  <b>{conditionRes?.[0]?.poLabel} : </b>{' '}
                  {plantDetails.custPoNo}{' '}
                  <b>Date : </b>{' '}
                  {moment(plantDetails.poDate).format('DD-MM-YYYY')}
                  </td>
              </tr>
              
              <tr>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>Pre Carriage By</b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>Vessel No</b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>Port Of Loading</b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>Port Of Discharge</b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}} colSpan={2}>
                  <b>
                    {conditionRes?.[0]?.destinationDetails
                      ? conditionRes?.[0]?.destinationDetails
                      : ''}
                  </b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}} colSpan={2}>
                  <b>Terms & Payments</b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>Origin Of Goods</b>
                </td>
              </tr>
              <tr>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  {/* {plantDetails?.vesselName} */}
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}> 
                  {/* {plantDetails?.vesselNumber} */}
                  </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>
                    {plantDetails?.portofloading
                      ? plantDetails?.portofloading?.toUpperCase() 
                      : ''}
                  </b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  {(plantDetails?.saleOrderItems[0]?.destinationDetails
                    ? plantDetails?.saleOrderItems[0]?.destinationDetails?.toUpperCase()
                    : '') +
                    ',' +
                    (plantDetails?.country ? plantDetails?.country : '')}
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}} colSpan={2}>
                  {(plantDetails?.saleOrderItems[0]?.destinationDetails
                    ? plantDetails?.saleOrderItems[0]?.destinationDetails?.toUpperCase()
                    : '') +
                    ',' +
                    (plantDetails?.country ? plantDetails?.country : '')}
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}} colSpan={2}>
                  {plantDetails?.saleOrderItems[0]?.paymentTerms}
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}} colSpan={1}>
                  INDIA
                </td>
              </tr>
              <tr>
              <td className={'ta-b'} style={{textAlign: "center"}}>
                <b>Marks & Nos.</b>
                {plantDetails?.endCustomerName === "KITAJIMA SUISAN CO., LTD." && (
                  <div className='rhombus'></div>
                )}
                {plantDetails?.endCustomerName === "M/S HANWA COMPANY LTD. , " && (
                  <div className='rhombus'>
                    <div><b>HK</b></div>
                  </div>
                )}
              </td>

                <td
                  className={'ta-b'}
                  style={{textAlign:"center"}}
                  colSpan={plantDetails?.isItem === true ? 2 : 3}
                >
                  <b>Description Of Goods</b>
                </td>
                {plantDetails?.isItem === true ? (
                  <>
                    <td className={'ta-b'} style={{textAlign:"center"}} colSpan={1} >
                      <b>Item Code</b>
                    </td>
                  </>
                ) : (
                  <></>
                )}
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>Size</b>
                </td>
                {hasBundelCategory?
                (<td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>No.Of Bundels</b>
                </td>):
                  (<td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>No.Of Cartons</b>
                </td>)}
                <td
                  className={'ta-b'}
                  colSpan={1}
                  style={{ textAlign: 'center', borderBottom: '0px' }}
                >
                  <b>
                    {' '}
                    Quantity{' '}
                    <br/> ( IN KGS )
                    {/* {conditionRes?.[0]?.quantityUom === true
                      ? ' ( IN LBS ) '
                      : ' ( IN KGS ) '} */}
                  </b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>
                    Price USD/KG
                    {/* {conditionRes?.[0]?.quantityUom === true ? 'LB' : 'KG'} */}
                  </b>
                </td>
                <td className={'ta-b'} style={{textAlign:"center"}}>
                  <b>
                    Amount IN USD{' '}
                    {conditionRes?.[0]?.amountParam === true
                      ? plantDetails.shipmentTerms
                      : ''}
                    {/* {
                    plantDetails?.country === 'CANADA' || plantDetails?.country === 'USA' || plantDetails?.country === 'UAE' ? <>
                    </> : <>{plantDetails?.shipmentTerms}</>
                  } <br />  */}
                  </b>
                </td>
              </tr>
              {
                // let totalRowSpan = 0;
                plantDetails?.gradeInfo?.map((g, prodIndex) => {
                  let prodRowSpan = containerProductLevelRowSpan.get(prodIndex);
                  return g?.info?.map((r, index) => {
                  
                    let freightCharges =
                      plantDetails?.freightCharges === undefined
                        ? 0
                        : plantDetails?.freightCharges;
                    let exchangeRate =
                      plantDetails?.exchangeRate === undefined
                        ? 0
                        : plantDetails?.exchangeRate;
                    totalCases += r.noOfCases;
                    const uom = UnitsOfWeightInput.find(
                      (uom) => uom.value == r.uomId
                    );
                    const uomPrice = UnitsOfWeightInput.find(
                      (uom) => uom.value == r.priceUom
                    );
                    let finalNetWeight;
                    let unitPrice;
                    let invUnitPrice;
                    if (plantDetails.isInvoiced == GlobalStatus.YES) {
                      if (uomPrice.name == UomEnum.LB || uomPrice.name == UomEnum.OZ) {
                        unitPrice = (Number(r.price) / 0.454).toFixed(5);
                      }else{
                        unitPrice = (Number(r.price)).toFixed(5);
                      }
                      if (uom.name == UomEnum.LB || uom.name == UomEnum.OZ) {
                        {
                          (finalNetWeight = (
                                Number(r.quatity) * 0.454
                              ).toFixed(3));
                        }
                        // unitPrice = (Number(r.price) / 0.454).toFixed(5);
                        grossWeightInKg = (
                          Number(
                            plantDetails?.grossWeight
                              ? plantDetails?.grossWeight
                              : 0
                          ) * 0.454
                        ).toFixed(3);
                        frozenWeightInKg = (
                          Number(
                            plantDetails?.frozenWeight
                              ? plantDetails?.frozenWeight
                              : 0
                          ) * 0.454
                        ).toFixed(3);
                        netWeightInKgs += Number(r.quatity)*0.454
                        netWeightInLbs += Number(r.quatity)

                      } else {
                        {
                           (finalNetWeight = Number(r.quatity).toFixed(3));
                        }
                        // unitPrice = Number(r.price).toFixed(5);
                        grossWeightInKg = Number(
                          plantDetails?.grossWeight
                            ? plantDetails?.grossWeight
                            : 0
                        ).toFixed(3);
                        frozenWeightInKg = Number(
                          plantDetails?.frozenWeight
                            ? plantDetails?.frozenWeight
                            : 0
                        ).toFixed(3);
                        netWeightInKgs += Number(r.quatity)
                        netWeightInLbs += Number(r.quatity)/0.454
                      }
                    } 
                    else {
                      if (uom.name == UomEnum.LB || uom.name == UomEnum.OZ) {
                        {
                          (finalNetWeight = (
                                Number(r.quatity) * 0.454
                              ).toFixed(3));
                        }
                        // unitPrice = (Number(r.price) / 0.454).toFixed(5);
                        grossWeightInKg = (
                          Number(
                            plantDetails?.grossWeight
                              ? plantDetails?.grossWeight
                              : 0
                          ) * 0.454
                        ).toFixed(3);  
                        frozenWeightInKg = (
                          Number(
                            plantDetails?.frozenWeight
                              ? plantDetails?.frozenWeight
                              : 0
                          ) * 0.454
                        ).toFixed(3);
                        netWeightInKgs += Number(r.quatity)*0.454
                        netWeightInLbs += Number(r.quatity)
                      } else {
                        {
                          conditionRes?.[0]?.quantityUom === true
                            ? (finalNetWeight = (
                                Number(r.quatity) / 0.454
                              ).toFixed(3))
                            : (finalNetWeight = Number(r.quatity).toFixed(3));
                        }
                        // unitPrice = Number(r.price).toFixed(5);
                        grossWeightInKg = Number(
                          plantDetails?.grossWeight
                            ? plantDetails?.grossWeight
                            : 0
                        ).toFixed(3);
                        frozenWeightInKg = Number(
                          plantDetails?.frozenWeight
                            ? plantDetails?.frozenWeight
                            : 0
                        ).toFixed(3);
                        netWeightInKgs += Number(r.quatity)
                        netWeightInLbs += Number(r.quatity)/0.454
                      }
                    }
                    {conditionRes[0]?.isRevisedPrice === true? (
                      // conditionRes?.[0]?.quantityUom === true?

                      (uomPrice.name == UomEnum.LB || uomPrice.name == UomEnum.OZ?(
                        unitPrice = (Number(r.revisedPrice ? r.revisedPrice : 0)/Number(0.454)).toFixed(5)):
                      (unitPrice = Number(r.revisedPrice ? r.revisedPrice : 0).toFixed(5)))
                      
                      
                    ): (
                      (uomPrice.name == UomEnum.LB || uomPrice.name == UomEnum.OZ?(
                        unitPrice = (Number(r.revisedPrice ? r.revisedPrice : 0)/Number(0.454)).toFixed(5)):
                      (unitPrice = Number(r.revisedPrice ? r.revisedPrice : 0).toFixed(5)))
                      )}
                    // totalLbWeight += Number(finalNetWeight);
                    // totalAmount += Number(Number(invUnitPrice) * Number(finalNetWeight));
                    
                    totalLbWeight += Number(finalNetWeight);
                    totalAmount += Number(
                      Number(unitPrice) * Number(finalNetWeight)
                    );
                    totalInvoiceAmount += Number(r.invoiceAmount);

                    // console.log(totalInvoiceAmount,"totalInvoiceAmount")
                    // console.log( plantDetails.freightCharges,"frieghtCharges")
                    // console.log( totalInvoiceAmount -
                    //   Number(
                    //     plantDetails.freightCharges
                    //       ? plantDetails.freightCharges
                    //       : 0
                    //   ),"subtotal")
subTotal = Number(
                          totalInvoiceAmount -
                              Number(
                                plantDetails.freightCharges
                                  ? plantDetails.freightCharges
                                  : 0))
                    // {
                    //   conditionRes?.[0]?.cvd === true
                    //     ? (subTotal = Number(
                    //       totalInvoiceAmount -
                    //           Number(
                    //             plantDetails.freightCharges
                    //               ? plantDetails.freightCharges
                    //               : 0
                    //           )
                    //       ))
                    //     : 0;
                    // }
                    {
                      conditionRes?.[0]?.cvd === true
                        ? (cvdVal = (
                            Number(subTotal) * Number(cvdDetails / 100)
                          ).toFixed(2)  )                     
                        : 0;
                    }
                  
                    {
                      conditionRes?.[0]?.cvd === true
                        ? (antiDumping = (subTotal * (1.35 / 100)).toFixed(2))
                        : conditionRes?.[0]?.freightRate === true
                        ? (antiDumping = Number(
                            Number(
                              totalInvoiceAmount -
                                Number(
                                  plantDetails.freightCharges
                                    ? plantDetails.freightCharges
                                    : 0
                                )
                            ) *
                              (1.35 / 100)
                          ).toFixed(2))
                        : (antiDumping = (
                            Number(totalInvoiceAmount) *
                            (1.35 / 100)
                          ).toFixed(2));
                    }
                      {conditionRes?.[0]?.cvd === true&&plantDetails?.deliveryTerms.includes('DDP') ?(
                      
                      mpfVal= Number(((subTotal)-(Number(cvdVal?cvdVal:0))-Number(antiDumping?antiDumping:0))* Number(mpfDetails / 100)).toFixed(4),
                      tariffVal = Number(((subTotal)-(Number(mpfVal?mpfVal:0))-(Number(cvdVal?cvdVal:0))-Number(antiDumping?antiDumping:0) )* Number(tariffDetails / 100)).toFixed(4)
                    ):(<></>)}
                   
  //                   const isDDP = plantDetails?.deliveryTerms.includes('DDP');
  // const hasAntiDumping = conditionRes?.[0]?.antiDumping === true && conditionRes?.[0]?.freightRate === true;
  // const hasCVD = conditionRes?.[0]?.cvd === true && conditionRes?.[0]?.freightRate === true;

  // Calculate combined percentages if DDP is present
  const combinedPercentage = plantDetails?.deliveryTerms.includes('DDP')
    ? 1.35 + Number(cvdDetails || 0) + Number(mpfDetails || 0) + Number(tariffDetails || 0)
    : 0;

  const subTotalValue = Number(subTotal || 0);
  const taxOnSubtotal = (subTotalValue * combinedPercentage);
  const taxBase = 100 + combinedPercentage;
  const totalvalue=taxOnSubtotal/taxBase
 {
                      conditionRes?.[0]?.cvd === true && plantDetails?.deliveryTerms.includes('DDP')
                        ? (fob =
                            Number(subTotal ? subTotal : 0) - Number(totalvalue)
                            
                          ): conditionRes?.[0]?.cvd === true?(fob =
                            Number(subTotal ? subTotal : 0)-
                            Number(antiDumping ? antiDumping : 0) -
                            Number(cvdVal ? cvdVal : 0)-
                            (plantDetails?.deliveryTerms.includes('DDP') ?Number(mpfVal ? mpfVal : 0):0)-
                            (plantDetails?.deliveryTerms.includes('DDP') ?Number(tariffVal ? tariffVal : 0):0)

                            
                          )
                          
                        : conditionRes?.[0]?.freightRate === true
                        ? (fob = Number(
                            totalInvoiceAmount -
                              Number(
                                plantDetails.freightCharges
                                  ? plantDetails.freightCharges
                                  : 0
                              ) 
                          ).toFixed(2))
                        : (fob = Number(
                            totalInvoiceAmount 
                          ).toFixed(2));
                    }
                    return (
                      <tr key={index}>
                        {plantDetails?.modeOfExport === ModeOfExportEnum.FLIGHT?(
                          <td className="ta-b" style={{textAlign:"center"}}>
                            {r.marksAndNo}
                          </td>
                        ):(
                          <td
                          className="ta-b"
                          rowSpan={totalContainersRowSpan}
                          style={{
                            display:
                              totalContainersRowSpan-- == copiedContainerRowSpan
                                ? ''
                                : 'none'
                          }}
                        >
                          <b>Container No:</b>
                          {plantDetails?.saleOrderItems[0]?.containerNo}
                          <br />
                          <hr />
                          <b>Seal No:</b>
                          {/* {plantDetails?.saleOrderItems[0]?.linearSelaNo} */}
                        </td>
                        )}
                       
                        <td
                          className="ta-b"
                          rowSpan={containerProductLevelRowSpan.get(prodIndex)}
                          colSpan={plantDetails?.isItem === true ? 2 : 3}
                          style={{
                            display:
                              prodRowSpan-- ==
                              containerProductLevelRowSpan.get(prodIndex)
                                ? ''
                                : 'none',textAlign:"center"
                          }}
                        >
                          {g.productDescription}
                        </td>
                        {plantDetails?.isItem === true ? (
                          <td className="ta-b" style={{textAlign:"center"}}>{r.itemCode}</td>
                        ) : (
                          <></>
                        )}
                        <td className="ta-b" style={{textAlign:"center"}}>
                          {r.gradeNames}
                          {r.grade && (
                            <>
                              <br />({r.grade})
                            </>
                          )}
                        </td>
{hasBundelCategory?(
                        <td className="ta-b" style={{textAlign:"center"}}>{r.noOfBundels}</td>
                      ):(
                        <td className="ta-b" style={{textAlign:"center"}}>{r.noOfCases}</td>
                      )}
                        {/* <td className="ta-b" style={{textAlign:"center"}}>{r.noOfCases}</td> */}
                        <td className="ta-b" style={{textAlign:"center"}}>
                          {finalNetWeight
                            ? Number(finalNetWeight).toLocaleString(undefined, {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2,
                              })
                            : 0}
                        </td>
                        <td className="ta-b" style={{textAlign:"center"}}>{unitPrice}</td>
                        <td className="ta-b" style={{textAlign:"center"}}>
                          {r.invoiceAmount}
                          {/* {Number(
                            Number(invUnitPrice) * Number(finalNetWeight)
                          )?.toLocaleString(undefined, {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2,
                          })} */}
                        </td>
                      </tr>
                    );
                  });
                })
              }

              
              <tr>
                <td className={'ta-b'}>
                  <b>Net Weight</b>
                </td>

                
                {conditionRes?.[0]?.lbParam == true ? (
                  <td className={'ta-b'}>
                     {Number(netWeightInLbs)?.toFixed(2)}
                    (LBS)
                  </td>
                ) : (
                  <td className={'ta-b'}></td>
                )}
                <td className={'ta-b'}>
                  {Number(netWeightInKgs)?.toFixed(2)}
                  (KGS)
                </td>
                {conditionRes?.[0]?.isHsn === true ? (
                  <td
                    className={'ta-b'}
                    rowSpan={conditionRes?.[0]?.frozenWeight === true ? 3 : 2}
                  >
                    <b>HSN Code: </b>
                    {[...new Set(plantDetails?.saleOrderItems?.map((item) => item.foodTypeHsnCode))].map((foodTypeHsnCode) => {
  return (
    <>
      <span>{foodTypeHsnCode}</span>
      <br />
    </>
  );
})}

                  </td>
                ) : (
                  <td
                    className={'ta-b'}
                    rowSpan={conditionRes?.[0]?.frozenWeight === true ? 3 : 2}
                  ></td>
                )}

                {conditionRes[0]?.blNo === true ? (
                  <>
                    <td className={'ta-b'}>
                      <b>Total</b>
                    </td>
                    <td className={'ta-b'}>{totalCases}</td>
                    <td className={'ta-b'}>
                      {totalLbWeight
                        ? Number(totalLbWeight)?.toLocaleString(undefined, {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2,
                          })
                        : 0}
                    </td>
                    <td className={'ta-b'}></td>
                    <td className={'ta-b'}>
                      {Number(totalAmount)?.toLocaleString(
                        CrrencySymbols.find(
                          (item) =>
                            item.name ==
                            plantDetails?.saleOrderItems[0]?.currencyDetails
                        )?.locale,
                        { minimumFractionDigits: 2, maximumFractionDigits: 2 }
                      )}
                    </td>
                  </>
                ) : (
                  <>
                    <td className={'ta-b'}></td>
                    <td className={'ta-b'}></td>
                    <td className={'ta-b'}></td>
                    <td className={'ta-b'}></td>
                    <td className={'ta-b'}></td>
                  </>
                )}
              </tr>
             
              {conditionRes?.[0]?.frozenWeight === true ? (
                <tr>
                  <td className={'ta-b'}>
                    <b>Frozen Weight</b>
                  </td>
                
                  {conditionRes?.[0]?.lbParam == true ? (
                    <td className={'ta-b'}>
                      {Math.round(
                        frozenWeightInKg / 0.454
                      )?.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2,
                      })}
                      (LBS)
                    </td>
                  ) : (
                    <td className={'ta-b'}></td>
                  )}
                    <td className={'ta-b'}>
                    {Math.round(frozenWeightInKg)?.toLocaleString('en-US', {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2,
                    })}
                    (KGS)
                  </td>
                  {conditionRes?.[0]?.blNo == true ? (
                    <></>
                  ) : (
                    <>
                      <td className={'ta-b'}></td>
                      <td className={'ta-b'}></td>
                      <td className={'ta-b'}></td>
                      <td className={'ta-b'}></td>
                    </>
                  )}
                </tr>
              ) : (
                ''
              )}
              <tr>
                <td className={'ta-b'}>
                  <b>Gross Weight</b>
                </td>

                {conditionRes?.[0]?.lbParam == true ? (
                  <td className={'ta-b'}>
                    {Math.round(
                      grossWeightInKg / 0.454
                    )?.toLocaleString('en-US', {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2,
                    })}
                    (LBS)
                  </td>
                ) : (
                  <td className={'ta-b'}></td>
                )}
                
                <td className={'ta-b'}>
                  {Math.round(grossWeightInKg)?.toLocaleString('en-US', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  })}
                  (KGS)
                </td>
                {conditionRes?.[0]?.blNo == true ? (
                  <>
                    <td
                      className={'ta-b'}
                      colSpan={5}
                      rowSpan={conditionRes?.[0]?.frozenWeight === true ? 2 : 1}
                    >
                      <b>BILL OF LADING NO:</b>
                      {plantDetails?.saleOrderItems[0]?.billOfLadingno}
                    </td>
                  </>
                ) : (
                  <>
                    <td className={'ta-b'}>
                      <b>Total</b>
                    </td>
                    <td className={'ta-b'} style={{textAlign:"center"}}>{totalCases}</td>
                    <td className={'ta-b'} style={{textAlign:"center"}}>
                      {totalLbWeight
                        ? Number(totalLbWeight)?.toLocaleString(undefined, {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2,
                          })
                        : 0}
                    </td>
                    <td className={'ta-b'}></td>
                    <td className={'ta-b'} style={{textAlign:"center"}}>
                    {Number(totalInvoiceAmount).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}
                      {/* {Number(totalAmount)?.toLocaleString(
                        CrrencySymbols.find(
                          (item) =>
                            item.name ==
                            plantDetails?.saleOrderItems[0]?.currencyDetails
                        )?.locale,
                        { minimumFractionDigits: 2, maximumFractionDigits: 2 }
                      )} */}
                    </td>
                  </>
                )}
              </tr>
              <tr>
                <td
                  className={'ta-b'}
                  colSpan={9}
                  style={{
                    textAlign: 'center',
                     }}
                >
                  <b>
                  (TOTAL U.S. Dollars&nbsp;&nbsp;:&nbsp;&nbsp;
                  {totalInvoiceAmount !== undefined 
                    ? (totalInvoiceAmount === 0 
                    ? "ZERO" 
                   : toWords.convert(totalInvoiceAmount, { currency: true }).toUpperCase())
                   : ''}
                   )
                  </b>
                </td>
              </tr>

              {conditionRes?.[0]?.freightRate === true ? (
                <tr>
                  <td
                    className={'ta-b'}
                    colSpan={5}
                    style={{
                      textAlign: 'right',
                      }}
                  >
                    <b>PREPAID FREIGHT IN USD:</b>
                  </td>
                  <td
                    className={'ta-b'}
                    colSpan={4}
                    style={{
                      textAlign: 'left',
                     }}
                  >
                    <b>
                      {plantDetails?.saleOrderItems[0]?.currencyDetails +
                      ' : ' +
                      plantDetails?.freightCharges
                        ? plantDetails?.freightCharges
                        : 0}
                    </b>
                  </td>
                </tr>
              ) : (
                ''
              )}
                <tr>
                  <td
                    className={'ta-b'}
                    colSpan={5}
                    style={{
                      textAlign: 'right',
                      }}
                  >
                    <b>SUB TOTAL:</b>
                  </td>
                  <td
                    className={'ta-b'}
                    colSpan={4}
                    style={{
                      textAlign: 'left',
                      }}
                  >
                    <b>{Number(subTotal).toFixed(2)}</b>
                  </td>
                </tr>
              {/* {conditionRes?.[0]?.cvd === true &&
              conditionRes?.[0]?.freightRate === true ? (
              
              ) : (
                ''
              )} */}
              {(() => {
  const isDDP = plantDetails?.deliveryTerms.includes('DDP');
  const hasAntiDumping = conditionRes?.[0]?.antiDumping === true && conditionRes?.[0]?.freightRate === true;
  const hasCVD = conditionRes?.[0]?.cvd === true && conditionRes?.[0]?.freightRate === true;

  // Calculate combined percentages if DDP is present
  const combinedPercentage = isDDP
    ? 1.35 + Number(cvdDetails || 0) + Number(mpfDetails || 0) + Number(tariffDetails || 0)
    : 0;

  const subTotalValue = Number(subTotal || 0);
  const taxOnSubtotal = (subTotalValue * combinedPercentage);
  const taxBase = 100 + combinedPercentage;
  const totalvalue=taxOnSubtotal/taxBase

  return (
    <>
      { conditionRes?.[0]?.antiDumping === true && conditionRes?.[0]?.freightRate === true && (
        <tr>
          <td className="ta-b" colSpan={5} style={{ textAlign: 'right' }}>
            <b>ANTI DUMPING DUTY @1.35%:</b>
          </td>
          <td
            className="ta-b"
            colSpan={isDDP ?2:4}
            rowSpan={isDDP ? 4 : 1}
            style={{ textAlign: 'left', verticalAlign: isDDP ? 'middle' : 'top', }}
          >
            <b>
            {isDDP
      ? `${subTotalValue} * ${combinedPercentage} / ${taxBase}`
      : antiDumping
      ? Number(antiDumping).toFixed(2)
      : 0}
            </b>
          </td>
          {isDDP
      ? <>
      <td  className="ta-b"
            colSpan={2}
            rowSpan={isDDP ? 4 : 1}
            style={{ textAlign: 'left', verticalAlign: isDDP ? 'middle' : 'top', }}>
            <b>{totalvalue.toFixed(2)}</b>
            </td>
      </>
      : <></>}
        </tr>
      )}

      {conditionRes?.[0]?.cvd === true && conditionRes?.[0]?.freightRate === true && (
        <tr>
          <td className="ta-b" colSpan={5} style={{ textAlign: 'right' }}>
            <b>CVD @ {cvdDetails}%:</b>
          </td>
          {!isDDP && (
            <td className="ta-b" colSpan={4} style={{ textAlign: 'left' }}>
              <b>{cvdVal ? Number(cvdVal).toFixed(2) : 0}</b>
            </td>
            
          )}
        </tr>
      )}

      {conditionRes?.[0]?.cvd === true && plantDetails?.deliveryTerms.includes('DDP') && (
        <tr>
          <td className="ta-b" colSpan={5} style={{ textAlign: 'right' }}>
            <b>MPF & HARBOUR MAINTAINCE @ {mpfDetails}%:</b>
          </td>
          {!plantDetails?.deliveryTerms.includes('DDP') && (
            <td className="ta-b" colSpan={4} style={{ textAlign: 'left' }}>
              <b>{mpfVal ? Number(mpfVal).toFixed(2) : 0}</b>
            </td>
          )}
        </tr>
      )}

      {conditionRes?.[0]?.cvd === true && plantDetails?.deliveryTerms.includes('DDP') && (
        <tr>
          <td className="ta-b" colSpan={5} style={{ textAlign: 'right' }}>
            <b>RECIPROCAL TARIFF @ {tariffDetails}%:</b>
          </td>
          {!plantDetails?.deliveryTerms.includes('DDP') && (
            <td className="ta-b" colSpan={4} style={{ textAlign: 'left' }}>
              <b>{tariffVal ? Number(tariffVal).toFixed(2) : 0}</b>
            </td>
          )}
        </tr>
      )}

      {/* <tr>
        <td className="ta-b" colSpan={5} style={{ textAlign: 'right' }}>
          <b>SUB TOTAL:</b>
        </td>
        <td className="ta-b" colSpan={4} style={{ textAlign: 'left' }}>
          <b>{Number(subTotal).toFixed(2)}</b>
        </td>
      </tr> */}
    </>
  );
})()}

               {/* {conditionRes?.[0]?.antiDumping === true &&
              conditionRes?.[0]?.freightRate === true ? (
              <tr>
                <td
                  className={'ta-b'}
                  colSpan={5}
                  style={{
                    textAlign: 'right',
                    }}
                >
                  <b>ANTI DUMPING DUTY @1.35%:</b>
                </td>
                <td
                  className={'ta-b'}
                  colSpan={4}
                  style={{
                    textAlign: 'left',
                     }}
                >
                  <b>{antiDumping ? Number(antiDumping).toFixed(2) : 0}</b>
                </td>
              </tr> ) : (
                ''
              )}
              {conditionRes?.[0]?.cvd === true &&
              conditionRes?.[0]?.freightRate === true ? (
                <tr>
                  <td
                    className={'ta-b'}
                    colSpan={5}
                    style={{
                      textAlign: 'right',
                      }}
                  >
                    <b>CVD @ {cvdDetails}%:</b>
                  </td>
                  <td
                    className={'ta-b'}
                    colSpan={4}
                    style={{
                      textAlign: 'left',
                      }}
                  >
                    <b>{cvdVal ? Number(cvdVal).toFixed(2) : 0}</b>
                  </td>
                </tr>
              ) : (
                ''
              )}
               {conditionRes?.[0]?.cvd === true &&
              plantDetails?.deliveryTerms.includes('DDP') ? (
                <tr>
                  <td
                    className={'ta-b'}
                    colSpan={5}
                    style={{
                      textAlign: 'right',
                      }}
                  >
                    <b>MPF & HARBOUR MAINTAINCE @ {mpfDetails}%:</b>
                  </td>
                  <td
                    className={'ta-b'}
                    colSpan={4}
                    style={{
                      textAlign: 'left',
                      }}
                  >
                    <b>{mpfVal ? Number(mpfVal).toFixed(2) : 0}</b>
                  </td>
                </tr>
              ) : (
                ''
              )}
               {conditionRes?.[0]?.cvd === true &&
              plantDetails?.deliveryTerms.includes('DDP') ? (
                <tr>
                  <td
                    className={'ta-b'}
                    colSpan={5}
                    style={{
                      textAlign: 'right',
                      }}
                  >
                    <b>RECIPROCAL TARIFF @ {tariffDetails}%:</b>
                  </td>
                  <td
                    className={'ta-b'}
                    colSpan={4}
                    style={{
                      textAlign: 'left',
                      }}
                  >
                    <b>{tariffVal ? Number(tariffVal).toFixed(2) : 0}</b>
                  </td>
                </tr>
              ) : (
                ''
              )} */}
              <tr>
                <td
                  className={'ta-b'}
                  colSpan={5}
                  style={{
                    textAlign: 'right',
                     }}
                >
                  <b>FOB VALUE IN USD :</b>
                </td>
                <td
                  className={'ta-b'}
                  colSpan={4}
                  style={{
                    textAlign: 'left',
                     }}
                >
                  <b>{fob ? Number(fob).toFixed(2) : 0}</b>
                </td>
              </tr>
              <tr>
                <td
                  className={'ta-b'}
                  colSpan={5}
                  style={{
                    textAlign: 'right',
                     }}
                >
                  <b>
                    FOB VALUE IN INR (EXCHANGE RATE:-Rs.
                    {plantDetails?.exchangeRate}):{' '}
                  </b>
                </td>
                <td
                  className={'ta-b'}
                  colSpan={4}
                  style={{
                    textAlign: 'left',
                     }}
                >
                  <b>
                    {fob
                      ? Number(
                          fob * Number(plantDetails?.exchangeRate)
                        ).toFixed(2)
                      : 0}
                  </b>
                </td>
              </tr>
              <tr>
                <td
                  className={'ta-b'}
                  colSpan={5}
                  style={{
                    textAlign: 'right',
                     }}
                >
                  <b>
                    INVOICE VALUE IN INR (EXCHANGE RATE:-Rs.
                    {plantDetails?.exchangeRate}):
                  </b>
                </td>
                <td
                  className={'ta-b'}
                  colSpan={4}
                  style={{
                    textAlign: 'left',
                     }}
                >
                  <b>
                    {' '}
                    {Number(
                      Number(plantDetails?.exchangeRate) * Number(totalInvoiceAmount)
                    ).toFixed(2)}
                  </b>
                </td>
              </tr>
              <tr>
              <td
                  className={'ta-b'}
                  colSpan={9}
                >
                  <b style={{ textAlign: 'left' }}>PACKED & PROCESSED BY : </b>
                  <h4 style={{ display: 'inline', textAlign: 'left' }}>
                    {processingData?.company ? processingData?.company : ''}
                  </h4>
                  <br />
                  {processingData?.addressOne ? processingData?.addressOne + ',' : ''}
          <br />
          {processingData?.addressTwo
            ? processingData?.addressTwo + ' - ' + processingData?.postalCode
            : ''}
          <br />
          {processingData?.state + ', ' + processingData?.country}
                  <br />
                  <b style={{ textAlign: 'center' }}>APPROVAL NUMBER :</b>
                  {exportersPlant?.approvalNum}{' '}
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  {exportersPlant?.feiNumber ? (
                    <>
                      <b style={{ textAlign: 'center' }}>USFDA REGN NO:</b>
                      {exportersPlant?.consigneefdaRegNumber}
                    </>
                  ) : (
                    <></>
                  )}
                </td>

              </tr>
              <tr>
                <td
                  colSpan={9}
                  style={{
                    textAlign: 'left',
                    }}
                >
                  <div style={{paddingLeft:"8px"}}>
                  1&#41; WE HEREBY DECLARE THAT WE SHALL CLAIM THE BENEFITS
                  UNDER CUSTOMS NOTIFICATION NO.88/2017 CUSTOMS NOTIFICATION
                  DATED 21- 09-2017, AS WELL AS CHAPTER 3 OF FTP 2015-2020 AS
                  APPLICABLE. FISH AND CRUSTACEANS, MOLLUSCS AND OTHER AQUATIC
                  INVERTEBRATES.
                  <br /> 2&#41; THIS SHIPMENT IS MADE UNDER DUTY DRAW BACK
                  SCHEME AS WELL AS UNDER RODTEP SCHEME
                  <br />
                  3&#41; ITC HS CODE: 03061720 DRAW BACK SCHEME CODE: 19,SL.NO.
                  OF EXPORT PRODUCT: 03060101A, RATE OF ENTITLEMENT: 3.00% ON
                  FOB OR RS.23.60/KG CAP
                  </div>
                </td>
              </tr>
              <tr>
                <td
                  colSpan={9}
                  style={{
                    textAlign: 'left',
                    border: '1px solid black',
                    borderCollapse: 'collapse',
                    textTransform: 'uppercase',
                    paddingLeft:"8px"
                  }}
                >
                  <br />
                  <b> Q CERTIFICATE NO: </b>
                  {plantDetails?.qCertificateNo} 
                  <br />
                </td>
              </tr>
              {plantDetails?.isTaxApplicable === 'YES' ? (
                <>
                  <tr>
                    <th className={'ta-b'}>TAXABLE VALUE OF GOODS IN Rs.</th>
                    <th className={'ta-b'}>
                      TAX RATE(%) {plantDetails?.invoiceCategory}
                    </th>
                    <th className={'ta-b'}>
                      TAX (Rs.) {plantDetails?.invoiceCategory}
                    </th>
                    <th className={'ta-b'}>
                      TOTAL AMOUNT INCLUDING {plantDetails?.invoiceCategory} IN
                      INR
                    </th>
                  </tr>
                  {/* {plantDetails?.saleOrderItems.map((e)=>{ */}
                  {/* return( */}
                  <tr>
                    <td className={'ta-b'}>{Number(
                      Number(plantDetails?.exchangeRate) * Number(totalInvoiceAmount)
                    ).toFixed(2)}</td>
                    <td className={'ta-b'}>
                      {plantDetails?.saleOrderItems?.[0]?.taxPer}%
                    </td>
                    <td className={'ta-b'}>
                      {(Number(
                        Number(
                          Number(plantDetails?.exchangeRate) * Number(totalInvoiceAmount)
                        )*
                          Number(plantDetails?.saleOrderItems?.[0]?.taxPer)
                      ) / 100).toFixed(2)}
                    </td>
                    <td className={'ta-b'}>
                      {(Number(
                        Number(
                          Number(Number(
                      Number(plantDetails?.exchangeRate) * Number(totalInvoiceAmount)
                    ).toFixed(2)) *
                            Number(plantDetails?.saleOrderItems?.[0]?.taxPer)
                        ) / 100
                      ) + Number(Number(
                      Number(plantDetails?.exchangeRate) * Number(totalInvoiceAmount)
                    ).toFixed(2))).toFixed(2)}
                    </td>
                  </tr>
                  {/* ) */}
                  {/* })} */}
                </>
              ) : (
                ''
              )}
            {plantDetails.remarks && plantDetails.remarks !== '' ? (
  <tr>
    <td
      className={'ta-b'}
      colSpan={10}
      style={{ fontSize: '14px', paddingTop: '15px' }}
    >
      <p>
        <b>{plantDetails.remarks}</b>
      </p>
    </td>
  </tr>
) : null}
              <tr>
                <td
                  className={'ta-b'}
                  colSpan={9}
                  style={{
                    textAlign: 'left',
                    }}
                >
                  <div>
                      <b>BANK DETAILS : </b>
                    <br />
                    <b>NAME OF ACCOUNT : </b>
                    {plantDetails?.bankInfo?.[0]?.displayName
                      ? plantDetails.bankInfo[0].displayName
                      : ''}
                    <br />
                    <b>BANK NAME : </b>
                    {plantDetails?.bankInfo?.[0]?.bankName
                      ? plantDetails.bankInfo[0].bankName
                      : ''}
                    <br />
                    <b>BRANCH : </b>
                    {plantDetails?.bankInfo?.[0]?.branchName
                      ? plantDetails.bankInfo[0].branchName
                      : ''}{" "} {plantDetails?.bankInfo?.[0]?.bankAddress
                        ? plantDetails.bankInfo[0].bankAddress
                        : ''}
                    <br />
                    <b>CURRENT ACCOUNT NO : </b>
                    {plantDetails?.bankInfo?.[0]?.bankAcc
                      ? plantDetails.bankInfo[0].bankAcc
                      : ''}
                    <br />
                    <b>SWIFT CODE : </b>
                    {plantDetails?.bankInfo?.[0]?.swiftCode
                      ? plantDetails.bankInfo[0].swiftCode
                      : ''}
                    <br />
                    <b>IFSC CODE : </b>
                    {plantDetails?.bankInfo?.[0]?.ifscCode
                      ? plantDetails.bankInfo[0].ifscCode
                      : ''}
                    <br />
                    {/* <b>BANK ADRESS : </b>
                    {plantDetails?.bankInfo?.[0]?.bankAddress
                      ? plantDetails.bankInfo[0].bankAddress
                      : ''}
                    <br /> */}
                  </div>
                </td>
              </tr>
              <tr>
                <td colSpan={4} id="inputText">
                  {' '}
                  <div style={{paddingLeft:"8px"}}>
                    <b>Declaration</b>
                  </div>
                  <div style={{paddingLeft:"8px"}}>
                  {conditionRes?.[0]?.declaration}
                  </div>
                </td>
                <td colSpan={5} className={'ta-b'} style={{textAlign:'center'}}>
                  for <b>{exporterData?.company}</b>
                  <br />
                  <br />
                  <br />
                  <br />
                  <h4>
                    <b>AUTHORISED SIGNATORY</b>
                  </h4>
                </td>
              </tr>
          
            </table>
            </div>
            <br />
            <div
      id="secondPage"
      className="page-break"
      style={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        textAlign: 'center',
        fontWeight: 'bold',
      }}
    >
      {props.showStuffingCertificate && (
        <div>
          {/* <h1 style={{ fontSize: '24px' }}>STUFFING CERTIFICATE</h1>
          <br />
          <h3 style={{ fontSize: '20px' }}>
            WE HEREBY CERTIFY THAT DESCRIPTION, QUANTITY, VALUE OF GOODS COVERED BY THIS INVOICE / PACKING LIST NO: {plantDetails?.invoiceNumber} DT.{' '}
            {plantDetails?.invoiceDate ? moment(plantDetails?.invoiceDate).format('DD-MM-YYYY') : ''} HAS BEEN VERIFIED AND CHECKED THAT THE GOODS {totalCases} CARTONS FROZEN VANNAMEI SHRIMPS IS STUFFED IN MY PRESENCE
          </h3>
          <br />
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>CONTAINER NO</th>
                <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>SIZE</th>
                <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>SELF SEAL NO OTS</th>
                <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>NO OF PKG</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>{plantDetails?.saleOrderItems[0]?.containerNo}</td>
                <td style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>
                  {plantDetails?.containerSize}
                  </td>
                <td style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>{plantDetails?.eSeal}</td>
                <td style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}>{totalCases}</td>
              </tr>
            </tbody>
          </table> */}
        </div>
      )}
    </div>
          </body>
        </html>
      ) : (
        <Card
          title={
            <span
              style={{
                color: 'black',
                borderColor: 'black',
                borderStyle: 'initial',
                height: '100',
              }}
            >
              CUSTOMS INVOICE
            </span>
          }
          style={{ textAlign: 'center' }}
          headStyle={{ backgroundColor: '#69c0ff' }}
        >
          <span style={{ paddingTop: '10px', textAlign: 'center' }}>
            <Spin />
          </span>
        </Card>
      )}
    </div>
  );
}

export default CustomsInvoice;
