import {
  GlobalStatus,
  LoadingSheetSaleOrderReq,
  UomEnum,
} from '@gtpl/shared-models/common-models';
import { ExporterDataInput } from '@gtpl/shared-models/logistics';
import {
  FactoriesInput,
  PlantInvoiceDetailsModel,
  PlantInvoiceDetailsRequest,
  UnitsOfWeightInput,
} from '@gtpl/shared-models/sale-management';
import { ContainerRegisterService } from '@gtpl/shared-services/logistics';
import { RMGrnService } from '@gtpl/shared-services/raw-material-procurement';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Row } from 'antd';
import moment from 'moment';
// import "./annexure-c-print.css";
import React, { useEffect, useState } from 'react';

export interface AnnexureCProps {
  saleOrderId: number;
}

const AnnexureCPrint = (props: AnnexureCProps) => {
  const salOrderService = new SaleOrderService();
  const [annexureCDetails, setAnnexureCdetails] = useState<
    PlantInvoiceDetailsModel
  >();
  const [sdfPrint, setSdfPrint] = useState<any>([]);
  console.log(sdfPrint, 'sdfffffprintttttt');
  const [grossMassContainerPrint, setGrossMassContainerPrint] = useState<any>(
    []
  );
  const containerRService = new ContainerRegisterService();
  const propsId = props.saleOrderId;

  const service = new SaleOrderService();
  const [total,setTotal] =  useState(0)

  
  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, 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');
    element.document.write(divContents);
    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);
  };

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

  const getContainerPrintData = (saleorderId) => {
    containerRService
      .getGrossMassOfContainerPrintData(new LoadingSheetSaleOrderReq(propsId))
      .then((res) => {
        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 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) {
          setAnnexureCdetails(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) {
            setAnnexureCdetails(undefined);
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setAnnexureCdetails(undefined);
      });
  };

  // const [rmInvoicePrint, setRMInvoicePrint] = useState<any>([]);
  // const rmService = new RMGrnService();

  // useEffect(() => {
  //   if (props.grnId) {
  //     console.log(props);
  //     getRMInvoice(props.grnId);
  //   }
  // }, [props.grnId]);

  // const getRMInvoice = (grnId) => {
  //   // const req=new SoFormSdfPrintDto()
  //   rmService.getRMInvoicePrint(new RMInvoicePrintReq(grnId)).then((res) => {
  //     if (res.status) {
  //       setRMInvoicePrint(res.data);
  //     }
  //   });
  // };

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

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

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

const processingId = annexureCDetails?.invoicedPlant.companyId;
      const processingData = exporterDetails.find(item => item.value === processingId);
  
  let exporterPlant = FactoriesInput;
  const exportersPlant = exporterPlant.find(
    (item) => item.id == processingId
  )
  const tableData = () => {
    const tableDataArray = [];
    for (const data of annexureCDetails?.saleOrderItems) {
      const tableDataArray = data;
    }
  };


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

  const shippingDate = sdfPrint?.[0]?.shipping_bill_date;
  
  const formatDate = (isoDateString) => {
    const date = new Date(isoDateString);
    const day = date.getUTCDate().toString().padStart(2, '0');
    const month = (date.getUTCMonth() + 1).toString().padStart(2, '0'); 
    const year = date.getUTCFullYear();
    return `${day}-${month}-${year}`;
  };
  
  let extractedDate = '--';
  if (shippingDate) {
    extractedDate = formatDate(shippingDate);
  } else {
    console.error('Shipping date is undefined or null.');
  }
  
  console.log(extractedDate); 


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

const dateOfExamination = sdfPrint?.[0]?.examination_date;
const extractedExaminationDate = regexPatternDate.test(dateOfExamination) ? dateOfExamination.match(regexPattern)[0] : "--";

let formattedDate = "--";

if (extractedExaminationDate !== "--") {
  const dateParts = extractedExaminationDate.split('-');
  const day = dateParts[2]; 
  const month = dateParts[1]; 
  const year = dateParts[0];

  formattedDate = `${day}-${month}-${year}`;
}
let totalNetWeight=0
let finalNetWeight;
let totalLbWeight = 0;

const updatedRows = annexureCDetails?.gradeInfo?.map((g, prodIndex) => {
  return g?.info?.map((r, index) => {
    const uom = UnitsOfWeightInput.find((uom) => uom.value === r.uomId);


    if (uom.name === UomEnum.LB || uom.name === UomEnum.OZ) {
      finalNetWeight = (Number(r.quatity) * 0.454).toFixed(3);
    } else {
      finalNetWeight = Number(r.quatity).toFixed(3);
    }

    totalLbWeight += Number(finalNetWeight);

    return (
      <tr key={index}>
        <td className="ta-b" style={{ textAlign: "center" }}>
          {r.gradeNames}
          {r.grade && (
            <>
              <br />({r.grade})
            </>
          )}
        </td>
        <td className="ta-b" style={{ textAlign: "center" }}>
          {finalNetWeight
            ? Number(finalNetWeight).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })
            : 0}
        </td>
      </tr>
    );
  });
});


  return (
    <div >
      <Card
        title="ANNEXURE C"
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={
          <span style={{ color: 'white' }}>
            <Button onClick={printOrder} className="panel_button">
              Print
            </Button>
          </span>
        }
      >
        <html>
          <div id="printme">
          <body style={{ border: '1px solid #000' }}>
            <table style={{ width: '100%',lineHeight:'1.6', border: '1px solid #000', borderCollapse: 'collapse' }}>
          <p style={{ textAlign: 'center' }}>
              <b><u>ANNEXURE "C"</u></b>
            </p>
            <p style={{ textAlign: 'center' }}>
              <b>Examination Report For Self-sealed Container</b>
            </p>
            <div style={{ display: 'flex' }}>
              <div
                style={{
                  textAlign: 'left',
                  marginLeft: '18px',
                }}
              >
                Shipping Bill No :{" "}{sdfPrint?.[0]?.shipping_bill_no}
              </div>
              <div
                style={{
                  textAlign: 'left',
                  marginLeft: '100px',
                  marginTop: '0',
                  marginBottom: '0',
                }}
              >
                Date :{" "}{extractedDate}
              </div>
            </div>
            <div style={{ textAlign: 'left', marginLeft: '18px' }}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ width: '250px', marginRight: '10px' }}>
                  1. Name of the Exporter
                </div>
                <div>
                  :{" "}{exporterData?.company}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ width: '250px', marginRight: '10px' }}>2. (a) IEC No</div>
                <div>
                  :{" "}{exporterData?.ieCode}
                </div>
              </div>
              <div style={{ marginLeft: '18px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '232px', marginRight: '10px' }}>(b) Branch Code</div>
                  <div >
                    :{" "}{sdfPrint?.[0]?.branch_code}
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '232px', marginRight: '10px' }}>(c) BIN</div>
                  <div >:</div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '232px', marginRight: '10px' }}>(d) GSTIN</div>
                  <div >
                    :{" "}{exporterData?.GSTNumber}
                  </div>
                </div>
                <div style={{ marginLeft: '18px' }}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ width: '215px', marginRight: '10px' }}>
                      Name Of the Commissionerate
                    </div>
                    <div >
                      :{" "}{exporterData?.commissionerate}
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ width: '215px', marginRight: '10px' }}>Division</div>
                    <div>
                      :{" "}{exporterData?.division}
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ width: '215px', marginRight: '10px' }}>Range</div>
                    <div >
                      :{" "}{exporterData?.range}
                    </div>
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex' }}>
                <div style={{ width: '250px', marginRight: '10px' }}>
                  3. Factory/Place of Stuffing
                </div>
                <div >
                  :{" "} {processingData?.company ? processingData?.company : ''}
                
                  <br />
                  {processingData?.addressOne ? processingData?.addressOne + ',' : ''}
          <br />
          {processingData?.addressTwo
            ? processingData?.addressTwo + ' - ' + processingData?.postalCode
            : ''}
          <br />
          {processingData?.state + ', ' + processingData?.country}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ width: '250px', marginRight: '10px' }}>
                  4. Date Of Examination/Stuffing
                </div>
                <div>
                  :{" "}Date :{" "}{sdfPrint?.[0]?.examination_date?.replace(/\//g, '-')}
                </div>
              </div>
              <div style={{ display: 'flex' }}>
                <div style={{ width: '250px', marginRight: '10px' }}>
                  5. Description Of cargo with quantity
                </div>
                <div >
                  :{" "}
                  {(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 />{" "}
                  &nbsp;{(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'
                    )+' ' +'SHRIMP'+' '+
                    annexureCDetails?.saleOrderItems[0].valueAdditionFourIdName?.toLocaleUpperCase(
                      'en-US'
                    ) +
                    ' ' +
                    (totalLbWeight
                      ? Number(totalLbWeight)?.toLocaleString(undefined, {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        })
                      : 0) }{" "}KGS
                </div>
              </div>
              <p style={{ marginRight: '10px' }}>6. Time Of Stuffing :</p>
              <div style={{ marginLeft: '36px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '215px', marginRight: '10px' }}>Starting Time</div>
                  <div >
                    :{" "}{sdfPrint?.[0]?.stuffing_start_time}{" "}Hrs
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '215px', marginRight: '10px' }}>Completion Time</div>
                  <div>
                    :{" "}{sdfPrint?.[0]?.stuffing_completion_time}{" "}Hrs
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '215px', marginRight: '10px' }}>
                    Time Taken For Stuffing
                  </div>
                  <div >
                    :{" "}2{" "}Hrs
                  </div>
                </div>
              </div>
            
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ width: '250px', marginRight: '10px' }}>
                  7. Country of final destination
                </div>
                <div >
                  :{" "}{annexureCDetails?.country ? annexureCDetails?.country : ''}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ width: '250px', marginRight: '10px' }}>
                  8. Name & Designation of the Authorised Signatory
                </div>
                <div >
                  :{" "} Mr.{" "}
  {grossMassContainerPrint && grossMassContainerPrint[0] ? (
    `${grossMassContainerPrint[0]?.empLastName ? grossMassContainerPrint[0]?.empLastName[0]?.toUpperCase() + "." : "-"}${
      grossMassContainerPrint[0]?.employeeName ? grossMassContainerPrint[0]?.employeeName?.toUpperCase() : "-"
    }`
  ) : (
    "-"
  )}{" ,"} {grossMassContainerPrint != undefined
                      ? grossMassContainerPrint[0]?.designation
                        ? grossMassContainerPrint[0]?.designation?.toUpperCase()
                        : '-'
                      : '-'}{" ,"} {grossMassContainerPrint != undefined
                        ? grossMassContainerPrint[0]?.departmentName
                          ? grossMassContainerPrint[0]?.departmentName?.toUpperCase()
                          : '-'
                        : '-'}
                </div>
              </div>
              <p>9. Particulars of Export Invoice</p>
              <div style={{ marginLeft: '18px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '230px', marginRight: '10px' }}>(a) GST Invoice</div>
                  <div >
                    :{" "}{annexureCDetails?.invoiceNumber}{' '}
                    DATE:{moment(annexureCDetails?.invoiceDate).format(
                      'DD-MM-YYYY'
                    )}
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div style={{ width: '230px', marginRight: '10px' }}>
                    (b) Total No.Of packages
                  </div>
                  <div >
                    :{" "}
                    {/* {annexureCDetails?.saleOrderItems[0].invoicedCases} */}
                    {total?total:0}
                     CTNS
                  </div>
                </div>
                <div style={{ display: 'flex' }}>
                  <div style={{ width: '230px', marginRight: '10px' }}>
                    (c) Name & address of the consignee abroad
                  </div>
                  <div>
                  :{" "} 
                  {/* {annexureCDetails?.endCustomerName}
        &nbsp;{annexureCDetails?.endCustomerName ? ':' : ''}
        <br />
        &nbsp;{annexureCDetails?.saleOrderItems[0]?.buyerAddress?.split(',')}
        <br />
        &nbsp;{annexureCDetails?.country ? annexureCDetails?.country:''} */}
                  {annexureCDetails?.consignee}{' '}
                    {annexureCDetails?.consignee ? ':' : ''} <br />{' '}
                    {annexureCDetails?.consigneeAddress?.split(',')}
            <br />
                    {annexureCDetails?.country ? annexureCDetails?.country : ''}
                    {' '}
                      </div>
                </div>
              </div>
              <p>
                10. Is the description of the goods, the quantity, and their
                value as per particulars furnished in the Export Document / GST
                invoice :Yes
              </p>
              <p>11. Container Particulars:</p>
              <div style={{ marginLeft: '18px' }}>
                <table
                  style={{
                    borderCollapse: 'collapse',
                    width: '80%',
                    marginLeft: '100px',
                  }}
                >
                  <thead>
                    <tr>
                      <th
                        style={{
                          textAlign: 'center',
                          border: '1px solid #000',
                        }}
                      >
                        Container No
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          border: '1px solid #000',
                        }}
                      >
                        Size
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          border: '1px solid #000',
                        }}
                      >
                        Self Seal No
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          border: '1px solid #000',
                        }}
                      >
                        Line Seal No
                      </th>
                      <th
                        style={{
                          textAlign: 'center',
                          border: '1px solid #000',
                        }}
                      >
                        No.of Packages Stuffed in Container
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td style={{ textAlign: 'center',border: '1px solid #000' }}>
                        {sdfPrint?.[0]?.container_number}
                      </td>
                      <td style={{textAlign: 'center', border: '1px solid #000' }}>
                        {sdfPrint?.[0]?.container_size}
                      </td>
                      <td style={{textAlign: 'center', border: '1px solid #000' }}>
                        {sdfPrint?.[0]?.e_seal}
                      </td>
                      <td style={{ textAlign: 'center',border: '1px solid #000' }}>
                        {sdfPrint?.[0]?.line_seal}
                      </td>
                      <td style={{textAlign: 'center', border: '1px solid #000' }}>
                        {/* {annexureCDetails?.saleOrderItems[0].invoicedCases} */}
                        {total?total:0} CTNS
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <br />
              <p>12. Starting time (moving the container to CFS/ICD/Port):22.00Hrs</p>
              <p>
                I have examined the goods and the same are found to be as per
                the declaration. The goods are stuffed in the container and the
                container was sealed with "RFID tamper proof one-time-bolt seal"
                of specified standard. The seal Number is{' '}
                {sdfPrint?.[0]?.e_seal} IEC
                (Importer Exporter Code), Shipping Bill Number, Shipping Bill
                Date, e-seal Number, date of sealing. Time of sealing,
                Destination Customs station for Export, container Number,
                Trailer-Truck Number is tagged to the seal. I undertake full
                responsibility for any difference in description, quality or quantity of the
                goods.
              </p>
              <div style={{ marginLeft: '500px' }}>
                <p>Signature Of the Authorised Signatory of the Exporter</p>
                <p>
                  Name :{' '}
                  Mr.{" "}
  {grossMassContainerPrint && grossMassContainerPrint[0] ? (
    `${grossMassContainerPrint[0]?.empLastName ? grossMassContainerPrint[0]?.empLastName[0]?.toUpperCase() + "." : "-"}${
      grossMassContainerPrint[0]?.employeeName ? grossMassContainerPrint[0]?.employeeName?.toUpperCase() : "-"
    }`
  ) : (
    "-"
  )}
                </p>
                <p>
                  Designation :{' '}
                  {grossMassContainerPrint != undefined
                    ? grossMassContainerPrint[0]?.designation
                      ? grossMassContainerPrint[0]?.designation?.toUpperCase()
                      : '-'
                    : '-'}{" ,"} {grossMassContainerPrint != undefined
                      ? grossMassContainerPrint[0]?.departmentName
                        ? grossMassContainerPrint[0]?.departmentName?.toUpperCase()
                        : '-'
                      : '-'}
                </p>
                <p>Stamp :</p>
              </div>
            </div>
            </table>
          </body>
          </div>

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

export default AnnexureCPrint;
