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 } from 'antd'
import moment from 'moment';
import React, { useEffect, useState } from 'react'
import logo from './bmr-logo.png';

export interface AnnexureDTptProps {
  saleOrderId: number;
}

const AnnexureDTptPrint = (props: AnnexureDTptProps) => {
    const salOrderService = new SaleOrderService();
    const [annexureDDetails, setAnnexureDdetails] = useState<PlantInvoiceDetailsModel>();
    const [sdfPrint, setSdfPrint] = useState<any>([])
    
    const service=new SaleOrderService()
    const [total,setTotal] =  useState(0)

  
    let exporterDetails = ExporterDataInput;
    const exporterData = exporterDetails.find(
      (item) => item.value == annexureDDetails?.exporterId );
  
    let unitInput = FactoriesInput;
    const unitsData = FactoriesInput.find(item => item.id == annexureDDetails?.unitId)
    const tableData = () => {
      const tableDataArray = [];
      for (const data of annexureDDetails?.saleOrderItems) {
        const tableDataArray = data;
      }
    };

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

    const getFormSdf = (saleOrderId) => {
      // const req=new SoFormSdfPrintDto()
      service.getFormSdfPrint(new PlantInvoiceDetailsRequest(props.saleOrderId)).then(res => {
          if (res.status) {
            setSdfPrint(res.data)
          }
      })
  }
  
    const getData = (saleOrderId) => {
      // const reqObj = new PlantInvoiceDetailsRequest(1);
      salOrderService.getPlantInvoiceDetails(new PlantInvoiceDetailsRequest(props.saleOrderId)).then((res) => {
        if (res.status) {
          setAnnexureDdetails(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)
        } else {
          if (res.intlCode) {
            setAnnexureDdetails(undefined);
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
        }
      })
        .catch((err) => {
          AlertMessages.getErrorMessage(err.message);
          setAnnexureDdetails(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);
      // 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;
    //                 }
    //                 .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();
    // };
  
    return (
      <div>
          <Card title="ANNEXURE D"
            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'>
                  <div style={{textAlign:"center"}}>
                  <p>ANNEXURE 'D' TO FACILITY CIRCULAR NO.26/2017 Dt.01.07.2017</p>
                  <p> (Application intimating shipment / Premises of self-sealing of export containers)</p>
                  </div>
                  <div  style={{
                      textAlign: 'start',
                      marginLeft: '36px',
                      marginTop: '0',
                      marginBottom: '0',
                    }}>
                  <div>To,</div>
                  <div>The Jurisdictional Superintendent of Customs </div>
                  <div>Tirupati,Andhra Pradesh 517502</div>
                  </div>
                  <div
              style={{
                textAlign: 'start',
                marginLeft: '18px',
                marginTop: '0',
                marginBottom: '0',
              }}
            >
              <p>
                Sir,
                <p
                  style={{
                    textAlign: 'start',
                    marginLeft: '56px',
                    marginTop: '0',
                    marginBottom: '0',
                  }}
                >
                  With reference to facility circular no. 26/2017.
                  Dt.01.07.2017, I/We hereby intimate our export program, the
                  goods that we propose to export, the premises from which we
                  planned too and the details are as follows:
                </p>
              </p>
            </div>
            <br />
            <div
              style={{
                textAlign: 'start',
                marginLeft: '18px',
                marginTop: '0',
                marginBottom: '0',
              }}
            >
             <div style={{ display: 'flex', alignItems: 'center' }}>
  <div
    style={{
      flex: '0 0 auto',
      marginRight: '160px', // Adjust this value to control the gap between the two divs
      textAlign: 'left',
      marginLeft: '18px',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    1.LOSSP No & Dt
  </div>
  <div
    style={{
      flex: '1',
      textAlign: 'left',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    : C.No.VIII/48/177/2018-Cus.TFCHQ dated: 12.09.2018
  </div>
</div>
<br />

<div style={{ display: 'flex', alignItems: 'flex-start' }}>
  <div
    style={{
      flex: '0 0 auto',
      marginRight: '85px', // Adjust this value to control the gap between the two divs
      textAlign: 'left',
      marginLeft: '18px',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <div>2.Address of the premises from</div>
    <div>Where self-sealing is done</div>
  </div>
  <div
    style={{
      flex: '1',
      textAlign: 'left',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <p>
      :{exporterData?.company ? exporterData?.company : ''}
      <br />
      &nbsp;{exporterData?.addressOne ? exporterData?.addressOne + ',' : ''}
      <br />
      {/* <span style={{ marginLeft: '80px' }}> */}
      &nbsp;{exporterData?.addressTwo
          ? exporterData?.addressTwo + ' - ' + exporterData?.postalCode
          : ''}
        <br />
        &nbsp;{exporterData?.state + ', ' + exporterData?.country}
      {/* </span> */}
    </p>
  </div>
</div>

              <br />
              <div style={{ display: 'flex', alignItems: 'flex-start' }}>
  <div
    style={{
      flex: '0 0 auto',
      marginRight: '100px', // Adjust this value to control the gap between the two divs
      textAlign: 'left',
      marginLeft: '18px',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <div>3.Description of goods to be</div>
    <div>Stuffed and exported</div>
  </div>
  <div
    style={{
      flex: '1',
      textAlign: 'left',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <p>:{total?total:0}
      {/* {annexureDDetails?.saleOrderItems[0].invoicedCases} */}
      {" "}CTNS{" "}<br />
      &nbsp;{(annexureDDetails?.saleOrderItems[0]?.foodTypeCode
        ?.toLocaleUpperCase('en-US')
        .charAt(0) == 'C'
        ? 'COOKED'
        : annexureDDetails?.saleOrderItems[0]?.foodTypeName?.toLocaleUpperCase(
            'en-US'
          )) +
        ' FROZEN ' +
        (annexureDDetails?.saleOrderItems[0]
          .valueAdditionOneIdCode === 'EZPeel'
          ? ' HEADLESS '
          : '') +
        annexureDDetails?.saleOrderItems[0].valueAdditionOneIdName?.toLocaleUpperCase(
          'en-US'
        ) +
        ' ' +
        (!(
          ['HLSO', 'HOSO', 'EZPeel', 'N/A'].indexOf(
            annexureDDetails?.saleOrderItems[0]
              .valueAdditionOneIdCode
          ) > -1
        )
          ? ' AND '
          : '') +
        (annexureDDetails?.saleOrderItems[0]
          .valueAdditionTwoIdCode
          ? annexureDDetails?.saleOrderItems[0].valueAdditionTwoIdName?.toLocaleUpperCase(
              'en-US'
            )
          : '')}
      <br />
      <span>
        &nbsp;{(annexureDDetails?.saleOrderItems[0]
          .valueAdditionThreeIdCode
          ? annexureDDetails?.saleOrderItems[0].valueAdditionThreeIdName?.toLocaleUpperCase(
              'en-US'
            )
          : '') +
          ' ' +
          (annexureDDetails?.saleOrderItems[0]
            .valueAdditionFiveIdCode
            ? annexureDDetails?.saleOrderItems[0].valueAdditionFiveIdName?.toLocaleUpperCase(
                'en-US'
              )
            : '') +
          ' ' +
          annexureDDetails?.saleOrderItems[0].itemName?.toLocaleUpperCase(
            'en-US'
          ) +
          ' ' +'SHRIMP'+' '+
          annexureDDetails?.saleOrderItems[0].valueAdditionFourIdName?.toLocaleUpperCase(
            'en-US'
          )}
      </span>
      <br />
      {/* {sdfPrint[0]?.productDescription}{""}<br /> */}
      <span>
      &nbsp;(INVOICE NUMBER: {annexureDDetails?.invoiceNumber}{" "} DATE: {moment(annexureDDetails?.invoiceDate).format('DD-MM-YYYY')})
      </span> 
    </p>
  </div>
</div>
<br />
<div style={{ display: 'flex', alignItems: 'flex-start' }}>
  <div
    style={{
      flex: '0 0 auto',
      marginRight: '45px', // Adjust this value to control the gap between the two divs
      textAlign: 'left',
      marginLeft: '18px',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <div>4.whether any incentives </div>
    <div>Is being claimed </div>
  </div>
  <div
    style={{
      flex: '1',
      textAlign: 'left',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <div style={{ marginLeft: '80px' }}> :YES </div>
  </div>
</div>

            </div>
            <br />
<div style={{ display: 'flex', alignItems: 'flex-start' }}>
  <div
    style={{
      flex: '0 0 auto',
      marginRight: '55px', // Adjust this value to control the gap between the two divs
      textAlign: 'left',
      marginLeft: '36px',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <div>5.Customs station from </div>
    <div>which the goods are </div>
    <div>to be exported </div>
  </div>
  <div
    style={{
      flex: '1',
      textAlign: 'left',
      marginTop: '0',
      marginBottom: '0',
    }}
  >
    <div style={{ marginLeft: '80px' }}> :PORT OF LOADING : {annexureDDetails?.portofloading} </div>
 <div style={{ marginLeft: '80px' }}>  &nbsp;PORT OF DISCHARGE :{(annexureDDetails?.saleOrderItems[0]?.destinationDetails
                    ? annexureDDetails?.saleOrderItems[0]?.destinationDetails
                    : '') +
                    ',' +
                    (annexureDDetails?.country ? annexureDDetails?.country : '')}  </div>
  </div>
</div>

         
            <br /><br />
            <div
              style={{
                textAlign: 'left',
                marginLeft: '300px',
                marginTop: '0',
                marginBottom: '0',
              }}
            >
              <p>Mr.M.RAGHU RAM </p>

            </div>
            <br />
            <div
              style={{
                textAlign: 'left',
                marginLeft: '280px',
                marginTop: '0',
                marginBottom: '0',
              }}
            >
              <p>DEPUTY GENERAL MANAGER FINANCE & ACCOUNTS</p>

            </div>
                 
                </body>
              </html>
          </Card>
      </div>
    )
  }
export default AnnexureDTptPrint