import { HarvestTypes } from '@gtpl/shared-models/common-models';
import { ExporterDataInput } from '@gtpl/shared-models/logistics';
import { RMInvoicePrintReq } from '@gtpl/shared-models/raw-material-procurement';
import { FactoriesInput } from '@gtpl/shared-models/sale-management';
import { RMGrnService } from '@gtpl/shared-services/raw-material-procurement';
import { Button, Card, Col, Form, Row } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';

export interface RMInvoiceProps {
  invoiceNumber: number;
}

const RMInvoicePrint = (props: RMInvoiceProps) => {
  const [rmInvoicePrint, setRMInvoicePrint] = useState<any>([]);
  const service = new RMGrnService();
  useEffect(() => {
    if (props.invoiceNumber) {
      console.log(props);
      getRMInvoice(props.invoiceNumber);
    }
  }, [props.invoiceNumber]);

  // let exporterDetails = ExporterDataInput;
  // let exporterId = 1;
  // const exporterData = exporterDetails.find(
  //   (item) => item.value == rmInvoicePrint?.exporterId ? rmInvoicePrint.exporterId : exporterId
  // );

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

  const getRMInvoice = (grnId) => {
    // const req=new SoFormSdfPrintDto()
    service.getRMInvoicePrint(new RMInvoicePrintReq(grnId)).then((res) => {
      if (res.status) {
        setRMInvoicePrint(res.data);
      }
    });
  };
  let exporterDetails = ExporterDataInput;
  const exporterData = exporterDetails.find(
    (item) => item.name == rmInvoicePrint?.[0]?.address 
  );
  const ammountInkgs = (rmInvoicePrint, ammount) => {
    return rmInvoicePrint.some(
      (item) => item.quantiy * item.approvedPrice === ammount
    );
  };

  // const getCssFromComponent = (fromDoc, toDoc) => {
  //   Array.from(fromDoc.styleSheets).forEach((styleSheet: any) => {
  //     console.log(styleSheet.cssRules);
  //     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 element = window.open('', '', 'height=700, width=1024');
    element.document.write(divContents);
    getCssFromComponent(document, element.document);
    element.document.close();
    setTimeout(() => {
      element.print();
      element.close(); // to close window when click on cancel/Save
// model should be open
    }, 1000);
  };

  // const printOrder = () => {
  //   // const printableElements = document.getElementById('printme').innerHTML;
  //   // const orderHTML = '<html><head><title></title></head><body>' + printableElements + '</body></html>'
  //   // const oldPage = document.body.innerHTML;
  //   // document.body.innerHTML = orderHTML;
  //   // // document.body.innerHTML = oldPage
  //   // window.print();
  //   // return;

  //   const divContents = document.getElementById('printme').innerHTML;
  //   // const secondPageContents = document.getElementById('secondPage').innerHTML;
  //   // const thirdPageContents = document.getElementById('thirdPage').innerHTML;
  //   // const forthPageContents = document.getElementById('forthPage').innerHTML;
  //   const element = window.open('', '', 'height=700, width=1024');
  //   const style = `
  //         <html>
  //           <head>
  //             <title></title>
  //             <style>
  //               @media print {
  //                 @page {
  //                   size: landscape;
  //                 }
  //                 .page-break { 
  //                   page-break-after: always;
  //                   page-break-before: always;
  //                 }
  //                 body {
  //                   width: 100%;
  //                 }
  //               }
  //               p {
  //                 font-size: 12px; /* Adjust the font size as needed */
  //               }
  //             </style>
  //           </head>
  //           <body class="page">${divContents}</body>
  //         </html>
  //       `;
  //   element.document.write(style);
  //   element.document.close();
  //   element.print();
  //   element.close();
  // };

  const calculateTotalquantity = (data) => {
    
    const total = data.reduce((total, item) => {
      let qty =0
      if (item.invoiceType?.toLowerCase()  === "defect" && item.defectQuantity != null && item.defectQuantity != undefined) {
        qty = Number(item.defectQuantity)
    } else if (item.harvestType === HarvestTypes.Re_Weighment && item.reweighmentQuantity != null && item.reweighmentQuantity != undefined) {
        qty = Number(item.reweighmentQuantity)
    } else {
        qty = Number(item.grnQuantity)
    }
      // const quantity=item?.harvestType=="Re Weighment"?Number(item?.reweighmentQuantity):Number(item?.grnQuantity)
      // const quantity = Number(item?.grnQuantity) || 0;
      return Number(total) + qty;
    }, 0);
  
    return Number(total).toFixed(3);  
  };
  

const calculateTotalAmountInKgs = (data) => {
  return data.reduce((total, item) => {
    let qty =0
    if (item.invoiceType?.toLowerCase()  === "defect" && item.defectQuantity != null && item.defectQuantity != undefined) {
      qty = Number(item.defectQuantity)
  } else if (item.harvestType === HarvestTypes.Re_Weighment && item.reweighmentQuantity != null && item.reweighmentQuantity != undefined) {
      qty = Number(item.reweighmentQuantity)
  } else {
      qty = Number(item.grnQuantity)
  }
    // const quantity=item?.harvestType=="Re Weighment"?Number(item?.reweighmentQuantity):Number(item?.grnQuantity)
    // const quantity = Number(item?.grnQuantity) || 0;
    const unitPrice = Number(item?.unitPrice) || 0;
    const totalAmount= Number(total) + Number(qty * unitPrice);
    return totalAmount.toFixed(3)
  }, 0);
};
// const calculateTDSAmount = (data) => {
//   const tdsRate = data?.[0]?.tdsApplicable || 0; 
//   const totalAmount = data.reduce((total, item) => {
//     let qty = 0;
//     if (item.invoiceType?.toLowerCase() === "defect") {
//       qty = Number(item.defectQuantity);
//     } else if (item.harvestType === HarvestTypes.Re_Weighment) {
//       qty = Number(item.reweighmentQuantity);
//     } else {
//       qty = Number(item.grnQuantity);
//     }
//     const unitPrice = Number(item?.unitPrice) || 0;
//     return total + qty * unitPrice;
//   }, 0);
//   return ((totalAmount * 0.1) / 100).toFixed(3); 
// };

const calculateTDSAmount = (data) => {
  const taxableAmount = Number(data?.[0]?.taxableAmount || 0);
  return ((taxableAmount * 0.1) / 100).toFixed(3);
};

  return (
    <div >
        <div>
        <p style={{ textAlign: 'center', lineHeight: "1.5 !important", backgroundColor: '#69c0ff', border: 0, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                    <h3 style={{ margin: 0,textAlign:"center" }}>{rmInvoicePrint?.[0]?.address}</h3>
                    <Button onClick={printOrder} className="panel_button" style={{ marginLeft: 'auto' }}>
                        Print
                    </Button>
                </p>
      {/* <Card
        title="BMR INDUSTRIES PRIVATE LIMITED"
        style={{ textAlign: 'center', lineHeight: "1.5 !important" }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={
            <span style={{ color: 'white' }}>
              <Button onClick={printOrder} className="panel_button">
                Print
              </Button>
              {/* <Button className="panel_button" onClick={downloadAsPDF}>
                Download PDF
              </Button>
            </span>
          }
      > */} 
        <br />
        <div id="printme">
<br/>
<br/>

<br/>

        <div style={{ textAlign: 'center' }}>
          <div>
          <b>{rmInvoicePrint?.[0]?.address}</b>
          </div>
          <div>
           {exporterData?.addressOne},{exporterData?.addressTwo}-{exporterData?.postalCode}
          </div>
          <div>{exporterData?.state},{exporterData?.country} </div>
          <div> GSTIN:{exporterData?.GSTNumber}</div>
        </div>
        <div>
          <p style={{alignItems:"Center"}}>
            <b>RM BOUGHT NOTE</b>
          </p>
        </div>
        <div>
          <Form>
            <Row style={{ textAlign: 'left' }} gutter={24}>
              <Col className="text-center" span={12}>
                <strong>INVOICE NUM :{rmInvoicePrint?.[0]?.invoiceNumber}</strong>
              </Col>
              <Col className="text-center" span={12}>
                <strong>VEHICLE NUM :{rmInvoicePrint?.[0]?.vehicle_number}</strong>
              </Col>
            </Row>
            <Row style={{ textAlign: 'left' }} gutter={24}>
              <Col className="text-center" span={12}>
              <strong>
  INVOICE DATE : {moment(rmInvoicePrint?.[0]?.invoiceDate).format('DD-MM-YYYY')}
</strong>
              </Col>
              <Col className="text-center" span={12}>
                <strong>BATCH NUM :{rmInvoicePrint?.[0]?.batchNumbers}</strong>
              </Col>
            </Row>
          </Form>
        </div>
 
        <div style={{ textAlign: 'left' }}>
          <p><b>Supplier Name :</b>{rmInvoicePrint?.[0]?.supplierName!=null && rmInvoicePrint?.[0]?.supplierName !== "" ?rmInvoicePrint?.[0]?.supplierName:rmInvoicePrint?.[0]?.dealerName}</p>
   
          <p><b>Supplier Address :</b> {rmInvoicePrint?.[0]?.supplierAddress !== null && rmInvoicePrint?.[0]?.supplierAddress !== "" 
    ? rmInvoicePrint?.[0]?.supplierAddress 
    : rmInvoicePrint?.[0]?.dealerAddress}</p>
   
          <p><b>GST Number :</b>{exporterData?.GSTNumber}</p>
   
          <p><b>Product Type :</b>{rmInvoicePrint?.[0]?.productName}</p>

          <b><p>Bill To :{rmInvoicePrint?.[0]?.billToType}- {rmInvoicePrint?.[0]?.financierName}</p></b>


        </div>
        <div>
  <table
    style={{
      borderCollapse: 'collapse',
      width: '100%',
      border: '1px solid #000',
      marginTop: '10px', 
      marginBottom: '10px',
    }}
  >
    <thead>
      <tr>
        <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          COUNT
        </th>
        <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          Type
        </th>
        <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          Defect Name
        </th>
        {/* <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          HSN 
        </th> */}
        <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          Qty in Kgs
        </th>
        <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          Rate per kg
        </th>
        <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          Amount in Rs
        </th>
        <th style={{ textAlign: 'center', border: '1px solid #000' }}>
          Remarks
        </th>
      </tr>
    </thead>
    <tbody>
      {rmInvoicePrint.map((rec, idx) => {
         let qty =0
         if (rec.invoiceType?.toLowerCase()  === "defect" && rec.defectQuantity != null && rec.defectQuantity != undefined) {
          qty = Number(rec.defectQuantity) * Number(rec.unitPrice);
      } else if (rec.harvestType === HarvestTypes.Re_Weighment && rec.reweighmentQuantity != null && rec.reweighmentQuantity != undefined) {
          qty = Number(rec.reweighmentQuantity) * Number(rec.unitPrice);
      } else {
          qty = Number(rec.grnQuantity) * Number(rec.unitPrice);
      }
        return(<><tr key={idx}>
              <td style={{ textAlign: 'center', border: '1px solid #000' }}>
                  {/* {rec.count !== null ? rec.count : '-'} */}
                  {rec.harvestType=="Re Weighment"?rec.reweighmentCount:rec.count}
              </td>
              <td style={{ textAlign: 'center', border: '1px solid #000' }}>
                  {rec.invoiceType !== null ? rec.invoiceType : '-'}
              </td>
              <td style={{ textAlign: 'center', border: '1px solid #000' }}>
              {rec.invoiceType?.toLowerCase() === "defect" ? rec.defectName : '-'}
              </td>
              <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px" }}>
              {rec.invoiceType?.toLowerCase() === "defect" ? rec.defectQuantity : (rec.harvestType === "Re Weighment"  ? rec.reweighmentQuantity  : rec.grnQuantity)}
          </td>

              <td style={{ textAlign: 'right', border: '1px solid #000' ,paddingRight:"8px"}}>
                  {rec.unitPrice !== null ? rec.unitPrice : '-'}
              </td>
              <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px" }}>
  {isNaN(Number(qty)) ? '0.00' : Number(qty).toFixed(3)}
</td>
              <td style={{ border: '1px solid #000' }}>
                  {rec.rmInvoiceRemarks !== null ? rec.rmInvoiceRemarks : '-'}
              </td>
          </tr></>)
})}
     {rmInvoicePrint.some(item => item.tdsApplicable !== null) && rmInvoicePrint.some(item => item.tdsApplicable !== 0) ? (
      <>
        <tr>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>Invoice Amount</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>

                   <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px" }}>{calculateTotalquantity(rmInvoicePrint)}</td>

                  <td style={{ textAlign: 'center', border: '1px solid #000',paddingRight:"8px" }}>&nbsp;</td>
                 <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px"  }}>{calculateTotalAmountInKgs(rmInvoicePrint)}</td>

                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
              </tr>
              <tr>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>TDS</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>

                   <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px" }}></td>

                  <td style={{ textAlign: 'center', border: '1px solid #000',paddingRight:"8px" }}>&nbsp;</td>
                 <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px"  }}>{calculateTDSAmount(rmInvoicePrint)}</td>

                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
              </tr>
              <tr>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>Total</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>

                   <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px" }}>--</td>

                  <td style={{ textAlign: 'center', border: '1px solid #000',paddingRight:"8px" }}>&nbsp;</td>
                 <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px"  }}>{(Number(calculateTotalAmountInKgs(rmInvoicePrint)) - Number(calculateTDSAmount(rmInvoicePrint))).toFixed(3)}</td>

                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
              </tr>
      </>
    ) : (
      <tr>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>Total</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>

                   <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px" }}>{calculateTotalquantity(rmInvoicePrint)}</td>

                  <td style={{ textAlign: 'center', border: '1px solid #000',paddingRight:"8px" }}>&nbsp;</td>
                 <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"8px"  }}>{calculateTotalAmountInKgs(rmInvoicePrint)} </td>

                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
              </tr>
    )}
    </tbody>
   {/* <tfoot>
    <tr>
        <td>Total</td>
        <td>Total</td>
        <td>Total</td>
      
    </tr>
   </tfoot> */}
  </table>
</div>

 
        <div>
          <Form>
            <Row>
              <Col  span={8}>PREPARED BY :</Col>
              <Col  span={8}>VERIFIED BY :</Col>
              <Col  span={8}>AUTHORISED BY :</Col>
            </Row>
          </Form>
        </div>
      {/* </Card> */}
      </div >

      </div>
    </div>
  );
};

export default RMInvoicePrint;
