import React from 'react'
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import { getSession } from '../../../../Services/Others';
import { getBranchDetail } from '../../../../Features/BrachLogin/BranchLogin';
import {
  GlobalprintSlNo,
  GlobalprintItem,
  GlobalprintMRP,
  GlobalprintDiscount,
  GlobalprintQuantity,
  GlobalprintRate,
  GlobalprintAmount,
  GlobalprintHsnCode,
  GlobalprintQrcodet,
  GlobalPritdummyData
} from '../../../../Features/ThemeChange/ThemeChange';
import '../../../../Styles/BookingScreen/PrintTemplates/ThermalPrinter/PrintStyle13.scss';


const PrintStyle13 = ({ orderId, CreatedDate, singleData2, table2Data, ExtraChargeDetails }) => {
  let OfferAmount = table2Data?.OrderOfferDetails?.reduce((acc, item) => {
    return acc + item.OfferAmount;
  }, 0);

  const GlobalSlNo = useSelector(GlobalprintSlNo)
  const GlobalItem = useSelector(GlobalprintItem)
  const GlobalMRP = useSelector(GlobalprintMRP)
  const GlobalDiscount = useSelector(GlobalprintDiscount)
  const GlobalQuantity = useSelector(GlobalprintQuantity)
  const GlobalRate = useSelector(GlobalprintRate)
  const GlobalAmount = useSelector(GlobalprintAmount)
  const GlobalHsnCode = useSelector(GlobalprintHsnCode)
  const GlobalQrcodet = useSelector(GlobalprintQrcodet)
  const GlobaldummyData = useSelector(GlobalPritdummyData)

  const dispatch = useDispatch();
  const BranchId = getSession("BranchId");
  const CashierName = getSession("userName")
  const Date1 = moment(CreatedDate).format('dddd, MMMM D, YYYY | hh:mmA');
  const [BranchLogo, setBranchLogo] = useState(null)
  const [BranchAddress, setBranchAddress] = useState()
  const [BranchCity, setBranchCity] = useState()
  const [BranchZip, setBranchZip] = useState()
  const PackageDetails = table2Data?.PackageDtl;
  let totalQuantityFilter = table2Data?.productDetails?.map((item) => (item?.SalesQty))
  const totalQuantity = totalQuantityFilter?.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0,
  );
  const ExtraChargeTotal = table2Data?.ExtraChargeDetails?.reduce((accumulator, currentObject) => { return accumulator + currentObject.TotalAmt }, 0)
  const [base64Image, setBase64Image] = useState(null);
  const [conversionError, setConversionError] = useState(null);
  const OrderDetailGST = table2Data?.TaxDetails?.filter(item => item.TaxIdName === "CGST,SGST")
  const OrderDetailIGST = table2Data?.TaxDetails?.filter(item => item.TaxIdName === "IGST")
  const OrderDetailVAT = table2Data?.TaxDetails?.filter(item => item.TaxIdName === "VAT")

  useEffect(() => {
    fetchBranchData()
  }, [])

  useEffect(() => {
    async function fetchImage() {
      try {
        const base64 = await imageUrlToBase64(BranchLogo);
        setBase64Image(base64);
      } catch (error) {
        setConversionError(error.message || 'Error converting image');
      }
    }
    if (BranchLogo) {
      fetchImage();
    }
  }, [BranchLogo]);

  const fetchBranchData = async () => {
    const response = await dispatch(getBranchDetail({ BrId: BranchId })).unwrap();
    if (response?.data?.statusCode === 1) {
      setBranchAddress(response?.data?.data?.[0]?.Address1)
      setBranchCity(response?.data?.data?.[0]?.City)
      setBranchZip(response?.data?.data?.[0]?.Zip)
      setBranchLogo(response?.data?.data?.[0]?.CompLogo)
    }
    else {

      setBranchAddress()
      setBranchCity()
      setBranchZip()
      setBranchLogo()
    }
  }

  const imageUrlToBase64 = async (url) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    } catch (error) {
      console.error('Error fetching or converting image:', error);
      throw error;
    }
  };



  const products = [
    { ProdName: 'BUTTER NAAN', Rate: 88.00, SalesQty: 2, MRP: 100, TotalAmt: 176, discount: 0, HSN: 0 },
    { ProdName: 'GRILL CHICKEN (f)', Rate: 300.00, SalesQty: 1, MRP: 350, TotalAmt: 300, discount: 0, HSN: 0 },
    { ProdName: 'TANDOORI CHICKEN (H) ', Rate: 200.00, SalesQty: 1, MRP: 250, TotalAmt: 200, discount: 0, HSN: 0 },
    { ProdName: 'KULFI', Rate: 30.00, SalesQty: 1, MRP: 50, TotalAmt: 30, discount: 0, HSN: 0 },
    { ProdName: 'Laddu', Rate: 30.00, SalesQty: 1, MRP: 50, TotalAmt: 30, discount: 0, HSN: 0 },
    { ProdName: 'Chicken Biryani', Rate: 130.00, SalesQty: 1, MRP: 150, TotalAmt: 130, discount: 0, HSN: 0 },
    { ProdName: 'Mutton Biryani', Rate: 230.00, SalesQty: 1, MRP: 250, TotalAmt: 230, discount: 0, HSN: 0 },
  ];

  return (
    <div className="PrintStyle13-MasterDiv" id="PrintStyle13">

      <div className="PrintStyle13-Header" >INVOICE</div>
      <div style={{ fontSize: 'clamp(1rem, 2.5vw, 1.4rem)', fontWeight: '600' }}>POZO RESTAURANT</div>
      <div style={{ fontWeight: '600' }}>HOSUR, TAMILNADU</div>

      <div className="PrintStyle13-inNdt">
        <div>Invoice No :553</div> <div>Date  : 02/12/12  - 07:20:00  Pm</div>
      </div>

      <hr className="hrline" />

      <div style={{ display: "flex", textAlign: 'left', justifyContent: 'space-evenly', width: '100%' }}>

        <div style={{ display: 'flex', justifyContent: 'flex-start', width: '100%', padding: '0.5rem 0.4rem' }}>
          <div style={{ padding: '1rem 0rem' }}>
            <div style={{ fontWeight: '600' }}>HOTEL POZO </div>
            <div>51 STEP COLONY, DHARGA, HOSUR KRISHNAGIRI - 635126 TAMILNADU </div>
            <div>GST NO  : 8907906906 </div>
            <div>PH : 8907906906</div>
            <div>CIN NO  : 8907906906 </div>
            <div>FSSL  : 8907906906 </div>
          </div>
        </div>

        <hr />

        <div style={{ display: "flex", flexDirection: 'column', width: '100%' }}>
          <div style={{ display: 'flex', justifyContent: 'flex-start', width: '100%', padding: '0.5rem 0rem', flexDirection: 'column', }}>
            <div style={{ padding: '0.5rem 0.5rem', }} >
              <div className="PrintStyle13-SubHeader" >INVOICE TO</div>
              <div style={{ fontWeight: '600', fontSize: '16px' }}>Tamil Selvan </div>
              <div>51 STEP COLONY, DHARGA, HOSUR</div>
              <div>PH:8907906906 </div>
            </div>

            <hr className="hrline" />

            <div style={{ padding: '0.5rem 0.5rem', }}>
              <div style={{ fontWeight: '600', fontSize: '13px' }}>Bank Details :</div>
              <div style={{ display: 'flex' }}> <div> Account Name : </div> <div>Tamil Selvan</div></div>
              <div>CIN NO  : 8907906906 </div>
            </div>
          </div>
        </div>
      </div>
      <hr className="hrline" />


      <div style={{ display: "flex", justifyContent: "space-between", fontWeight: '600', width: '100%', padding: '1rem 1rem' }}>
        {GlobalSlNo && <div style={{ width: "100%", textAlign: "left", }}> SL.No </div>}
        <div style={{ width: "100%", textAlign: "left", }}> {GlobalItem && 'ITEM /DESCRIPTION /'} {GlobalQuantity && 'QTY'} </div>
        {GlobalHsnCode && <div style={{ width: "100%", textAlign: "right", }}> HSN </div>}
        {GlobalMRP && <th style={{ width: "100%", textAlign: 'right' }}>MRP</th>}
        {GlobalRate && <div style={{ width: "100%", textAlign: "right", }}> Price </div>}
        {GlobalDiscount && <th style={{ width: "100%", textAlign: 'right' }}>(%)</th>}
        {GlobalAmount && <div style={{ width: "100%", textAlign: "right", }}> Total </div>}
      </div>

      <hr className="hrline" />

      {(GlobaldummyData ? products : singleData2)?.map((item, index) => (
        <div key={index} className="PrintStyle13-print-prddtls">
          {GlobalSlNo && <div style={{ width: "100%", textAlign: "left", }}> {index + 1}</div>}
          <div style={{ width: "100%", textAlign: "left", padding: '0.6rem 0rem', fontWeight: '600', }}>
            {GlobalItem && (
              <>
                {item?.ProdName}
                {PackageDetails?.filter((pkg) => pkg.ProdId === item.ProdId).length > 0 ? (
                  PackageDetails?.filter((pkg) => pkg.ProdId === item.ProdId)?.map(
                    (pkg, index) => (
                      <div key={index}>
                        {pkg.ParcelCount} PCS {pkg.ParcelQty} PACK ({pkg.ParcelType})
                      </div>
                    )
                  )
                ) : (
                  <span>
                    ({item?.Size ? item?.Size : "1"}
                    {item?.SinglePc === "Y"
                      ? "PCS"
                      : item?.Type !== "C"
                        ? item?.UomName
                        : "COMBO"}
                    )
                  </span>
                )}
                {" - "}
                {GlobalQuantity && item?.SalesQty}
              </>
            )}
          </div>
          {GlobalHsnCode && <div style={{ width: "100%", textAlign: "right", }}>
            {item?.HSN}
          </div>}
          {GlobalMRP && <div style={{ width: "100%", textAlign: "right", }}>
            {item?.MRP}
          </div>}
          {GlobalRate && <div style={{ width: "100%", textAlign: "right", }}>
            {item?.Rate}
          </div>}
          {GlobalDiscount && <div style={{ width: "100%", textAlign: "right", }}>
            {item?.discount}
          </div>}
          {GlobalAmount && <div style={{ width: "100%", textAlign: "right", }}>
            {item?.TotalAmt}
          </div>}
        </div>
      ))}
      <hr className="hrline" />

      <div style={{ display: 'flex', width: '100%', justifyContent: 'space-evenly', }}>
        <div style={{ width: "100%", padding: '1rem 1rem' }}>
          <div>

            <div className="PrintStyle13-print-tableMaster">

              <table className="PrintStyle13-print-table">
                <thead>
                  <tr>
                    <th style={{ width: '10px', textAlign: 'right' }}>CGST%</th>
                    <th style={{ width: '10px', textAlign: 'right' }} >CGST Amt</th>
                    <th style={{ width: '10px', textAlign: 'right' }}>SGST%</th>
                    <th style={{ width: '10px', textAlign: 'right' }}>IGST%</th>
                    <th style={{ width: '10px', textAlign: 'right' }}>IGST Amt</th>
                  </tr>
                </thead>
                <tbody>

                  <tr  >
                    <td style={{ textAlign: 'right' }}>  6.00% </td>
                    <td> 7.99 </td>
                    <td style={{ textAlign: 'right' }}> 6.00%</td>
                    <td style={{ textAlign: 'right' }} >  7.99</td>
                    <td style={{ textAlign: 'right' }} >  0.00</td>
                  </tr>

                </tbody>
              </table>
            </div>

          </div>
        </div>


        <div style={{ width: "100%", padding: '1rem 1rem', fontSize: '13px', }}>
          <div style={{ display: 'flex', width: "100%", justifyContent: 'space-evenly', }}> <div style={{ width: "100%", textAlign: 'left' }}>Total Item : </div> <div style={{ width: "100%", textAlign: 'right' }}>100</div> </div>
          <div style={{ display: 'flex', width: "100%", justifyContent: 'space-evenly' }}> <div style={{ width: "100%", textAlign: 'left' }}>Qty: </div> <div style={{ width: "100%", textAlign: 'right' }}>100</div> </div>
          <div style={{ display: 'flex', width: "100%", justifyContent: 'space-evenly' }}> <div style={{ width: "100%", textAlign: 'left' }}>Extra Charges : </div> <div style={{ width: "100%", textAlign: 'right' }}>100</div> </div>
          <div style={{ display: 'flex', width: "100%", justifyContent: 'space-evenly' }}> <div style={{ width: "100%", textAlign: 'left' }}>Discount : </div> <div style={{ width: "100%", textAlign: 'right' }}>100</div> </div>
          <div style={{ display: 'flex', width: "100%", justifyContent: 'space-evenly' }}> <div style={{ width: "100%", textAlign: 'left' }}>Total : </div> <div style={{ width: "100%", textAlign: 'right' }}>100</div> </div>
          <div style={{ display: 'flex', width: "100%", justifyContent: 'space-evenly', fontWeight: '600' }}> <div style={{ width: "100%", textAlign: 'left' }}>Net Amount : </div> <div style={{ width: "100%", textAlign: 'right' }}>100.00</div> </div>
          <div style={{ display: 'flex', justifyContent: 'space-evenly', fontWeight: '600', }}> <div style={{ width: "100%", textAlign: 'left', fontSize: 'clamp(0.4rem, 2.5vw, 0.7rem)' }}>Net Total In Word : One Hundred twenty six only   </div> </div>
        </div>
      </div>


      <div style={{ displa: 'flex', justifyContent: 'flex-start', width: '100%', textAlign: 'left', padding: '1rem 1rem' }} >
        <div>
          <div>Terms & Condition</div>
          <div>Menu available everyday 11.30am onwards (Lunch and Dinner)</div>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', width: '100%', textAlign: 'left', padding: '1rem 1rem', fontWeight: '600' }}>
        <div>   Authorised Signatory </div>
      </div>

      <div>
        <div style={{ fontWeight: '600', fontSize: '14px' }}>Thank You Visit Again.!</div>
      </div>

      {/* <div onClick={Print5}> print</div> */}

    </div>
  )
}

export default PrintStyle13
