import { ExporterDataInput } from '@gtpl/shared-models/logistics';
import { FactoriesInput, 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, Card, Form } from 'antd';
import React, { useEffect, useState } from 'react';
import CustomsInvoice from './new-customs-invoice';

export interface DeclarationFormProps {
    saleOrderId: number;
  }

export function DeclarationForm (props: DeclarationFormProps)  {

    const salOrderService = new SaleOrderService();
    const [declarationFormDetails, setDeclarationFormDetails] = useState<any>();
    const [annexureCDetails, setAnnexureCdetails] = useState<PlantInvoiceDetailsModel>();
    const [compName, setCompName] = useState<string>('');

    //    useEffect(()=>{getData()},[])

    useEffect(() => {
      // Assuming compName is determined somewhere in your code
      setCompName('CustomsInvoice');
    }, []);

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


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

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


      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 regexPattern = /\d{4}-\d{2}-\d{2}/; 

      const formatDateString = (dateString) => {
        const [year, month, day] = dateString.split('-');
        return `${day}-${month}-${year}`;
      };
      
      const invoiceDate = declarationFormDetails?.[0]?.invoice_date;
      const shippingDate = declarationFormDetails?.[0]?.expected_delivery_date;
      
      const extractedDate = regexPattern.test(shippingDate) ? formatDateString(shippingDate.match(regexPattern)[0]) : "--";
      
      const extractedInvoiceDate = regexPattern.test(invoiceDate) ? invoiceDate.match(regexPattern)[0] : "--";

      let exporterDetails = ExporterDataInput;
      const exporterData = exporterDetails.find(
        (item) => item.value == annexureCDetails?.exporterId );

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

      // 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 secondPageContents = document.getElementById('secondPage').innerHTML;
        const element = window.open('', '', 'height=700, width=1024');
        // element.document.write(divContents,secondPageContents,thirdPageContents,forthPageContents);
        element.document.write(`
        <html>
          <head>
            <style>
              @media print {
                .page-break {
                  page-break-before: always;
                }
    
                .no-page-break {
                  page-break-inside: avoid;
                }
    
                #printme, #secondPage, #thirdPage, #forthPage {
                  page-break-after: always;
                }
              }
            </style>
          </head>
          <body>
            <div id="printme">${divContents}</div>
            <div id="secondPage" class="page-break">${secondPageContents}</div>
          </body>
        </html>
      `);
        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 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;
      //                 }
      //                 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 downloadAsPDF = () => {
        const element = document.getElementById('printme');
        const options = {
          margin: 6,
          width: '100%',
          filename: 'PO.pdf',
          image: { type: 'jpeg', quality: 1.0 },
          html2canvas: { scale: 2 },
          jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' },
        };
    
        // html2pdf(element, options);
      };

const invoiceLogisticsDate = annexureCDetails?.invoiceDate;

const formatDate = (dateString) => {
  if (!dateString) return '--'; // Handle case where dateString is undefined or null
  const date = new Date(dateString);
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
  const year = date.getFullYear();
  return `${day}-${month}-${year}`;
};

  return (
    <div >
      <Card
    title="DECLARATION FORM"
    style={{ textAlign: 'center' }}
    headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    extra={
      <span style={{ color: 'white' }}>
        <Button onClick={printOrder} className="panel_button">
          Print
        </Button>
      </span>
    }
>
  <div>
   
    
    <div id='printme'>
      <div style={{
            textAlign: 'center',
            marginTop: '0',
            marginBottom: '0',
        }}>
        <b>DECLARATION FORM</b>
      </div>
    <p
        style={{
            textAlign: 'right',
            marginRight: '18px',
            marginTop: '0',
            marginBottom: '0',
        }}
    >
Date: {new Date().toLocaleDateString('en-GB')}
</p>
    <br />
        <p style={{ textAlign: 'left', whiteSpace: 'pre-line' }}>
            <Form>
            I, <u>{declarationFormDetails?.[0]?.employee_name}</u> Authorized signatory of {' '}
            <u>{exporterData?.name}</u> on their behalf declare that, I am fully aware of the composition
            of the consignment of <u>{declarationFormDetails?.[0]?.productName}</u> <u>on{' '}
            {declarationFormDetails?.[0]?.productDescription}</u>
            {/* {((annexureCDetails?.saleOrderItems[0]?.foodTypeCode?.toLocaleUpperCase('en-US').charAt(0) == "C") ? 'COOKED' : annexureCDetails?.saleOrderItems[0]?.foodTypeName?.toLocaleUpperCase('en-US')) + ' FROZEN ' + ((annexureCDetails?.saleOrderItems[0].valueAdditionOneIdCode === 'EZPeel') ? ' HEADLESS ' : '') + annexureCDetails?.saleOrderItems[0].valueAdditionOneIdName?.toLocaleUpperCase('en-US') + ' ' + (
                          (!(([
                            'HLSO', 'HOSO', 'EZPeel', 'N/A'
                          ].indexOf(annexureCDetails?.saleOrderItems[0].valueAdditionOneIdCode)) > -1) ? " AND " : '')
                        ) + (annexureCDetails?.saleOrderItems[0].valueAdditionTwoIdCode ? annexureCDetails?.saleOrderItems[0].valueAdditionTwoIdName?.toLocaleUpperCase('en-US') : '')}<br />{(annexureCDetails?.saleOrderItems[0].valueAdditionThreeIdCode ? annexureCDetails?.saleOrderItems[0].valueAdditionThreeIdName?.toLocaleUpperCase('en-US') : '') + ' ' + (annexureCDetails?.saleOrderItems[0].valueAdditionFiveIdCode ? annexureCDetails?.saleOrderItems[0].valueAdditionFiveIdName?.toLocaleUpperCase('en-US') : '') + ' ' + annexureCDetails?.saleOrderItems[0].itemName?.toLocaleUpperCase('en-US')  + annexureCDetails?.saleOrderItems[0].valueAdditionFourIdName?.toLocaleUpperCase('en-US')} */}
                         (name of products) <u>{declarationFormDetails?.[0]?.packing_method_name}</u>(type of packing) and (brand name) <u> {(annexureCDetails?.saleOrderItems[0].brandName ? annexureCDetails?.saleOrderItems[0].brandName?.toLocaleUpperCase('en-US') : '')}</u>{" "}
                           shipped
            Invoice No: <u>{declarationFormDetails?.[0]?.invoice_number}</u> Dated: <u>{formatDate(invoiceLogisticsDate)}</u> and
            Bill of Lading No <u>{declarationFormDetails?.[0]?.bl_no}</u> Dated <u>{extractedDate}</u> and the above
            consignment does not contain deep sea shrimps and contain only shrimps mentioned in the Raw
            Material Register, a copy of the relevant page of which is enclosed. I am fully aware that
            myself and the company / firm are fully responsible and liable for penal action and / or
            deregistration as an exporter under the MPEDA Act & Rules if the details of consignment
            mentioned above including its composition are found to be incorrect by the MPEDA or any
            other Agency in India or in the United States or elsewhere.
            </Form><br />
            <p>
            Signed This
            </p><br />
            <p>
            Signature
            </p><br />
            <p>
            Witness
            </p><br />
            <p>
            1.A.SAI MANOJ
            </p><br />
            <p>
            2.U.MAHESH
            </p>
        </p>
    </div>
    </div>
  
</Card>

<div id="secondPage">
  <Card  className="page-break">
  {compName === 'CustomsInvoice' && (
          <CustomsInvoice saleOrderId={props.saleOrderId} showStuffingCertificate={false}/> )}

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

export default DeclarationForm;
