import { ConditionsRequest, PlantInvoiceDetailsModel, PlantInvoiceDetailsRequest } from '@gtpl/shared-models/sale-management';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button } from 'antd';
import moment from 'moment';
import { PrinterOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';

export interface StuffingInvoiceProps {
  saleOrderId: number;
}

const StuffingCertificate: React.FC<StuffingInvoiceProps> = (props) => {
  const [plantDetails, setPlantDetails] = useState<PlantInvoiceDetailsModel>();
  const saleOrderService = new SaleOrderService();
  const [total,setTotal] =  useState(0)
  let totalCases = 0;

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

  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 getCssFromComponent = (fromDoc: Document, toDoc: Document) => {
  //   Array.from(fromDoc.styleSheets).forEach((styleSheet: any) => {
  //     if (styleSheet.cssRules) {
  //       const newStyleElement = toDoc.createElement('style');
  //       Array.from(styleSheet.cssRules).forEach((cssRule: any) => {
  //         newStyleElement.appendChild(toDoc.createTextNode(cssRule.cssText));
  //       });
  //       toDoc.head.appendChild(newStyleElement);
  //     }
  //   });
  // };

  const printOrder = () => {
    const divContents = document.getElementById('printme')?.innerHTML || '';
    const secondPageContents = document.getElementById('secondPage')?.innerHTML || '';
  
    if (!divContents && !secondPageContents) {
      console.error('No content to print');
      return;
    }
  
    const printWindow = window.open('', '', 'height=700, width=1024');
  
    if (printWindow) {
      printWindow.document.write(`
        <html>
          <head>
            <style>
              @media print {
                body, html {
                  height: 100%;
                  margin: 0;
                  display: block;
                  font-family: Arial, sans-serif;
                }
                #printme, #secondPage {
                  width: 100%;
                  display: block;
                  text-align: left;
                  margin: 10px auto;
                  page-break-after: always;
                }
                .page-break {
                  page-break-before: always;
                }
                table {
                  width: 100%;
                  margin: 10px auto;
                  border-collapse: collapse;
                }
                th, td {
                  border: 1px solid black;
                  padding: 8px;
                  text-align: center;
                }
              }
            </style>
          </head>
          <body>
            ${divContents ? `<div id="printme">${divContents}</div>` : ''}
            ${secondPageContents ? `<div id="secondPage" class="page-break">${secondPageContents}</div>` : ''}
          </body>
        </html>
      `);
  
      getCssFromComponent(document, printWindow.document);
      printWindow.document.close();
  
      printWindow.onload = () => {
        setTimeout(() => {
          printWindow.print();
          printWindow.close();
        }, 500);
      };
    } else {
      console.error('Unable to open print window');
    }
  };
  
  

  const getData = (saleOrderId: number) => {
    const reqObj = new PlantInvoiceDetailsRequest(1);
    saleOrderService
      .getPlantInvoiceDetails(new PlantInvoiceDetailsRequest(saleOrderId))
      .then((res) => {
        if (res.status) {
          setPlantDetails(res.data);
          const tot = (res.data.gradeInfo || []).reduce(
            (total, g) =>
              total +
              (g.info || []).reduce(
                (subtotal, val) => subtotal + (Number(val.noOfCases) || 0),
                0
              ),
            0
          );
          setTotal(tot)
          console.log(total,'oooooooooooo');
          
         
          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 = res.data.saleOrderItems[0]?.buyerAddress;
          request.deliveryAddress = res.data.saleOrderItems[0]?.deliveryaddress;

          saleOrderService.getConditionsBasedLogistics(request).then((res) => {
            if (res.status) {
              // handle successful response
            }
          });
        } else {
          setPlantDetails(undefined);
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setPlantDetails(undefined);
      });
  };
console.log(totalCases,'pppppppppppppp');

  if (!plantDetails) {
    return null;
  }

  const totalNoCases = plantDetails.gradeInfo.reduce((total, grade) => {
    const gradeTotal = grade.info.reduce((subTotal, r) => subTotal + (r.noOfCases || 0), 0);
    return total + gradeTotal;
  }, 0);

  // return (
  //   <>
  //     {plantDetails.gradeInfo.map((g, prodIndex) => (
  //       g.info.map((r, index) => {
  //         let exchangeRate = plantDetails?.exchangeRate ?? 0;
  //         totalCases += r.noOfCases;

          return (
            <div  id="print">
              <h1 style={{ fontSize: '24px',fontWeight:"bold",justifyContent:"center",alignItems:"center" }}><u>STUFFING CERTIFICATE</u></h1>
                   <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 {totalNoCases} CARTONS FROZEN VANNAMEI SHRIMPS IS STUFFED IN MY PRESENCE
              </h3>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr>
                    <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}><u>CONTAINER NO</u></th>
                    <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}><u>SIZE</u></th>
                    <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}><u>SELF SEAL NO OTS</u></th>
                    <th style={{ border: '1px solid black', padding: '8px', textAlign: 'center' }}><u>NO OF PKG</u></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' }}>{total?total:0}</td>
                  </tr>
                </tbody>
              </table>
            </div>
    //       );
    //     })
    //   ))}
     
    // </>
  );
};

export default StuffingCertificate;
