import { ExporterDataInput } from '@gtpl/shared-models/logistics';
import { ConditionsRequest, PlantInvoiceDetailsModel, PlantInvoiceDetailsRequest, SoFormSdfPrintDto } 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, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
// import "./annexure-c-print.css";
export interface AppendixPrintProps {
  saleOrderId: number;
}

const AppendixPrint = (props: AppendixPrintProps) => {

  const [sdfPrint, setSdfPrint] = useState<any>([])
  const service=new SaleOrderService()
  const location = useLocation()
  const [plantDetails, setPlantDetails] = useState<PlantInvoiceDetailsModel>();

  useEffect(() => {
    // setRemarksData("text");
    if (props.saleOrderId) {
      getData(props.saleOrderId);
    }
    // window.print()
  }, [props.saleOrderId]);
  
  useEffect(() => {
    if (props.saleOrderId) {
      getFormSdf(props.saleOrderId);
    }
  }, [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);
  service
    .getPlantInvoiceDetails(new PlantInvoiceDetailsRequest(props.saleOrderId))
    .then((res) => {
      if (res.status) {
        setPlantDetails(res.data);
      } else {
        if (res.intlCode) {
          setPlantDetails(undefined);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    })
    .catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setPlantDetails(undefined);
    });
};

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+\-+\d+\-+\d+/;

const shippingDate = sdfPrint?.[0]?.shipping_bill_date;
const extractedDate = regexPattern.test(shippingDate) ? shippingDate.match(regexPattern)[0] : "--";

let formattedDate = "--";

if (extractedDate !== "--") {
  const dateParts = extractedDate.split('-');
  const day = dateParts[2]; // Year
  const month = dateParts[1]; // Month
  const year = dateParts[0]; // Day

  formattedDate = `${day}-${month}-${year}`;
}

console.log(`Date: ${formattedDate}`);

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


// const regexPattern = /\d+\-+\d+\-+\d+/; 

// const shippingDate = sdfPrint?.[0]?.shipping_bill_date;
// const extractedDate = regexPattern.test(shippingDate) ? shippingDate.match(regexPattern)[0] : "--";
  // const printOrder = () => {
  //   const divContents = document.getElementById('printme').innerHTML;
  //   const secondPageContents = document.getElementById('secondPage').innerHTML;
  //   const thirdPageContents = document.getElementById('thirdPage').innerHTML;
  //   const forthPageContents = document.getElementById('forthPage').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}${secondPageContents}${thirdPageContents}${forthPageContents}</body>
  //         </html>
  //       `;
  //   element.document.write(style);
  //   element.document.close();
  //   element.print();
  //   element.close();
  // };

  const getCssFromComponent = (fromDoc, toDoc) => {
      Array.from(fromDoc.styleSheets).forEach((styleSheet: any) => {
        console.log(styleSheet.cssRules);
        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;
      const thirdPageContents = document.getElementById('thirdPage').innerHTML;
      const forthPageContents = document.getElementById('forthPage').innerHTML;
      const element = window.open('', '', 'height=700, width=1024');
      // element.document.write(divContents,secondPageContents,thirdPageContents,forthPageContents);
      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-before: always;
                }
      
                .no-page-break {
                  page-break-inside: avoid;
                }
      
                #printme, #secondPage, #thirdPage, #forthPage {
                  page-break-after: always;
                }
      
                /* Add this rule to ensure text is not transformed */
                body, div, p, span, b, h1, h2, h3, h4, h5, h6 {
                  text-transform: none;
                }
              }
            </style>
          </head>
          <body>
            <div id="printme">${divContents}</div>
            <div id="secondPage" class="page-break">${secondPageContents}</div>
            <div id="thirdPage" class="page-break">${thirdPageContents}</div>
            <div id="forthPage" class="page-break">${forthPageContents}</div>
          </body>
        </html>
      `;
      
      // getCssFromComponent(document, element.document);
      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 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);
  };

  return (
    <div>
      <div>
        <Card
          title="FORM SDF"
          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: 'right' }}>
              <b>APPENDIX-I</b>
                </div>
              <div style={{ textAlign: 'center', }}>
                 <b> FORM SDF</b>
                <div>
                    <b>[Declaration Under The Foreign Exchange Regulation Act,1973]</b>
                  {/* </h1> */}
                </div>
                <br />
                <div
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
                  <div style={{ textAlign: 'left',marginLeft: '18px',
                        marginTop: '0',
                        marginBottom: '0', }}>
                      Shipping Bill No :{" "}<b>{sdfPrint?.[0]?.shipping_bill_no}</b>
                  </div>
                  <div style={{ textAlign: 'right',marginLeft: '18px',
                        marginTop: '0',
                        marginBottom: '0', }}>
                      Date :{" "}{formattedDate}
                  </div>
                </div>
                <div
                  style={{
                    textAlign: 'start',
                    // fontSize: '12px',
                    // fontFamily: 'Un Shinmun',
                    marginLeft: '18px',
                    marginTop: '0',
                    marginBottom: '0',
                  }}
                >
                    <p>Declaration Under Foreign Exchange Management Act . 1999</p>
                    <p>
                      I/We,{exporterData?.company ? exporterData?.company : ''}, hereby declare that:
                    </p>
                    <br />
                    <p>
                      I/We am/are the SELLER/CONSIGNOR of the goods in respect
                      of which this declaration is made and that the particulars
                      given in the Shipping Bill No :{" "}<b>{sdfPrint?.[0]?.shipping_bill_no}</b></p>
                      <div
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
                      <div style={{ textAlign: 'left',
                        marginTop: '0',
                        marginBottom: '0', }}> are true and that:
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      Date :{" "}{formattedDate}</div>
                    </div>
                    {/* <p>are true and that:</p> */}
                    <br />
                    <p>
                      a. The Value as contracted with the buyer is the same as
                      the full export value declared in the above shipping bill.
                    </p>
                    <p>
                      b. The full export value of the goods is not ascertainable at
                      the time of export and that the value declared is that
                      which I/We having regard to the market conditions expect
                      to receive on the sale of goods in the overseas market.
                    </p>
                    <p>
                      That I/We undertake that I/We will deliver to the bank
                      named {sdfPrint?.[0]?.bank_details} the foreign
                      exchange representing the full export value of the goods
                      on or before {sdfPrint?.[0]?.bankReachedDate} in the manner prescribed in Rule
                      9 of the Foreign Exchange Management Act 1999.
                    </p>
                    <p>
                      That I/We am/are a resident(s) in India and I/We have a
                      place of business in India
                    </p>
                    <p>
                      That I/We*am/are OR am/are not in the caution list of the
                      Reserve Bank Of India.
                    </p>
                    <div style={{ textAlign: 'right' }}>
                      <p>For {exporterData?.company ? exporterData?.company : ''}</p>
                    </div>
                    <p>
  <h4>Date :{" "}{formattedDate}</h4>
</p>

                    <div style={{ textAlign: 'right' }}>
                      <p>
                        <b>Authorized Signatory</b>
                      </p>
                    </div>
                    <p>
                      Note: A State appropriate date of delivery which must be
                      the due date for payment or within 6 months from the date
                      of shipment whichever is earlier, but for exports to
                      warehouses established outside India with permission of
                      the Reserve Bank, the date of delivery must be within 15
                      months.
                    </p>
                  {/* </h2> */}
                </div>
              </div>
            </body>
          </html>
        </Card>
      </div>
      <div id="secondPage" >
        <Card
        className="page-break"
        //   title="APPENDIX-III"
        //   style={{ textAlign: 'center' }}
        //   headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        >
          <html>
            <body>
            <div style={{ textAlign: 'center',   lineHeight: '10px',
                    paddingTop: '20px', }}>
                       <b> APPENDIX-III</b>
                    </div>
              <div style={{ textAlign: 'center',   lineHeight: '10px',
                    paddingTop: '20px', }}>
                {/* <h1
                  style={{
                    // fontSize: '16px',
                    lineHeight: '10px',
                    paddingTop: '20px',
                  }}
                > */}
                 <b> DRAWBACK/DEEC DECLARATION</b>
                {/* </h1> */}
              </div>
              <div   style={{
                textAlign: 'center',
                    // fontSize: '16px',
                    lineHeight: '10px',
                    paddingTop: '20px',
                  }}>
                {/* <h1
                  style={{
                    // fontSize: '16px',
                    lineHeight: '10px',
                    paddingTop: '20px',
                  }}
                > */}
                 <b> (To be filled for exporter goods under claim for Drawback)</b>
                {/* </h1> */}
              </div>
              <br />
              <div
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
              <div style={{ textAlign: 'left',marginLeft: '18px',
                    marginTop: '0',
                    marginBottom: '0', }}>
                  Shipping Bill No :{" "}<b>{sdfPrint?.[0]?.shipping_bill_no}</b>
              </div>
              <div style={{ textAlign: 'right',   marginRight: '18px',
                    marginTop: '0',
                    marginBottom: '0', }}>
                  Date :{" "}{formattedDate}
              </div>
              </div>
              <div
                style={{
                  textAlign: 'start',
                //   fontSize: '12px',
                //   fontFamily: 'Un Shinmun',
                  marginLeft: '18px',
                  marginTop: '0',
                  marginBottom: '0',
                }}
              >
                  <p>
                    <b>I/We:</b>{exporterData?.company ? exporterData?.company : ''} <b>. do hereby further declare as follows:</b>
                  </p>
                  <div>
                  <p>
                    1 . That the quality and specification of the goods as
                    stated in this shipping bill are in accordance with the
                    terms of the exports contract entered into with the
                    buyer/consignee in pursuance of the goods which are being
                    exported.
                  </p>
                  <p>
                    2 . That we are not claiming benefit and in the quantum
                    export goods and hat the materials or components under
                    "Engineering Products Export (Replenishment of iron and
                    steel intermediates) Scheme" Notified vide ministry of
                    commerce Notificate <b>No 539 Re/92-97 dated 01-03-95.</b>
                  </p>
                  <p>
                    3 . That there is no change in the manufacturing formula
                    which have been stated in the application under rule 7 of
                    the D.B.K. Rules, 1995 to have been imported, continue to be
                    so imported and are not been obtained from indigenous
                    sources.
                  </p>
                  <p>
                    4 . (a) That the export goods have not been manufactured by
                    availing the procedure under the Rule
                  </p>
                  <p style={{marginLeft:"18px"}}>
                    (b) That the export goods have been manufactured by availing
                    the procedure under the Rule.
                  </p>
                  <p>
                  <p style={{ textIndent: '-2em', paddingLeft: '2em' }}>
                    5. (a) That the export goods are not manufactured and/or exported in discharge 
                    of export obligation against an Advance Licence issued under the Duty 
                    Exemption Scheme (DEEC) vide-relevent import and Export Policy in Force.
                  </p>

                   
                    <p style={{marginLeft:"12px"}}>
                      (b)That goods are manufactured and are being exported in
                      discharge of export obligation under Duty Exemption Scheme
                      (DEEC), in terms of Notification <b>No79/95-Cus or 80/95-Cus</b>{" "}
                      both dated <b>31-3-95 or  31/97 dated 01-04-97</b> but I/We are claiming
                      Drawback of only the Central Excise portion of the dutied on
                      inputs in the drawback Schedule.
                    </p>
                    <p style={{marginLeft:"12px"}}>
                      (c)That the goods are manufactured and are being exported
                      in discharge of export obligation under the duty exemption scheme
                      (DEEC), but I/We are claiming brand rate of drawback fixed
                      under rule 6 to 7 of the D.B.K. Rules 1995.
                    </p>
                  </p>
                  <p>
                    6 . That the goods are not manufactured and/or exported
                    after availing of the facility under the Pass Book scheme as contained
                    in <b>para7.25</b> of the Export and Import Policy (Apr. That the
                    goods are not manufactured and or exported after availing of the
                    facility il, 1997-31 march 2002)
                  </p>
                  </div>
                {/* </h2> */}
              </div>
            </body>
          </html>
        </Card>
      </div>
      <div id="thirdPage">
        <Card  className="page-break">
            <html>
                <body>
<div style={{textAlign:"left",  marginLeft: '18px',
                  marginTop: '0',
                  marginBottom: '0',}}>
   
        <p>7 . That the goods are not manufactured and/or exported by a unit licenced and 100% Exporter oriented Unit in terms of Import and Export Policy in Force.
</p>
<p>8 . That the goods are not manufactured and/or exported by a unit situated in a Free Trade Zone/Export Processing Zone or any other such Zone.

</p>
<p>9 . That the goods are not manufactured partly of wholly inbond under section65 of the Customs Act, 1962
</p>
<p>10 . The present market value of the goods is as follow
</p>

<div style={{ textAlign: 'center' }}>
<table style={{ borderCollapse: 'collapse', width: '60%',  marginLeft: '200px',
                  marginTop: '0',
                  marginBottom: '0' }}>
  <thead>
    <tr>
      <th style={{ textAlign: 'center', border: '1px solid #000' }}>S.No</th>
      <th style={{ textAlign: 'center', border: '1px solid #000' }}>Item No. in the Invoice</th>
      <th style={{ textAlign: 'center', border: '1px solid #000' }}>Market Value</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
    <tr>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
      <td style={{ border: '1px solid #000' }}>&nbsp;</td>
    </tr>
  </tbody>
</table>

</div>
<div style={{textAlign:"left",  marginLeft: '18px',
                  marginTop: '0',
                  marginBottom: '0',}}>
<p>11 . That the export value of goods covered by this Shipping Bill is not less the value
of all imported
materials used in manufacture of such goods</p>
<p>12 .  That the market price of the goods being exported is not less than the drawback amount being claimed

</p>
<p>13 . That the drawback amount claimed is more than 1% of the FOB value of the export product, or the drawback amount claimed is less than 1% FOB value but more than <b>Rs.500.00</b> against the Shipping Bill,
</p>
<p>14. I/ We undertake to repatriate export proceeds within 6month from date of export and submit B.R.C to Asst. Commissioner (Drawback), in case, the export proceeds are not realized within 6months from the date of export, I/We will either furnish extension of time R.B.I, and submit B.R.C within such extended period or will pay back the drawback received against this Shipping Bill.
</p>
<p style={{textAlign:"right"}}>For {exporterData?.company ? exporterData?.company : ''}</p>
<br />
<p style={{textAlign:"right"}}><b>Authorized Signature</b></p>

<p style={{textAlign:"left"}}>Date {" "}:{" "}{formattedDate}</p>
</div>
</div>
                </body>
            </html>
        </Card>
      </div>
      <div id="forthPage" >
<Card className="page-break">
    <html>
        <body>
            <div style={{textAlign:"center"
 }}>{exporterData?.company ? exporterData?.company : ''}</div>
 <div style={{textAlign:"center"
 }}> <b>APPENDIX-IV
 </b></div>
        <div style={{textAlign:"left",  marginLeft: '18px',
                  marginTop: '0',
                  marginBottom: '0',}}>

<p><b>(Declaration to be filled in respect of goods for which drawback under SI Nos....</b>
</p>
<p><b>03.02, 03.03, 04.03, 07.03, 08.02, 08.03, 09.02, 09.03, 16.02, 16.03, 17.02, 17.03, 18.03, 19.02, 19.03,

20.03, 20.02, 20.06, 20.06, 20.07, 20.11, 20.12, 20.16, 21.02, 39.01, 39.03, 39.09.39.06, 39.07, 39.09,

39.11, 39.12, 39.13, 39.14, 39.15, 39.17, 39.18, 39.20, 39.24, 42.01, 42.02, 42.05, 42.06, 42.10, 42.12,52.02, 52.03, 52.04. 52.05, 52.04, 52.05, 54.04,54.06, 55.01,55.02, 55.03, 55.04, 55.05, 56.04, 58.01,



58.02, 58.03, 60.06, 61.02, 61.05, 61.07, 62.02, 62.09, 62.10 62.21, 63.01, 63.04, 63.06, 63.07, 63.07,

63.08, 63.10, 63.11, 73.11, 73.15, 73.22, 74.04, 74.05, 74.05, 04.06, 74.07, 74.13, 73.04, 82.01, 86.07,

84.26, 84.58, 85.37, 85.40, 85.120, 85.154, 87.45, Has been claimed)</b></p>
<div
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
<div  style={{textAlign:"left" }}>
<p><b>Shipping Bill Number :{" "}{sdfPrint?.[0]?.shipping_bill_no}</b></p>
</div>
<div  style={{textAlign:"right" }}>
<p>Date :{" "}{formattedDate}</p>
</div>
</div>
<div>
<p><b>I/We: {exporterData?.company ? exporterData?.company : ''}

. (Name of the Exporter) do hereby</b> declare as follow:</p>
<p>1 . That no Cen vet facility has been availed for any of the inputs used in the manufacture of export products.
</p>
<p>2 . That the goods are being exported under bond or claim for rebate of Central Excise Duty and a

Certificate from concerned Superintendent of Central Excise, in charge of factory of production

to the effect that Modvat facility has not been availed for the goods export is enclosed (Drawback as per schedule is applicable).
</p>
<p style={{textAlign:"right"}}>
For {exporterData?.company ? exporterData?.company : ''}
</p>
<p style={{textAlign:"left"}}>
Date :{" "}{formattedDate}
</p>
<p style={{textAlign:"right"}}>
<b>Authorized Signatory</b>
</p>
</div>
            </div> 
        </body>
    </html>
</Card>
      </div>
    </div>
  );
};

export default AppendixPrint;
