import { LoadingSheetSaleOrderReq } from '@gtpl/shared-models/common-models';
import { ExporterDataInput } from '@gtpl/shared-models/logistics';
import { PlantInvoiceDetailsModel, PlantInvoiceDetailsRequest } from '@gtpl/shared-models/sale-management';
import { ContainerRegisterService } from '@gtpl/shared-services/logistics';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card } from 'antd'
import React, { useEffect, useState } from 'react'

export interface ContainerPrintProps { 
  saleOrderId: number;
}

const GrossMassContainerPrint = (props:ContainerPrintProps) => {
console.log(props.saleOrderId,"grosssssmassssssscontainnnnnnnnerrrrrr");

    const [grossMassContainerPrint,setGrossMassContainerPrint] = useState<any>([]);
    console.log(grossMassContainerPrint,"%%%%%%%%%%%")
    const containerRService = new ContainerRegisterService();
    const salOrderService = new SaleOrderService();
    const [annexureCDetails, setAnnexureCdetails] = useState<
      PlantInvoiceDetailsModel
    >();
    const propsId=props.saleOrderId

    let exporterDetails = ExporterDataInput;
    const exporterData = exporterDetails.find(
      (item) => item.value == annexureCDetails?.exporterId );
      console.log(exporterData,"exporterDataaaaaaaaaaaaaaa")
    // let exporterDetails = ExporterDataInput;
    // let exporterId = 1;
    // const exporterData = exporterDetails.find((item) =>
    //   item.value == grossMassContainerPrint?.exporterId
    //     ? grossMassContainerPrint.exporterId
    //     : exporterId
    // );

    useEffect(() => {
        if (props) {
            getContainerPrintData( props);
        }
      }, [props]);

      useEffect(() => {
        // setRemarksData("text");
        if (props.saleOrderId) {
          getData(props.saleOrderId);
        }
        // window.print()
      }, [props.saleOrderId]);

      const getData = (saleOrderId) => {
        // const reqObj = new PlantInvoiceDetailsRequest(1);
        salOrderService
          .getPlantInvoiceDetails(new PlantInvoiceDetailsRequest(props.saleOrderId))
          .then((res) => {
            console.log(res);
            if (res.status) {
              console.log(res);
              setAnnexureCdetails(res.data);
            } else {
              if (res.intlCode) {
                setAnnexureCdetails(undefined);
                AlertMessages.getErrorMessage(res.internalMessage);
              } else {
                AlertMessages.getErrorMessage(res.internalMessage);
              }
            }
          })
          .catch((err) => {
            AlertMessages.getErrorMessage(err.message);
            setAnnexureCdetails(undefined);
          });
      };


    const getContainerPrintData=(saleorderId)=>{
        containerRService.getGrossMassOfContainerPrintData(new LoadingSheetSaleOrderReq(propsId)).then((res) => {
            console.log(res,"grosssssssresponse##################");
          if (res.status) {
            setGrossMassContainerPrint(res.data);
          } else {
            if (res.intlCode) {    
          
                
              setGrossMassContainerPrint(undefined);
              AlertMessages.getErrorMessage(res.internalMessage);
            } else {
              AlertMessages.getErrorMessage(res.internalMessage);
            }
          }
        })
          .catch((err) => {
            AlertMessages.getErrorMessage(err.message);
            setGrossMassContainerPrint(undefined);
          });
      }

      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 printOrder = () => {
        const divContents = document.getElementById('printme').innerHTML;
        const element = window.open('', '', 'height=700, width=1024');
  
        const style = `
          <html>
            <head>
              <style>
                @media print {
                  @page {
                    size: A4;
                    margin-top: 50mm; 
                    margin-bottom: 35mm; 
                    margin-left: 10mm;
                    margin-right: 10mm;
                  }
                  body {
                    margin: 0;
                    padding: 0;
                    font-size: 10pt; 
                  }
                  .page-break {
                    page-break-after: always;
                  }
                  .content {
                    margin: 0;
                    padding: 0 10mm; /* Optional: add side padding if needed */
                  }
                }
              </style>
            </head>
            <body>
              <div class="content">
                ${divContents}
              </div>
            </body>
          </html>
        `;
      
        element.document.write(style);
        element.document.close();
        setTimeout(() => {
          element.print();
          element.close(); // to close window when click on cancel/Save
   // model should be open
        }, 1000);
      };


      // const printOrder = () => {
      //   const divContents = document.getElementById('printme').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 currentDate = new Date();
const day = String(currentDate.getDate()).padStart(2, '0');
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Months are 0-based
const year = currentDate.getFullYear();

const formattedTodayDate = `${day}-${month}-${year}`;

const regexPattern = /\d{4}-\d{2}-\d{2}/;

const formatDateString = (dateString) => {
  const [year, month, day] = dateString.split('-');
  return `${day}-${month}-${year}`;
};

  return (
    <div>
        <Card title="Gross mass of container"
         style={{ textAlign: 'center' }}
         headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
         extra={
           <span style={{ color: 'white' }}>
             <Button onClick={printOrder} className="panel_button">
               Print
             </Button>
           </span>
         }>
            <html>
                <body id="printme">
                <p style={{textAlign:"right",paddingRight:"18px"}}><u><b>Annex-1</b></u></p>

                    <p style={{textAlign:"center"}}><u><b>INFORMATION ABOUT VERIFIED GROSS MASS OF CONTAINER</b></u></p>
                    <table style={{ borderCollapse: 'collapse', width: '97%', textAlign:"center",borderLeft:"18px",
                  marginTop: '0',
                  marginBottom: '0' }}>
  <thead>
    <tr>
      <th style={{ textAlign: 'center', border: '1px solid #000' }}><b>S.No</b></th>
      <th style={{ textAlign: 'center', border: '1px solid #000' }}><b>Details Of Information</b></th>
      <th style={{ textAlign: 'center', border: '1px solid #000' }}><b>Particulars</b></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style={{ border: '1px solid #000' }}>1*</td>
      <td style={{  textAlign: 'left',border: '1px solid #000',borderLeft:"18px" }}>Name of the shipper</td>
      <td style={{ border: '1px solid #000' }}>{exporterData?.company}</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>2*</td> 
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Shipper Registration/License No.(IEC No/CIN No)**</td>
      <td style={{ border: '1px solid #000' }}>{exporterData?.ieCode?exporterData?.ieCode:"-"}</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>3*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Name and designation of official of the shipper authorised to sign document</td>
      <td style={{ border: '1px solid #000' }}>
  Mr.{" "}
  {grossMassContainerPrint && grossMassContainerPrint[0] ? (
    `${grossMassContainerPrint[0]?.empLastName ? grossMassContainerPrint[0]?.empLastName[0]?.toUpperCase() + "." : "-"}${
      grossMassContainerPrint[0]?.employeeName ? grossMassContainerPrint[0]?.employeeName?.toUpperCase() : "-"
    }`
  ) : (
    "-"
  )}
</td>

    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>4*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>24*7 contact details of authorised official of shipper</td>
      <td style={{ border: '1px solid #000' }}>
         <div>9848595166-J.SIVAKUMAR </div>
         <div>EXPORT MANAGER</div>        
         {/* {grossMassContainerPrint?.employee_name} */}
         </td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>5*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Container No.</td>
      <td style={{ border: '1px solid #000' }}> 
      {/* {grossMassContainerPrint?.containerNumber?grossMassContainerPrint?.containerNumber:'-'} */}
      {grossMassContainerPrint != undefined ?(grossMassContainerPrint[0]?.containerNumber?grossMassContainerPrint[0]?.containerNumber:'-'):"-"}
      </td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>6*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Container Size(TEU/FEU/other)</td>
      <td style={{ border: '1px solid #000' }}> 
      {grossMassContainerPrint != undefined ? (
  grossMassContainerPrint[0]?.containerSize ? (
    (() => {
      switch (grossMassContainerPrint[0].containerSize) {
        case '20FT':
          return 'TEU - 1 X 20 FT REFER';
        case '40FT':
          return 'FEU - 1 X 40 FT REFER';
        default:
          return grossMassContainerPrint[0].containerSize;
      }
    })()
  ) : '-'
) : '-'}      {/* {grossMassContainerPrint?.container_size} */}
      </td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>7*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Maximum Permissible Weight Of Container as per the CSC plate</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>8*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Verified gross mass of container (method-1/method-2)</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>9*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Date and Time of Weighing</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>10*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Weighing Slip no.</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>11*</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Weighbridge Registration no. & Address of Weighbridge</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>12</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Type(Normal/Reefer/Hazardous/others)</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>13</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>If Hazardous , UN No, IMDG class</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>14</td>
      <td style={{ textAlign: 'left', border: '1px solid #000',borderLeft:"18px" }}>Vessel Name and VCN No</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
  </tbody>
</table>

<br /><br /><br />
<div style={{textAlign:"right"}}>
    <div>Signature of authorised person of shipper</div>
    <div>Name : 
    Mr.{" "}
  {grossMassContainerPrint && grossMassContainerPrint[0] ? (
    `${grossMassContainerPrint[0]?.empLastName ? grossMassContainerPrint[0]?.empLastName[0]?.toUpperCase() + "." : "-"}${
      grossMassContainerPrint[0]?.employeeName ? grossMassContainerPrint[0]?.employeeName?.toUpperCase() : "-"
    }`
  ) : (
    "-"
  )}

        {/* {grossMassContainerPrint?.employeeName} */}
        </div>
        <div>
    Date: {annexureCDetails?.invoiceDate && regexPattern.test(annexureCDetails.invoiceDate)
      ? formatDateString(annexureCDetails.invoiceDate.match(regexPattern)[0])
      : "--"}
  </div></div>
<br /><br />
<div style={{textAlign:"left"}}>
    <div>Remarks:</div>
    <div>*Indicates mandatory fields </div>
    <div>**Shippers not having IEC No. or CIN No. may provide information as follows:</div>
    <div>Company-PAN No.</div>
    <div>Individuals</div>
    {/* <div>Individuals</div> */}
    <div>Indian National-AADHAR No , Foreign National - PASSPORT No & Country of issue of Passport</div>
</div>
                </body>
            </html>
        </Card>
    </div>
  )
}

export default GrossMassContainerPrint