import React, { useEffect, useState } from 'react';
import { Button, Card } from 'antd'; // Only importing Button from antd
import { PrinterOutlined } from '@ant-design/icons';
import './rm-grn-print.css'
import { GrnService } from '@gtpl/shared-services/procurement';
import { GrnIDRequest, GrnItemIdRequest } from '@gtpl/shared-models/procurement-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { ToWords } from 'to-words';
import moment from 'moment';
import { GrnIdReq } from '@gtpl/shared-models/raw-material-procurement';
import { FactoriesInput } from '@gtpl/shared-models/sale-management';
import { getCssFromComponent } from '..';
import { ExporterDataInput } from '@gtpl/shared-models/logistics';
import {VehicleAssignmentService} from '@gtpl/shared-services/transportation'
import { HarvestTypes, SupplierTypeEnum } from '@gtpl/shared-models/common-models';
// Define the interface for props


const toWords = new ToWords({
  localeCode: 'en-US',
})
function formatQuantityInWords(quantity) {
  const quantityNumeric = parseFloat(quantity);
  if (isNaN(quantityNumeric)) {
    return '';
  }
  const kilograms = Math.floor(quantityNumeric);
  const grams = Math.round((quantityNumeric - kilograms) * 1000); // Convert decimal part to grams

  let quantityWords = '';
  if (kilograms > 0) {
    quantityWords += toWords.convert(kilograms, { currency: false }).toUpperCase() + ' KGS';
  }
  if (grams > 0) {
    if (quantityWords.length > 0) {
      quantityWords += ' ';
    }
    quantityWords += toWords.convert(grams, { currency: false }).toUpperCase() + ' GRAMS';
  }

  return quantityWords;
}

export interface BMRPrintProps {
  batchNumber:string
  year:string
// grnId:number
}

export function RawMaterialGRNPrint(props:BMRPrintProps) {
  const service = new GrnService()
    const [data, setData] = useState([])
    const [deffects, setDeffects] = useState([])

    // const [indentId, setIndentId] = useState<number>()
    const [vehicles, setVehicles] = useState([])

    const vehicleService = new VehicleAssignmentService()

    const [isModalVisible, setIsModalVisible] = useState<boolean>(false);

let total =0
let totalWeight =0
let totalQty =0
useEffect(()=>{getData()
},[totalQty])
    const getData=()=>{
        const req =new GrnIDRequest(props.batchNumber,undefined,props.year)
        service.getRawMaterialGrn(req).then((res)=>{
            if(res.status){
                setData(res.data?.[0]?.details)
                setDeffects(res.data?.[0]?.deffects)
                res.data?.[0]?.details.map((e)=> total = total+e.noOfCrates)
                // res.data.map((e)=> totalQty = totalQty + Number(e.quantity))
                // console.log(res.data.map((e)=> totalQty = totalQty + Number(e.quantity)),'ooooooooooooooooooo');
                // res.data.map((e)=>totalQty += Number(e.quantity))

                // setIndentId(res.data[0]?.indentId)
                if(res.data?.[0]?.details[0]?.IndentId != null|| res.data?.[0]?.details[0]?.IndentId != undefined || res.data?.[0]?.details[0]?.IndentId != 0){
                  vehicleService.getVehicleAssignDetailsByIndentId({indentId:res.data?.[0]?.details[0]?.IndentId}).then(res=>{
                    if(res.status){
                      setVehicles(res.data[0]?.vechileInfo)
                    }
                  })
                }
            }
            else{
                AlertMessages.getErrorMessage(res.internalMessage)
            }
        })
    }
  // console.log(totalQty,"totalQtyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")

    
    const quantityInWords = formatQuantityInWords(totalQty ?? '');
    let exporterDetails = ExporterDataInput;

    const exporterData = exporterDetails.find(
    (item) => item.value == data[0]?.plantId ? data[0]?.plantId : 0
  );
  
    const printOrder = () => {
      const printableElements = document.getElementById('printme').innerHTML;
      const element =window.open( '<html><head><title></title></head><body>' + printableElements + '</body></html>')
      const oldPage = document.body.innerHTML;
      element.document.write(printableElements);
      getCssFromComponent(document, element.document);
      element.document.close();
      setTimeout(() => {
        element.print();
        element.close(); // to close window when click on cancel/Save
        setIsModalVisible(true); // model should be open
      }, 1000);
      // window.document.close();
      // window.print();
      // window.close()    
    }  
  return (
    <>
    <div className="print-content">
      <Card
        title='Raw Material Grn' style={{ textAlign: 'center', 
        // width: '210mm',
        // height: '297mm',
        // margin: 'auto',
        padding: '5mm',
        position: 'relative'
      }} headStyle={{ backgroundColor: '#69c0ff',fontSize:'15px'  }}
        
        extra={
          <span style={{alignSelf:'end'}}><Button onClick={printOrder}>Print</Button></span>

        }
      >
      <br />
        <>
          <html>
            <body id="printme">
              <div style={{ textAlign: 'center'}}>
              <div style={{ textAlign: 'center' }}>
                  <h2 style={{ margin: '0' }}>{data[0]?.company}</h2>
                  <p>{exporterData?.addressOne} <br/> {exporterData?.addressTwo}</p>
                </div>
                <table style={{ width: '100%' }}>
                  <tbody>
                    <tr>
                      <td style={{ textAlign: 'center' }}>
                        <h3 style={{ margin: '0' }}>RAW MATERIAL RECEIVING REPORT</h3>
                        <hr style={{width: '370px',margin: 'auto',border: '1px solid black'}}/>
                      </td>
                    </tr>
                    <tr>
                      <td style={{ textAlign: 'center' }}>
                        <table style={{ width: '100%' }}>
                          <tbody>
                            <tr>
                              <td style={{textAlign: 'center',verticalAlign:'right',}}>
                                <div style={{border: '1px solid black',width: '130px',margin: '-50px auto',marginRight: '10px',height: '90px'}}>
                                  <p style={{ margin: 0, textAlign: 'center' }}>Source Code</p>
                                  <hr style={{margin: '5px 0',border: 'none',borderTop: '1px solid black'}}/>
                                  <p style={{ margin: 0 }}>{data?.map(item => item?.lotNum).join(", ")}</p>
                                </div>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </td>
                    </tr>
                  </tbody>
                </table>
                <div style={{ textAlign: 'center', marginTop: '5px' }}>
                  <table style={{ borderCollapse: 'collapse', margin: 'auto' }}>
                    <tr style={{ height: '43px' }}>
                      <td style={{border: '1px solid black',padding: '10px 20px',width: '85px'}}></td>
                      <td style={{border: '1px solid black',padding: '10px 20px',width: '250px'}}></td>
                    </tr>
                  </table>
                  <p style={{ marginTop: '-25px', textAlign: 'left' }}>RMRN No: {data?.[0]?.grnNum ? data?.[0]?.grnNum:'-'}</p>
                </div>
                <table style={{ width: '100%', textAlign: 'left' }}>
                  <tbody>
                    <tr>
                      <td style={{ width: '50%' }}>
                        <p style={{ margin: '-4px 0', marginBottom: '14px' }}>FARMER'S NAME/ADDRESS:</p>
                        <p style={{ margin: '-4px 0', marginBottom: '14px' }}>{data?.[0]?.supplierType === SupplierTypeEnum.DEALER? data?.[0]?.dealer:data?.[0]?.farmer}</p>
                        <p style={{ margin: '-4px 0', marginBottom: '14px' }}>{data?.[0]?.supplierType === SupplierTypeEnum.DEALER?data?.[0]?.dealerCity:data?.[0]?.city?data?.[0]?.city:''},{data?.[0]?.supplierType === SupplierTypeEnum.DEALER?data?.[0]?.dealerStreet:data?.[0]?.street?data?.[0]?.street:''},{data?.[0]?.supplierType === SupplierTypeEnum.DEALER?data?.[0]?.dealerPostalCode:data?.[0]?.postalCode?data?.[0]?.postalCode:''}</p>
                        <p style={{ margin: '-4px 0', marginBottom: '14px' }}>Variety: {data?.[0]?.product}</p>
                        {/* <p style={{ margin: '-4px 0', marginBottom: '14px' }}>{data?.[0]?.product}</p> */}
                      </td>
                      <td style={{ width: '21%' }}>
                        <pre style={{ margin: '-4px 0' }}>Date :{data?.[0]?.reWeighmentDate=== null ? moment(data?.[0]?.grnDate).format('DD-MM-YYYY'):data?.[0]?.reWeighmentDate? moment(data?.[0]?.reWeighmentDate).format('DD-MM-YYYY'):''}</pre>
                        {/* <pre style={{ margin: '-4px 0' }}>Vehicle No. :{vehicles?.map(item => item?.vehicleNum).join(", ")}</pre> */}
                        <pre style={{ margin: '-4px 0' }}>Vehicle No. :{data?.[0]?.vehicleNumber}</pre>

                        <pre style={{ margin: '-4px 0' }}>Time Started :</pre>
                        <pre style={{ margin: '-4px 0' }}>Total Crates :{data?.[0]?.noOfCrates}</pre>
                        <pre style={{ margin: '-4px 0' }}>Time Reached :</pre>
                        <pre style={{ margin: '-4px 0' }}>Seal No. :{data?.[0]?.seal?data?.[0]?.seal:'-'}</pre>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div style={{ textAlign: 'center' }}>
                <div style={{ display: 'flex', justifyContent: 'center' }}>
                  <table style={{width: '100%',borderCollapse: 'collapse',margin: 'auto'}}>
                    <tbody>
                      <tr style={{ fontWeight: 'bolder' }}>
                        <td style={{ border: '1px solid black', padding: '10px' }}>COUNT</td>
                        <td style={{ border: '1px solid black', padding: '10px' }}>QUANTITY (KGS)</td>
                      </tr>
                      {data?.map(e =>{
                        let qty =0
                        let count = 0 
                        if(e.harvestType ==HarvestTypes.Re_Weighment && e.reweighmentQty != undefined){
                          qty =  e.reweighmentQty
                        }else{
                          qty =   e.quantity
                        }
                        if(e.rmCount!= null && e.rmCount != undefined){
                          count = e.rmCount
                        }else{
                          count= e.count
                        }
                        totalQty = totalQty+Number(qty)
                        console.log(totalQty,"totalQty")

                       return (
                        <>
                      <tr>
                      <td className='ta-b'>{count}</td>
                        <td className='ta-b'>{qty}</td>

                      </tr>
                      {/* {e.defect!= null?
                        (<tr>
                        <td className='ta-b'>{count}{e.defect!= null?`(${e.defect})`:null}</td>
                        <td className='ta-b'>{e.defectQty}</td>

                      </tr>):('')
                      } */}
                      </>
                      )})}
                       {deffects?.map(e =>{
                        let qty =0
                        let count = 0 
                        // if(e.reweighmentQty != null && e.reweighmentQty != undefined){
                        //   qty =  e.reweighmentQty
                        // }else{
                        //   qty =   e.quantity
                        // }
                        if(e.rmCount!= null && e.rmCount != undefined){
                          count = e.rmCount
                        }else{
                          count= e.count
                        }
                        totalQty = totalQty+Number(e.defectQty)
                        // totalQty += Number(qty)
                        // console.log(totalQty,"totalQty")

                       return (
                        <>
                      {/* <tr>
                      <td className='ta-b'>{count}</td>
                        <td className='ta-b'>{qty}</td>

                      </tr> */}
                      {e.defect!= null?
                       ( <tr>
                        <td className='ta-b'>{count}{e.defect!= null?`(${e.defect})`:null}</td>
                        <td className='ta-b'>{e.defectQty}</td>

                      </tr>):''
                    }
                      </>
                      )})}
                      <tr>
                        <td className='ta-b'>&nbsp;</td>
                        <td className='ta-b'>&nbsp;</td>

                      </tr>
                      <tr>
                        <td className='ta-b'>Total</td>
                        <td className='ta-b'>{totalQty.toFixed(3)}</td>

                      </tr>
                    </tbody>
                  </table>
                  <table style={{ width: '100%', borderCollapse: 'collapse', margin: 'auto', marginLeft: '10px'}}>
                    <tbody>
                      <tr style={{ fontWeight: 'bolder' }}>
                        <td style={{ border: '1px solid black', padding: '10px' }}>COUNT</td>
                        {/* <td style={{ border: '1px solid black', padding: '10px' }}>Rate/Kgs. (Rs.)</td> */}
                      </tr>
                      {data?.map(e =>(
                        // totalQty= totalQty+e?.quantity
                      <tr>
                        <td className='ta-b'>&nbsp;</td>
                        {/* <td className='ta-b'>{e.ratePerKg}</td> */}

                      </tr>
                      ))}
                      {/* <tr>
                      <td className='ta-b'></td>
                      <td className='ta-b'>{data?.[0]?.ratePerKg}</td>

                      </tr> */}
                      <tr>
                        <td className='ta-b'>&nbsp;</td>
                        {/* <td className='ta-b'>&nbsp;</td> */}

                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              {/* <footer style={{ position: 'absolute', bottom: '10mm', width: '100%' }}> */}
                <div style={{textAlign:'left'}}>
                    <div style={{ marginTop: '10px'}}>
                        <p>Total Quantity in Words: <b>{formatQuantityInWords(totalQty ?? '')}</b></p>
                    </div>
                    
                    {/* Remarks */}
                    <div style={{ marginTop: '10px'}}>
                        <p>Remarks(If any): <b></b></p>
                    </div>
                </div>
                <table
                  style={{ width: '90%', textAlign: 'center', border: 'none' }}
                >
                  <tbody>
                    {/* <tr>
                      <td>________________________</td>
                      <td>________________________</td>
                      <td>________________________</td>
                      <td>________________________</td>
                    </tr> */}
                    <tr>
                      <td>PROCURED BY</td>
                      <td>Farmer's Signature</td>
                      <td>RECD BY<br />(at Process Plant)</td>
                      <td>AUTHORISED BY<br />(Process Plant)</td>
                    </tr>
                  </tbody>
                </table>
              {/* </footer> */}
            </body>
          </html>
        </>
      </Card>
      </div>
    </>
  );
}

export default RawMaterialGRNPrint;
