import {
  AllPoDetailsInfo,
  GrnIDRequest,
  PoRequest,
} from '@gtpl/shared-models/procurement-management';
import {
  GrnService,
  PurchaseOrderService,
} from '@gtpl/shared-services/procurement';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { PrinterOutlined } from '@ant-design/icons'
import { FactoriesInput } from 'libs/shared-models/sale-management/src/lib/sale-order/address-input';
import { GlobalStatus } from '@gtpl/shared-models/common-models';
import { ExporterDataInput } from '@gtpl/shared-models/logistics';


export interface GrnPrintProps {
  grnId: number;
  printOrder: () => void;
}

const GrnPrint = (props: GrnPrintProps) => {
  const grnService = new GrnService();
  const [grnPrintData, setGrnPrintData] = useState<any>([]);

  // let exporterPlant = FactoriesInput;
  // console.log(exporterPlant,"exporterPlant")
  // const factoryDetails = exporterPlant.find(
  //   (item) => item.id == grnPrintData?.unit_id
  // )

  const factoryDetails = FactoriesInput.find(factory => factory.id === 26);
  const exporterDetails = ExporterDataInput.find(exporter => exporter.value === 26);



  useEffect(() => {
    getData(props.grnId);
  }, []);


  const getData = (grnId) => {
    const reqObj = new GrnIDRequest(null,grnId);
    grnService
      .getGrnPrint(reqObj)
      .then((res) => {
        if (res.status) {
          console.log(res.data);
          setGrnPrintData(res.data);
          // console.log(PoDataModel?.[0])
        } else {
          if (res.intlCode) {
            setGrnPrintData(undefined);
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setGrnPrintData(undefined);
      });
  };

  const totalReceivedQuantity = grnPrintData.reduce((total, rec, idx) => {
    console.log(`Record ${idx + 1}:`, rec.receivedQuantity);
    const quantity = rec.receivedQuantity !== null ? Number(rec.receivedQuantity) : 0;
    console.log(`Parsed Quantity for Record ${idx + 1}:`, quantity);
    return total + (isNaN(quantity) ? 0 : quantity); 
  }, 0);
  console.log('Total Received Quantity:', totalReceivedQuantity);
  

  let totalAmount = 0;

  grnPrintData.map((rec, idx) => {
      let individualAmount = rec.receivedQuantity !== null && rec.unitPrice !== null ?
          (rec.discountPer !== null ?
              ((rec.receivedQuantity * rec.unitPrice) - (rec.receivedQuantity * rec.unitPrice) * (rec.discountPer / 100)) :
              (rec.receivedQuantity * rec.unitPrice)) : 0;
  
      totalAmount += individualAmount;

      
  });

      const taxAmount = grnPrintData[0]?.taxCategory === "State" ? (totalAmount * grnPrintData[0]?.taxPercentage / 100) : 0;

      const cgstTaxAmount = grnPrintData[0]?.taxCategory === "State" ? taxAmount : 0;
const sgstTaxAmount = grnPrintData[0]?.taxCategory === "State" ? taxAmount : 0;

const totalTaxAmount = cgstTaxAmount + sgstTaxAmount;


function numberToWords(num: number): string {
  // Array of units
  const units: string[] = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
  const tens: string[] = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
  const teens: string[] = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
  const magnitudes: string[] = ['', 'thousand', 'lakh', 'crore'];

  // Function to convert a three-digit number to words
  function convertThreeDigitNumber(num: number): string {
      let words = '';

      // Extract hundreds digit
      const hundreds = Math.floor(num / 100);
      if (hundreds !== 0) {
          words += units[hundreds] + ' hundred ';
      }

      // Extract last two digits
      const lastTwoDigits = num % 100;
      if (lastTwoDigits !== 0) {
          if (lastTwoDigits < 10) {
              words += units[lastTwoDigits];
          } else if (lastTwoDigits < 20) {
              words += teens[lastTwoDigits - 11];
          } else {
              const tensDigit = Math.floor(lastTwoDigits / 10);
              words += tens[tensDigit];
              const onesDigit = lastTwoDigits % 10;
              if (onesDigit !== 0) {
                  words += ' ' + units[onesDigit];
              }
          }
      }

      return words.trim();
  }

  // Function to split the number into groups according to the Indian numbering system
  function convertToWords(num: number): string {
      if (num === 0) return 'zero';

      let words = '';
      let crore = Math.floor(num / 10000000);
      let lakh = Math.floor((num % 10000000) / 100000);
      let thousand = Math.floor((num % 100000) / 1000);
      let hundred = Math.floor((num % 1000) / 100);
      let rest = num % 100;

      if (crore) {
          words += convertThreeDigitNumber(crore) + ' crore ';
      }
      if (lakh) {
          words += convertThreeDigitNumber(lakh) + ' lakh ';
      }
      if (thousand) {
          words += convertThreeDigitNumber(thousand) + ' thousand ';
      }
      if (hundred) {
          words += convertThreeDigitNumber(hundred) + ' hundred ';
      }
      if (rest) {
          words += convertThreeDigitNumber(rest);
      }

      return words.trim();
  }

  // Convert the number to words
  let words = convertToWords(num);

  return words + ' rupees only';
}

const totalSum = grnPrintData.reduce((sum, rec) => {
  if (rec.receivedQuantity !== null && rec.unitPrice !== null) {
    const amount = rec.discountPer !== null
      ? (rec.receivedQuantity * rec.unitPrice) - (rec.receivedQuantity * rec.unitPrice) * (rec.discountPer / 100)
      : rec.receivedQuantity * rec.unitPrice;
      
    return sum + amount; 
  }
  
  return sum; 
}, 0);



let cgstTotal = 0;
let sgstTotal = 0;
let totalAmountSum = 0;
  let finalCalculation=0

  const totalTaxAmounts = cgstTotal + sgstTotal;
  console.log(totalTaxAmounts,"totalTaxAmounts")

  grnPrintData.forEach((rec) => {
    const totalAmounts =
      rec.receivedQuantity !== null && rec.unitPrice !== null
        ? rec.discountPer !== null
          ? (rec.receivedQuantity * rec.unitPrice) -
            (rec.receivedQuantity * rec.unitPrice * (rec.discountPer / 100))
          : rec.receivedQuantity * rec.unitPrice
        : 0;
  
    const taxAmount = (totalAmounts * rec.taxPercentage) / 100;
    const cgstValue = rec.taxCategory === 'State' ? taxAmount / 2 : 0;
    const sgstValue = rec.taxCategory === 'State' ? taxAmount / 2 : 0;
  
    cgstTotal += cgstValue;
    sgstTotal += sgstValue;
    totalAmountSum += totalAmounts;
  });
  
  // Calculate the round-off value and final calculation
  const totalTax = cgstTotal + sgstTotal;
  const roundOffValue = Math.round(totalTax + totalAmountSum) - (totalTax + totalAmountSum);
  const finalCalculations = totalAmountSum + totalTax + roundOffValue;
  



  return (
    <div>
      <Card
      title={<span style={{ color: 'white' }}>GRN</span>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
      extra={<Button onClick={props.printOrder} className='noprint' style={{ float: 'right', backgroundColor: '#69c0ff' }}><span style={{ color: 'white' }}><PrinterOutlined /> Print</span></Button>}
      >
        <div>
          <html>
            <body id='printme'>
               <br/><br/><br/> <p style={{textAlign:"center"}}><b>Receipt Note</b></p>
                <table
                style={{ width: '100%',lineHeight:'1.6', border: '1px solid #000' }}
              >
                <tr>
                  <td
                    rowSpan={3}
                    colSpan={2}
                   style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                   <div><b>{grnPrintData[0]?.unitName}</b></div>
                   <div>Shrimp Process Division</div>
                   <div>SY No:{grnPrintData[0]?.village_name},{grnPrintData[0]?.mandal_name}</div>
                   <div>{grnPrintData[0]?.distirct_name}</div>
                   <div>{grnPrintData[0]?.state_name}-{grnPrintData[0]?.postal_code}</div>
                   <div>GSTIN/UIN:{exporterDetails?.GSTNumber}</div>
                   <div>State Name:{grnPrintData[0]?.state_name?grnPrintData[0]?.state_name:"-"},code:{exporterDetails?.stateCode}</div>
                   <div>E-Mail:accounts@bmrgroups.org</div>
                  </td>
                  <td
                    colSpan={3}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                   <div> Receipt Note No.</div>
                   <div><b>{grnPrintData[0]?.grnNumber?grnPrintData[0]?.grnNumber:"-"}</b></div>
                  </td>
                  <td
                    colSpan={2}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                    <div>Dated</div>
                    {/* <div>{grnPrintData[0]?.grnDate?grnPrintData[0]?.grnDate:"-"}</div> */}
                    <div><b>{moment(grnPrintData[0]?.grnDate).format('D-MMM-YY')}</b></div>
                    </td>
                </tr>
                <tr>
                  <td
                    colSpan={3}
                     className={'ta-b'}
                  >
                    &nbsp;
                  </td>
                  <td
                    colSpan={2}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                    <div>Mode/Terms of Payment</div>
                    <div>{grnPrintData[0]?.payment_terms_name?grnPrintData[0]?.payment_terms_name:"-"}</div>
                  </td>
                </tr>
                <tr>
                  <td
                    colSpan={3}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                    Reference No & Date
                    <div>{grnPrintData[0]?.grnInvNum?grnPrintData[0]?.grnInvNum:"-"}&nbsp;
                    {/* {grnPrintData[0]?.genInvDate?grnPrintData[0]?.genInvDate:"-"} */}
                    <b> {moment(grnPrintData[0]?.genInvDate).format('D-MMM-YY')}</b>
                    </div>

                  </td>
                  <td
                    colSpan={2}
                    style={{ border: '1px solid #000', textAlign: 'left',paddingTop:"2px"}}
                  >
                    Other References
                  </td>
                </tr>
                <tr>
                  <td
                    rowSpan={3}
                    colSpan={2}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                   <b> Supplier(Bill From)</b>

                    <div><b>{grnPrintData[0]?.poVendorName}</b></div>
                    <div>{grnPrintData[0]?.poStreet}</div>
                    <div>{grnPrintData[0]?.poStateName}</div>
                    <div>GSTIN/UIN:{grnPrintData[0]?.poGstNumber?grnPrintData[0]?.poGstNumber:"-"}</div>
                    <div>State Name:{grnPrintData[0]?.poStateName?grnPrintData[0]?.poStateName:"-"}</div>
                    <div>E-Mail:{grnPrintData[0]?.poEmailId?grnPrintData[0]?.poEmailId:"-"}</div>
                  </td>
                  <td
                    colSpan={3}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                    Receipt Doc No.
                    <div><b>{grnPrintData[0]?.poNumber?grnPrintData[0]?.poNumber:"-"}</b></div>
                  </td>
                  <td
                    colSpan={2}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                   &nbsp;

                  </td>
                </tr>
                <tr>
                  <td
                    colSpan={3}
                     style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                    Dispatched through
                    <div><b>By Road</b></div>
                  </td>
                  <td
                    colSpan={2}
                     style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                    Destination
                    {/* <div><b>{grnPrintData[0]?.grnCity?grnPrintData[0]?.grnCity:"-"}</b></div>
                     */}
                     <div><b>Damavaram</b></div>

                  </td>
                </tr>
                <tr>
                  <td
                    colSpan={5}
                    style={{ border: '1px solid #000', textAlign: 'left'}}
                  >
                    Terms of Delivery
                    <div><b>{grnPrintData[0]?.deliveryTerms?grnPrintData[0]?.deliveryTerms:"-"}</b></div>

                  </td>
                </tr>
                <tr>
                  <td
                    style={{ textAlign: 'center', border: '1px solid #000',width:"40px" }}
                  ><b>
                    SI No.
                    </b> </td>
                  <td
                    style={{ textAlign: 'center', border: '1px solid #000',width:"500px" }}
                  ><b>
                    Description Of Goods
                    </b> </td>
                  <td  style={{ textAlign: 'center', border: '1px solid #000' }}>
                   <b> Quantity</b>
                  </td>
                  <td
                    style={{ textAlign: 'center', border: '1px solid #000' }}
                  ><b>
                    Rate</b>
                  </td>
                  <td
                    style={{ textAlign: 'center', border: '1px solid #000' }}
                  ><b>
                    Per
                    </b> </td>
                  <td
                    style={{ textAlign: 'center', border: '1px solid #000' }}
                  ><b>
                    Disc %
                    </b> </td>
                  <td
                    style={{ textAlign: 'center', border: '1px solid #000' }}
                  ><b>
                    Amount

                    </b> </td>
                </tr>



                {grnPrintData.map((rec, idx) => {
      const totalAmounts =
        rec.receivedQuantity !== null && rec.unitPrice !== null
          ? rec.discountPer !== null
            ? (rec.receivedQuantity * rec.unitPrice) -
              (rec.receivedQuantity * rec.unitPrice * (rec.discountPer / 100))
            : rec.receivedQuantity * rec.unitPrice
          : 0;

      const taxAmount = (totalAmounts * rec.taxPercentage) / 100;
      const cgstValue = rec.taxCategory === 'State' ? taxAmount / 2 : 0;
      const sgstValue = rec.taxCategory === 'State' ? taxAmount / 2 : 0;
      // cgstTotal+=cgstValue
      // sgstTotal+=sgstValue

      return (
        <tr key={idx} style={{ borderBottom: 'none' }}>
          <td style={{ textAlign: 'center', border: '1px solid #000', width: '40px',borderBottom:"none" ,borderTop:"none"}}>
            {idx + 1}
          </td>
          <td style={{ textAlign: 'left', border: '1px solid #000', paddingLeft: '15px',borderBottom:"none" ,borderTop:"none"}}>
            {rec.ProductDescription !== null ? rec.ProductDescription : '-'}
          </td>
          <td style={{ textAlign: 'right', border: '1px solid #000', paddingRight: '15px' ,borderBottom:"none",borderTop:"none"}}>
            {rec.receivedQuantity !== null ? rec.receivedQuantity : '-'} {rec.itemUom}
          </td>
          <td style={{ textAlign: 'right', border: '1px solid #000', paddingRight: '15px',borderBottom:"none" ,borderTop:"none"}}>
            {rec.unitPrice !== null ? rec.unitPrice : '-'}
          </td>
          <td style={{ textAlign: 'center', border: '1px solid #000' ,borderBottom: 'none',borderTop:"none"}}>{rec.itemUom}</td>
          <td style={{ textAlign: 'right', border: '1px solid #000', paddingRight: '15px',borderBottom:"none" ,borderTop:"none"}}>
            {rec.discountPer !== null ? rec.discountPer : '-'}
          </td>
          <td style={{ textAlign: 'right', border: '1px solid #000', paddingRight: '15px' ,borderBottom:"none",borderTop:"none"}}>
            {totalAmounts.toFixed(2)}
          </td>
        </tr>
      );
    })}


      <tr style={{ borderBottom: 'none',borderTop:"none" }}>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'right', borderRight: '1px solid #000',paddingRight:"15px" }}><b>Input CGST-Goods</b></td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'right', borderRight: '1px solid #000', paddingRight: '15px' }}>
  <b>
    {/* CGST Calculation */}
    {cgstTotal.toFixed(2)}
  </b>
</td>
    </tr>
      <tr style={{ borderBottom: 'none' }}>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'right', borderRight: '1px solid #000',paddingRight:"15px" }}><b>Input SGST-Goods</b></td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'right', borderRight: '1px solid #000',paddingRight:"15px" }}>
    <b>
    {sgstTotal.toFixed(2)}
    </b>
</td>   
   </tr>
   <tr style={{ borderBottom: 'none' }}>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'right', borderRight: '1px solid #000',paddingRight:"15px" }}><b>ROUND OFF</b></td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'center', borderRight: '1px solid #000' }}>&nbsp;</td>
      <td style={{ textAlign: 'right', borderRight: '1px solid #000', paddingRight: '15px' }}>
  <b>
  {roundOffValue.toFixed(2)}

  </b>
</td>
  
   </tr>
   <tr style={{ borderBottom: 'none' }}>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</td>
                  <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"15px" }}><b>Total</b></td>
                  <td style={{ textAlign: 'right', border: '1px solid #000',paddingRight:"15px" }}><b>{Number(totalReceivedQuantity).toFixed(2)} </b></td>
                  <td style={{ textAlign: 'center', border: '1px solid #000' }}>&nbsp;</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: '15px' }}>
  <b>
  ₹ {finalCalculations}
  </b>
</td>
              </tr>
              <tr>
                  <td
                    colSpan={2}
                    style={{ border: '1px solid #000', textAlign: 'left',borderBottom:"none",borderRight:"none"}}
                  >
                    Amount Chargeable(in Words)
                    <div> <b>INR{" "}{numberToWords(finalCalculations)
        ?.split(" ")                   // Split the string into words
        ?.map(word => word.charAt(0).toUpperCase() + word.slice(1)) // Capitalize the first letter of each word
        ?.join(" ")}</b></div>
                  </td>
                  <td colSpan={5}
                    style={{ textAlign: 'right', border: '1px solid #000',borderBottom:"none",borderLeft:"none",paddingRight:"15px" }}
                  >
                    E. & O.E
                  </td>
                </tr>
                <tr>
                      <td colSpan={1}>&nbsp;</td>
                        <td colSpan={1} style={{
                            position: 'relative' 
                          }}>
                          
                          <span style={{
                            position: 'absolute',
                            left: '50%',
                            top: '0',
                            height: '100%', 
                            width: '1px', 
                            backgroundColor: 'black', 
                            transform: 'translateX(-50%)' 
                          }}></span>
                          <span style={{
                              position: 'absolute',
                              right: '0',
                              top: '0',
                              height: '1px', 
                              width: 'calc(50% )', 
                              backgroundColor: 'black' 
                          }}></span>
                                            
                            &nbsp; 
                        </td>
                        
                        <td colSpan={7} 
                        style={{
                  
                          position: 'relative' 
                          }}>
                        <span style={{
                          position: 'absolute',
                          left: '0',
                          top: '0', 
                          height: '1px', 
                          width: 'calc(100% )', 
                          backgroundColor: 'black' 
                            }}>

                        </span>
                     
                          <span>
                            <span style={{ textTransform: 'lowercase' }}>for</span> <b>BMR INDUSTRIES PRIVATE LIMITED</b>
                          </span>
                        </td>
                    </tr>
                    <tr>
                      <td colSpan={1} >&nbsp;</td>
                        
                        <td colSpan={1} style={{
                          position: 'relative'
                          }}>
                          <span style={{
                            position: 'absolute',
                            left: '50%', 
                            top: '0',
                            height: '100%', 
                            width: '1px',
                            backgroundColor: 'black', 
                            transform: 'translateX(-50%)'
                          }}></span>
                          
                          &nbsp; 
                          <div style={{  textAlign: 'center', marginLeft: '200px'}}>Prepared by</div>
                        </td>
                        <td colSpan={7} >
                        <div style={{
                          textAlign: 'left',
                          marginTop: '24px',
                          display: 'flex', 
                          justifyContent: 'space-between',
                           }}>
                          <div style={{  textAlign: 'center' }}>Verified by</div>
                          <div style={{  textAlign: 'center' }}>Authorized Signatory</div>
                        </div>

                      </td>
        </tr>
                {/* <tr>
                  <td colSpan={1} style={{ border: '1px solid #000', textAlign: 'left',borderTop:"none",borderBottom:"none",borderRight:"none"}}>&nbsp;</td>
                    <td colSpan={1} style={{ border: '1px solid #000', textAlign: 'left',borderTop:"none",borderBottom:"none",borderLeft:"none"}}>                   &nbsp;                   </td>
                    <td colSpan={7} style={{ border: '1px solid #000', textAlign: 'right',borderBottom:"none",borderLeft:"none"}}>                  for<b> BMR INDUSTRIES PRIVATE LIMITED    </b>               </td>
                </tr>
                <tr>
                  <td colSpan={1} style={{ border: '1px solid #000', textAlign: 'left',borderTop:"none",borderBottom:"none",borderRight:"none"}}>&nbsp;</td>
                    <td colSpan={1} style={{ border: '1px solid #000', textAlign: 'left',borderTop:"none",borderBottom:"none",borderLeft:"none"}}>                   &nbsp;                   </td>
                    <td colSpan={7} style={{ border: '1px solid #000', textAlign: 'left',borderBottom:"none",borderLeft:"none",borderTop:"none"}}> &nbsp;  </td>
                </tr>
                <tr>
                  <td colSpan={2} style={{ border: '1px solid #000', textAlign: 'left',borderTop:"none"}}>&nbsp;</td>
                    <td colSpan={1} style={{ border: '1px solid #000', textAlign: 'left',borderTop:"none",borderRight:"none"}}>                   Prepared by                     </td>
                    <td colSpan={1} style={{ border: '1px solid #000', textAlign: 'center',borderTop:"none",borderLeft:"none",borderRight:"none"}}>                   Verified by                    </td>
                    <td colSpan={3} style={{ border: '1px solid #000', textAlign: 'right',borderTop:"none",borderLeft:"none"}}>                  Authorized Signatory                    </td>
                </tr> */}
                </table>
            </body>
          </html>
        </div>
      </Card>
    </div>
  );
};

export default GrnPrint;
