import React, { useEffect, useMemo, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { Drawer, message } from 'antd';
import { DefaultModal } from '../../../Components/Modal/DefaultModal';
import {
  changeKioskPageName,
  getCardlistDate,
  getchangesHappenedORderCardDtls,
  getKioskLightColour,
  PostBlockSlots,
} from '../../../Features/Kiosk/kiosk';
import { settingDataSelector } from '../../../Features/PreferenceMaster/PreferenceMaster.js';
import { MdCurrencyRupee } from 'react-icons/md';
import '../../../Styles/Kiosk/CardPage/SelfCardPage1.scss';
import {
  GlobalKioskOrderDetails,
  GlobalProductCardListKiosk,
  changeKioskOrderDetails,
  GlobalBookingTypeKiosk,
  getProductCardListKiosk,
  GlobalProductCategorieKiosk,
  changeAddlastPrds,
  GlobalProductSubCategorieKiosk,
  GlobalMembershipDetail,
} from '../../../Features/BookingScreen/BookingData/KioskBookingData';
import horizontal from '../../../Images/defaultItemImg.png';
import {
  changeKisokSearchedData,
  getConfigType,
  GlobalKisoksearchedData,
  GlobalOrderCardDetails,
  GlobalReorderHoldDetails,
  GlobalReorderProductDetails,
  GlobalSearchData,
} from '../../../Features/BookingScreen/BookingData/BookingData';
import { useCallback } from 'react';
import { FaCircle } from 'react-icons/fa6';
import {
  SelectedGlobalCardColorDetail,
  SelectedGlobalCardFont,
} from '../../../Features/ThemeChange/ThemeChange.js';

const CardPage1 = (props) => {
  const dispatch = useDispatch();
  const AppName = sessionStorage.getItem('AppName');
  const selfBookingOption = sessionStorage.getItem('selfBookingOption');
  const SelectedCardColor = useSelector(
    SelectedGlobalCardColorDetail,
    shallowEqual
  );
  const ReportholdData = useSelector(GlobalReorderHoldDetails, shallowEqual);
  const ReorderProductData = useSelector(
    GlobalReorderProductDetails,
    shallowEqual
  );
  const SelectedCardFont = useSelector(SelectedGlobalCardFont, shallowEqual);
  const GlobalChangeAddlastPrds = useSelector(
    (state) => state?.KioskBookingData?.changeAddlastPrds
  );
  const GlobalLastBuyProducts = useSelector(
    (state) => state?.KioskBookingData?.LastBuyProducts
  );
  const kioskCategoriesCard = useSelector(GlobalProductCardListKiosk);
  const CartOrderDetails = useSelector(GlobalOrderCardDetails, shallowEqual);
  const prodCat = useSelector(GlobalProductCategorieKiosk);
  const prodSubCat = useSelector(GlobalProductSubCategorieKiosk);
  const globalsearch = useSelector(GlobalKisoksearchedData);
  const customerData = useSelector(GlobalMembershipDetail);
  const MembershipDetail = customerData?.MembershipDetail;
  const SessionDtl = props?.SessionDtl;
  const KioskOrderDetails = useSelector(GlobalKioskOrderDetails);
  const getKioskLightColourdata = useSelector(getKioskLightColour);
  const BookingType = useSelector(GlobalBookingTypeKiosk);
  const [openQuantity, setopenQuantity] = useState(false);
  const [VariantOpen, setVariantOpen] = useState(false);
  const [onePeiceFlow, setOnePeiceFlow] = useState(false);
  const [qtydata, setQtydata] = useState();
  const [QtyIndex, setQtyIndex] = useState(0);
  const [ConfigDataList, setConfigDataList] = useState([]);
  const [playingHours, setplayingHours] = useState(0);
  const kioskTemplateData = props?.data;
  const changesHappenedOrderCardDtls = useSelector(
    getchangesHappenedORderCardDtls
  );
  const Date = useSelector(getCardlistDate);
  const SettingDataSelector = useSelector(settingDataSelector);
  const UomPrint = SettingDataSelector?.[0]?.SettingDtlDetails.filter(
    (i) => i.SettingIdName === 'PrintUom'
  )?.[0];
  const [OrderCardDetails, setOrderCardDetails] = useState([
    ...KioskOrderDetails,
  ]);
  const [OrderOfferDetails, setOrderOfferDetails] = useState([]);
  const searchBarcode = useCallback(async () => {
    if (globalsearch?.length > 0 || prodCat || prodSubCat) {
      let Response = await dispatch(
        getProductCardListKiosk({
          CompId: SessionDtl?.CompId,
          BranchId: SessionDtl?.BranchId,
          AppId: SessionDtl?.AppId,
          ProdCat: prodCat,
          ProdSubCat: prodSubCat,
          Search: globalsearch?.length > 0 ? globalsearch : null,
          Dates: Date?.format('YYYY-MM-DD'),
        })
      ).unwrap();
      if (
        Response?.data?.statusCode === 1 &&
        Response?.data?.data?.length === 1 &&
        Response?.data?.data?.[0]?.QrBasedSearch == 'Y'
      ) {
        CardOnClick(Response?.data?.data?.[0]);
        // message.success("got data")
      }
    }
  }, [globalsearch, Date]);

  function debounce(fn, delay) {
    let timeout;
    return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        fn(...args);
      }, delay);
    };
  }
  const to12Hour = (timeStr) => {
    if (!timeStr) return '';
    let [h, m] = timeStr.split(':');
    h = parseInt(h, 10);
    const suffix = h >= 12 ? 'PM' : 'AM';
    h = h % 12 || 12;
    return `${h}:${m}${suffix}`;
  };
  const debounceFn = useMemo(
    () => debounce(searchBarcode, 0),
    [globalsearch, Date]
  );
  useEffect(() => {
    debounceFn();
    // optional: cleanup to clear timeout on unmount
    // return () => debounceFn.cancel?.();
  }, [globalsearch, Date, changesHappenedOrderCardDtls]);

  useEffect(() => {
    setOrderCardDetails([...KioskOrderDetails]);

    calculateTotalplayingHours();
    // processBookings(KioskOrderDetails)
  }, [KioskOrderDetails]);

  const calculateTotalplayingHours = () => {
    let totalHours = [];
    KioskOrderDetails.forEach((item) => {
      console.log(item, 'item1111111111111');
      totalHours.push(
        calculateHours(item?.AvailableFrom, item?.AvailableTo) * item?.Size || 0
      );
    });
    setplayingHours(totalHours);
  };
  function addLastBuyProducts() {
    let { productDetails } = GlobalLastBuyProducts[0];
    let dataa = { ...GlobalLastBuyProducts[0] };
    dataa.ProductDetail = dataa?.productDetails;
    delete dataa?.productDetails;

    // Use a local array to accumulate changes
    let newOrderDetails = [...OrderCardDetails];
    console.log(newOrderDetails, 'newOrderDetails');
    for (let i = 0; i < productDetails?.length; i++) {
      // Build product data as in dataTransfer
      const TakAwayId = ConfigDataList?.find(
        (a) => a?.ConfigName === 'TakeAway'
      )?.ConfigId;
      const DineinId = ConfigDataList?.find(
        (a) => a?.ConfigName === 'Dine In'
      )?.ConfigId;
      let item = {
        Type: 'P',
        OverallQuantity: dataa?.OverAllQty,
        ActiveStatus: dataa?.ProductDetail?.[i]?.ActiveStatus,
        AvailableFrom: dataa?.ProductDetail?.[i]?.AvailableFrom,
        AvailableTo: dataa?.ProductDetail?.[i]?.AvailableTo,
        Cess: dataa?.ProductDetail?.[i]?.Cess,
        HSNCode: dataa?.ProductDetail?.[i]?.HSNCode,
        BrandName: dataa?.ProductDetail?.[i]?.BrandName,
        OpeningQty: dataa?.ProductDetail?.[i]?.OpeningQty,
        PartNumber: dataa?.ProductDetail?.[i]?.PartNumber,
        ProdId: dataa?.ProductDetail?.[i]?.ProdId,
        ProdLogo: dataa?.ProductDetail?.[i]?.ProdLogo,
        ProdName: dataa?.ProductDetail?.[i]?.ProdName,
        QRCode: dataa?.ProductDetail?.[i]?.QRCode,
        QtyBasedPrice: dataa?.ProductDetail?.[i]?.QtyBasedPrice,
        Rack: dataa?.ProductDetail?.[i]?.Rack,
        Size: dataa?.ProductDetail?.[i]?.Size,
        StockAvailable: dataa?.ProductDetail?.[i]?.StockAvailable,
        TaxId: dataa?.ProductDetail?.[i]?.TaxId,
        TaxPercentage: dataa?.ProductDetail?.[i]?.TaxPercentage,
        TaxName: dataa?.ProductDetail?.[i]?.TaxIdName,
        UniqueId: dataa?.ProductDetail?.[i]?.UniqueId,
        UomName: dataa?.ProductDetail?.[i]?.UomName,
        SinglePc: 'N',
        NoOfPcs: null,
        ProdVariantName:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.ProdVariantName,
        BalanceQty:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.BalanceQty,
        BatchRef:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.BatchRef,
        InwardDate:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.InwardDate,
        InwardDtlId:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.InwardDtlId,
        ExpDate:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.ExpDate,
        InwardId:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.InwardId,
        MRP: dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]
          ?.StockDetails?.[0]?.MRP,
        OrderRate:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.SellPrice,
        SuppId:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.SuppId,
        SuppName:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.SuppName,
        Offer:
          dataa?.ProductDetail?.[i]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
            ?.OfferPrice,
        OrderType: 'S',
        OrderStatus: 'O',
        BookingTypeName: BookingType,
        BookingType: BookingType === 'Dine In' ? DineinId : TakAwayId,
        ProdNameQty:
          UomPrint?.SettingValue === 'N'
            ? `${dataa?.ProductDetail?.[i]?.ProdName} ${dataa?.ProductDetail?.[i]?.UomName?.toLowerCase() === 'half' ? '(Half)' : ''}`
            : `${dataa?.ProductDetail?.[i]?.ProdName} ${dataa?.ProductDetail?.[i]?.Size} ${dataa?.ProductDetail?.[i]?.UomName}`,
      };
      // Add/update in newOrderDetails
      const isItemInCart = newOrderDetails.find(
        (cartItem) =>
          cartItem.ProdId === item.ProdId &&
          cartItem.InwardDtlId === item.InwardDtlId &&
          cartItem.OrderRate === item.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName &&
          !cartItem?.disabled
      );
      if (isItemInCart) {
        newOrderDetails = newOrderDetails.map((cartItem) =>
          cartItem.ProdId === item.ProdId &&
          cartItem.InwardDtlId === item.InwardDtlId &&
          cartItem.OrderRate === item.OrderRate &&
          cartItem?.BookingTypeName === item?.BookingTypeName &&
          !cartItem?.disabled
            ? {
                ...cartItem,
                OrderQty: cartItem.OrderQty + 1,
                TotalAmt: (cartItem.OrderQty + 1) * cartItem.OrderRate,
                TaxAmt: (
                  ((cartItem.OrderQty + 1) *
                    cartItem.OrderRate *
                    cartItem.TaxPercentage) /
                  (100 + cartItem.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (cartItem.OrderQty + 1) * cartItem.OrderRate -
                  (
                    ((cartItem.OrderQty + 1) *
                      cartItem.OrderRate *
                      cartItem.TaxPercentage) /
                    (100 + cartItem.TaxPercentage)
                  ).toFixed(2),
              }
            : cartItem
        );
      } else {
        newOrderDetails.push({
          ...item,
          OrderQty: 1,
          TotalAmt: item.OrderRate,
          TaxAmt: (
            (item.OrderRate * item.TaxPercentage) /
            (100 + item.TaxPercentage)
          ).toFixed(2),
          WithoutTaxRate: (
            item.OrderRate -
            (item.OrderRate * item.TaxPercentage) / (100 + item.TaxPercentage)
          ).toFixed(2),
        });
      }
    }
    setOrderCardDetails(newOrderDetails);
    dispatch(changeKioskOrderDetails(newOrderDetails));
    message.success(' Favourite Products Added in the Cart');
    dispatch(changeKisokSearchedData(null));
    dispatch(changeAddlastPrds(false));
  }

  useEffect(() => {
    getBookingTypeId();
  }, []);

  useEffect(() => {
    if (GlobalChangeAddlastPrds) {
      addLastBuyProducts();
    }
  }, [GlobalChangeAddlastPrds]);

  const onClose = () => {
    setopenQuantity(false);
  };
  const handleClose = () => {
    setVariantOpen(false);
  };
  //Card on click function

  const CardOnClick = async (item, Parameter) => {
    dispatch(changeKisokSearchedData(null));
    setOnePeiceFlow(Parameter === 'OnePeiceProduct');

    const transformedItem = {
      ...item,
      ProductDetail: item.ProductDetail.filter(
        (detail) => detail.OnePcsAvailable === 'Y'
      ).map(({ ProdId, ProdName, ProdVariantDetails, ...rest }) => ({
        ProdId,
        ProdName,
        ProdVariantDetails,
        ...rest,
      })),
    };
    const modiffiedData =
      Parameter === 'OnePeiceProduct' ? transformedItem : item;
    setQtydata(modiffiedData);
    let count = modiffiedData?.ProductDetail?.length;
    if (count > 1) {
      setopenQuantity(true);
    } else {
      setQtyIndex(0);
      SingleQuantity(modiffiedData, Parameter === 'OnePeiceProduct');
    }
  };
  const SingleQuantity = (item, onePcs) => {
    let count = item?.ProductDetail?.[0]?.ProdVariantDetails?.length;
    if (count > 1 && AppName?.toLowerCase() !== 'sports') {
      setVariantOpen(true);
    } else if (AppName?.toLowerCase() == 'sports' && count > 0) {
      setVariantOpen(true);
    } else {
      let Isincart = KioskOrderDetails?.find(
        (cartItem) =>
          cartItem?.ProdId === item?.ProductDetail?.[0]?.ProdId &&
          cartItem?.InwardDtlId ===
            item?.ProductDetail?.[0]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
              ?.InwardDtlId &&
          cartItem?.OrderRate ===
            item?.ProductDetail?.[0]?.ProdVariantDetails?.[0]?.StockDetails?.[0]
              ?.SellPrice
      );
      if (Isincart && Isincart?.StockAvailable === 'Y') {
        if (Isincart?.BalanceQty > Isincart?.OrderQty) {
          dataTransfer(item, 0, 0, 0, onePcs);
        } else {
          dataTransfer(item, 0, 0, 1, onePcs);
        }
      } else {
        dataTransfer(item, 0, 0, 0, onePcs);
      }
    }
  };
  const VarientFun = (index) => {
    const selectedProIndex = qtydata?.ProductDetail?.findIndex(
      (item) =>
        item?.ProdId === index?.ProdId &&
        item?.Size === index?.Size &&
        item?.UomName === index?.UomName &&
        item?.Brand === index?.Brand
    );

    if (selectedProIndex !== -1) {
      const count =
        qtydata?.ProductDetail[selectedProIndex]?.ProdVariantDetails?.length ||
        0;

      if (count > 1) {
        setopenQuantity(false);
        setVariantOpen(true);
      } else {
        const item = { QtyIndex: selectedProIndex, VarientIndex: 0 };
        singleVarient(item);
        setopenQuantity(false);
      }
    }

    setQtyIndex(selectedProIndex);
    //   setRepeatedModel(false);
  };

  // mohan
  const getBookingTypeId = async () => {
    let tempconfigdata = await dispatch(
      getConfigType({ TypeName: 'Booking Type' })
    ).unwrap();
    setConfigDataList(tempconfigdata?.data?.data);
  };
  //mohan

  const singleVarient = (item) => {
    let Isincart = KioskOrderDetails?.find(
      (cartItem) =>
        cartItem?.ProdId === qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdId &&
        cartItem?.InwardDtlId ===
          qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
            item?.VarientIndex
          ]?.StockDetails?.[0]?.InwardDtlId &&
        cartItem?.OrderRate ===
          qtydata?.ProductDetail?.[item?.QtyIndex]?.ProdVariantDetails?.[
            item?.VarientIndex
          ]?.StockDetails?.[0]?.SellPrice
    );
    console.log(Isincart, item, KioskOrderDetails, 'IsincartsingleVarient');
    if (Isincart && Isincart?.StockAvailable === 'Y') {
      if (Isincart?.BalanceQty > Isincart?.OrderQty) {
        dataTransfer(
          qtydata,
          item?.QtyIndex,
          item?.VarientIndex,
          0,
          onePeiceFlow
        );
      } else {
        dataTransfer(
          qtydata,
          item?.QtyIndex,
          item?.VarientIndex,
          1,
          onePeiceFlow
        );
      }
    } else {
      dataTransfer(
        qtydata,
        item?.QtyIndex,
        item?.VarientIndex,
        0,
        onePeiceFlow
      );
    }
    // dataTransfer(qtydata, item?.QtyIndex, item?.VarientIndex, 0, onePeiceFlow);
    setopenQuantity(false);
  };
  const Stockfun = (item, index) => {
    let Isincart = KioskOrderDetails?.find(
      (cartItem) =>
        cartItem?.ProdId === item?.ProdId &&
        cartItem?.InwardDtlId === item?.StockDetails?.[0]?.InwardDtlId &&
        cartItem?.OrderRate === item?.StockDetails?.[0]?.SellPrice
    );
    if (Isincart && Isincart?.StockAvailable === 'Y') {
      if (Isincart?.BalanceQty > Isincart?.OrderQty) {
        dataTransfer(qtydata, QtyIndex, index, 0, onePeiceFlow);
      } else {
        dataTransfer(qtydata, QtyIndex, index, 1, onePeiceFlow);
      }
    } else {
      dataTransfer(qtydata, QtyIndex, index, 0, onePeiceFlow);
    }
    // dataTransfer(qtydata, QtyIndex, index, 0, onePeiceFlow);
    setVariantOpen(false);
    // setVarientIndex(index);
  };
  //calculate Slot hours

  function calculateHours(from, to) {
    if (!from || !to) return 0;
    const [fromH, fromM] = from?.split(':')?.map(Number);
    const [toH, toM] = to?.split(':')?.map(Number);

    let diff = toH * 60 + toM - (fromH * 60 + fromM);

    // handle case when 'to' time is on the next day
    if (diff < 0) {
      diff += 24 * 60;
    }

    return diff / 60; // returns hours (can be decimal)
  }
  //  card data conversion
  const dataTransfer = async (
    a,
    QtyIndex,
    VarientIndex,
    stockIndex,
    onePcs,
    isFav = false
  ) => {
    console.log(QtyIndex, 'QtyIndexQtyIndex');
    const TakAwayId = ConfigDataList?.find(
      (a) => a?.ConfigName === 'TakeAway'
    )?.ConfigId;
    const DineinId = ConfigDataList?.find(
      (a) => a?.ConfigName === 'Dine In'
    )?.ConfigId;
    let data = {
      Type: 'P',
      OverallQuantity: a?.OverAllQty,
      ActiveStatus: a?.ProductDetail?.[QtyIndex]?.ActiveStatus,
      // TotalHrs: calculateHours((a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.AvailableFrom || 0), (a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]?.AvailableTo || 0)) * (a?.ProductDetail?.[QtyIndex]?.Size || 1),
      AvailableFrom:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.AvailableFrom,
      AvailableTo:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.AvailableTo,
      Cess: a?.ProductDetail?.[QtyIndex]?.Cess,
      HSNCode: a?.ProductDetail?.[QtyIndex]?.HSNCode,
      BrandName: a?.ProductDetail?.[QtyIndex]?.BrandName,
      // 'ManufDate': a?.ProductDetail?.[QtyIndex]?.ManufDate,
      OpeningQty: a?.ProductDetail?.[QtyIndex]?.OpeningQty,
      PartNumber: a?.ProductDetail?.[QtyIndex]?.PartNumber,
      ProdId: a?.ProductDetail?.[QtyIndex]?.ProdId,
      ProdLogo: a?.ProductDetail?.[QtyIndex]?.ProdLogo,
      ProdName: a?.ProductDetail?.[QtyIndex]?.ProdName,
      QRCode: a?.ProductDetail?.[QtyIndex]?.QRCode,
      QtyBasedPrice: a?.ProductDetail?.[QtyIndex]?.QtyBasedPrice,
      Rack: a?.ProductDetail?.[QtyIndex]?.Rack,
      Size: a?.ProductDetail?.[QtyIndex]?.Size,
      StockAvailable: a?.ProductDetail?.[QtyIndex]?.StockAvailable,
      TaxId: a?.ProductDetail?.[QtyIndex]?.TaxId,
      TaxPercentage: a?.ProductDetail?.[QtyIndex]?.TaxPercentage,
      TaxName: a?.ProductDetail?.[QtyIndex]?.TaxIdName,
      UniqueId: a?.ProductDetail?.[QtyIndex]?.UniqueId,
      UomName: a?.ProductDetail?.[QtyIndex]?.UomName,
      SinglePc: onePcs ? 'Y' : 'N',
      NoOfPcs: onePcs
        ? a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.NoOfPcs
        : null,
      ProdVariantName:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.ProdVariantName,
      BalanceQty:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.BalanceQty,
      BatchRef:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.BatchRef,
      InwardDate:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.InwardDate,
      InwardDtlId:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.InwardDtlId,
      ExpDate:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.ExpDate,
      InwardId:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.InwardId,
      MRP: onePcs
        ? a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.OnePcsPrice
        : a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.MRP,
      OrderRate: onePcs
        ? a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.OnePcsPrice
        : a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
            ?.StockDetails?.[stockIndex]?.SellPrice,
      SuppId:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.SuppId,
      SuppName:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.SuppName,
      Offer:
        a?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.[VarientIndex]
          ?.StockDetails?.[stockIndex]?.OfferPrice,
      OrderType: 'S',
      OrderStatus: 'O',
      BookingTypeName: BookingType,
      BookingType: BookingType === 'Dine In' ? DineinId : TakAwayId,
      ProdNameQty:
        UomPrint?.SettingValue === 'N'
          ? `${a?.ProductDetail?.[QtyIndex]?.ProdName} ${a?.ProductDetail?.[QtyIndex]?.UomName?.toLowerCase() === 'half' ? '(Half)' : ''}`
          : `${a?.ProductDetail?.[QtyIndex]?.ProdName} ${a?.ProductDetail?.[QtyIndex]?.Size} ${a?.ProductDetail?.[QtyIndex]?.UomName}`,
    };
    setopenQuantity(false);
    setVariantOpen(false);
    setQtyIndex(0);
    //   setVarientIndex(0)
    AddOrderDetails(data);
    setOnePeiceFlow(false);
  };
  //   add Product in cart state
  const AddOrderDetails = async (item) => {
    // debugger
    message.success(`${item?.ProdName} Added in the Cart`);
    const isItemInCart = KioskOrderDetails?.find(
      (cartItem) =>
        cartItem.ProdId === item.ProdId &&
        cartItem.InwardDtlId === item.InwardDtlId &&
        cartItem.OrderRate === item.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName &&
        !cartItem?.disabled
    );

    if (isItemInCart) {
      dispatch(
        changeKioskOrderDetails(
          KioskOrderDetails?.map((cartItem) =>
            cartItem.ProdId === item.ProdId &&
            cartItem.InwardDtlId === item.InwardDtlId &&
            cartItem.OrderRate === item.OrderRate &&
            cartItem?.BookingTypeName === item?.BookingTypeName &&
            !cartItem?.disabled
              ? {
                  ...cartItem,
                  OrderQty: cartItem.OrderQty + 1,
                  TotalAmt: (cartItem.OrderQty + 1) * cartItem.OrderRate,
                  TaxAmt: (
                    ((cartItem.OrderQty + 1) *
                      cartItem.OrderRate *
                      cartItem.TaxPercentage) /
                    (100 + cartItem.TaxPercentage)
                  ).toFixed(2),
                  WithoutTaxRate:
                    (cartItem.OrderQty + 1) * cartItem.OrderRate -
                    (
                      ((cartItem.OrderQty + 1) *
                        cartItem.OrderRate *
                        cartItem.TaxPercentage) /
                      (100 + cartItem.TaxPercentage)
                    ).toFixed(2),
                }
              : cartItem
          )
        )
      );
    } else {
      dispatch(
        changeKioskOrderDetails([
          ...KioskOrderDetails,
          {
            ...item,
            OrderQty: 1,
            TotalAmt: item.OrderRate,
            TaxAmt: (
              (item.OrderRate * item.TaxPercentage) /
              (100 + item.TaxPercentage)
            ).toFixed(2),
            WithoutTaxRate: (
              item.OrderRate -
              (item.OrderRate * item.TaxPercentage) / (100 + item.TaxPercentage)
            ).toFixed(2),
          },
        ])
      );
    }
  };
  //Brand based display
  let brandMapping = {};
  // Group product details by Brand ID
  let filterqtydata = qtydata?.ProductDetail?.filter(
    (item) => item?.ProdVariantDetails?.length > 0
  );

  filterqtydata?.forEach((item) => {
    const brandId = item?.BrandName;
    if (!brandMapping[brandId]) {
      brandMapping[brandId] = [];
    }
    brandMapping[brandId].push(item);
  });
  const BrandCheckresult = qtydata?.ProductDetail.every((product) => {
    return product.BrandName === null || product.BrandName === undefined;
  });

  const ItemSellingPrice = (item) => {
    const variantWithDetails = item?.ProductDetail?.find(
      (variant) => variant?.ProdVariantDetails?.length > 0
    );
    if (variantWithDetails) {
      // Access the details of the first variant with ProdVariantDetails
      const firstVariantDetails =
        variantWithDetails?.ProdVariantDetails?.[0]?.StockDetails?.[0]
          ?.SellPrice;
      return firstVariantDetails;
    } else {
      // Handle the case where no variant satisfies the condition
      return null; // or any other value you want to return
    }
  };

  const ItemSize = (item) => {
    const variantWithDetails = item?.ProductDetail?.find(
      (variant) => variant?.ProdVariantDetails?.length > 0
    );

    if (variantWithDetails) {
      // Access the details of the first variant with ProdVariantDetails
      const firstVariantDetails = variantWithDetails?.Size;
      return firstVariantDetails;
    } else {
      // Handle the case where no variant satisfies the condition
      return null; // or any other value you want to return
    }
  };
  const ItemUomName = (item) => {
    const variantWithDetails = item?.ProductDetail?.find(
      (variant) => variant?.ProdVariantDetails?.length > 0
    );

    if (variantWithDetails) {
      // Access the details of the first variant with ProdVariantDetails
      const firstVariantDetails = variantWithDetails?.UomName;
      return firstVariantDetails;
    } else {
      // Handle the case where no variant satisfies the condition
      return null; // or any other value you want to return
    }
  };
  const stockavailablecard = (data) => {
    let fildata = data?.filter(
      (item) =>
        item?.ProductDetail?.[0]?.StockAvailable !== 'Y' ||
        (item?.ProductDetail?.[0]?.StockAvailable === 'Y' &&
          item?.OverAllQty > 0)
    );
    return fildata;
  };
  const returnCount = (ProdName, currentQty, KioskOrderDetails) => {
    let getCurrentProdDtl = KioskOrderDetails?.filter(
      (a) => a?.ProdName === ProdName
    );
    let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.OrderQty || 0);
    }, 0);
    console.log(getCurrentProdDtl, 'getCurrentProdDtl');
    let count =
      parseInt(currentQty) - parseInt(getCurrentProdDtl ? totalOrderQty : 0);

    return count;
  };
  const returnQtyCount = (ProdId, item, orderDetails) => {
    let ItemQuantity = item?.ProdVariantDetails?.reduce((accumulator, card) => {
      return accumulator + parseInt(card.OverAllQty || 0);
    }, 0);

    let getCurrentProdDtl = orderDetails?.filter((a) => a?.ProdId === ProdId);
    let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
      return accumulator + parseInt(card.OrderQty || 0);
    }, 0);
    // let OverallProdQty = totalOrderQty - totalSelectedProductQty
    if (
      parseInt(ItemQuantity) > parseInt(getCurrentProdDtl ? totalOrderQty : 0)
    ) {
      let count =
        parseInt(ItemQuantity) -
        parseInt(getCurrentProdDtl ? totalOrderQty : 0);

      return parseInt(count);
    } else {
      let count = 0;
      return count;
    }
  };
  const returnOnepcCount = (ProdName, currentQty, orderDetails, overallpcs) => {
    let SelectedProduct = ReorderProductData?.filter(
      (a) => a?.ProdName === ProdName
    );
    let totalSelectedProductQty = SelectedProduct?.reduce(
      (accumulator, card) => {
        return (
          accumulator +
          parseInt(
            card?.StockAvailable === 'Y'
              ? card.SinglePc !== 'Y'
                ? card.OrderQty * card.NoOfPcs
                : card.OrderQty
              : 0
          )
        );
      },
      0
    );
    let getCurrentProdDtl = orderDetails?.filter(
      (a) => a?.ProdName === ProdName
    );

    let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
      return (
        accumulator +
        parseInt(
          card?.StockAvailable === 'Y'
            ? card.SinglePc !== 'Y'
              ? card.OrderQty * card.NoOfPcs
              : card.OrderQty
            : 0
        )
      );
    }, 0);
    let OverallProdQty = totalOrderQty - totalSelectedProductQty;
    if (
      parseInt(currentQty) >
      parseInt(
        Object.keys(ReportholdData)?.length > 0 && totalOrderQty
          ? OverallProdQty
          : getCurrentProdDtl
            ? totalOrderQty
            : 0
      )
    ) {
      let count =
        parseInt(currentQty) -
        parseInt(
          Object.keys(ReportholdData)?.length > 0 && totalOrderQty
            ? OverallProdQty
            : getCurrentProdDtl
              ? totalOrderQty
              : 0
        );
      return parseInt(count);
    } else {
      let count = 0;
      return count;
    }
  };
  const returnVariantStock = (
    ProdId,
    currentQty,
    orderDetails,
    ProdVariantName
  ) => {
    let getCurrentProdDtl = orderDetails?.filter(
      (a) => a?.ProdId === ProdId && a?.ProdVariantName === ProdVariantName
    );
    let totalOrderQty = getCurrentProdDtl?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.OrderQty || 0);
    }, 0);

    if (
      parseInt(currentQty) > parseInt(getCurrentProdDtl ? totalOrderQty : 0)
    ) {
      let count =
        parseInt(currentQty) - parseInt(getCurrentProdDtl ? totalOrderQty : 0);
      return parseInt(count);
    } else {
      let count = 0;
      return count;
    }
  };
  return (
    <div
      className="KioskCardmaster"
      style={{ height: '100vh',   }}
    >
      {/* Top area */}
      <div style={{ backgroundColor: '#EEEEEE', overflow: 'auto' }}>
        {/* Card area */}
        <div
          className={
            kioskTemplateData?.KioskCategory?.[0] === 'Category2'
              ? 'KioskCard-card-main-cat2'
              : props?.class
                ? props.class
                : 'KioskCard-card-main'
          }
          // style={{ backgroundColor: getKioskLightColourdata }}
        >
          {/* Mapping through kioskCategoriesCard */}
          {(selfBookingOption === 'Card Only' ||
            selfBookingOption === 'Both') &&
            stockavailablecard(kioskCategoriesCard)?.map(
              (card, index) =>
                card?.OverAllExpStatus === 'N' && (
                  <div
                    className={
                      (card?.OverAllQty !== undefined &&
                        returnCount(
                          card?.ProductDetail?.[0]?.ProdName,
                          card?.OverAllQty,
                          KioskOrderDetails
                        ) > 0) ||
                      card?.ProductDetail?.some(
                        (item) => item?.StockAvailable !== 'Y'
                      )
                        ? 'KioskCard-card'
                        : 'KioskCard-card-dis'
                    }
                    key={index}
                    onClick={() => {
                      if (ItemSellingPrice(card) !== null) {
                        CardOnClick(card);
                      }
                    }}
                  >
                    <div className="KioskCard-card-dishimage">
                      <img
                        src={
                          card?.ProductDetail?.[0]?.ProdLogo
                            ? card?.ProductDetail?.[0]?.ProdLogo
                            : horizontal
                        }
                        alt="card image"
                      />
                    </div>
                    <div className="KioskCard-card-dishname">
                      <p>{card?.ProdName}</p>
                    </div>
                    {(card?.OverAllQty !== undefined &&
                      returnCount(
                        card?.ProductDetail?.[0]?.ProdName,
                        card?.OverAllQty,
                        KioskOrderDetails
                      ) > 0) ||
                    card?.ProductDetail?.some(
                      (item) => item?.StockAvailable !== 'Y'
                    ) ? (
                      ''
                    ) : (
                      <div
                        style={{
                          color: 'red',
                          marginTop: '5px',
                          fontSize: '15px',
                        }}
                      >
                        Out Of Stock
                      </div>
                    )}
                    <div className="dishPrize">
                      {ItemSellingPrice(card) !== null && (
                        <p>
                          <MdCurrencyRupee
                            style={{
                              marginBottom: '-2px',
                              marginRight: '-5px',
                            }}
                          />{' '}
                          {ItemSellingPrice(card)}&nbsp;
                          <span className="BSItemCard-itemCount">
                            ({ItemSize(card)} {ItemUomName(card)})
                          </span>
                        </p>
                      )}
                    </div>
                    {card?.ProductDetail?.filter(
                      (item) => item.OnePcsAvailable == 'Y'
                    ).length !== 0 && (
                      <div
                        className="card4Main-onepiece-selfBooking"
                        onClick={(e) => {
                          e.stopPropagation(); // Stop event propagation to the parent div

                          if (
                            !(
                              (card?.OverAllQty !== undefined &&
                                returnOnepcCount(
                                  card?.ProductDetail?.[0]?.ProdName,
                                  card?.OverAllPcs,
                                  CartOrderDetails
                                ) > 0) ||
                              card?.ProductDetail?.some(
                                (item) => item?.StockAvailable !== 'Y'
                              )
                            )
                          ) {
                            return; // Don't proceed if the condition isn't met
                          } else {
                            CardOnClick(card, 'OnePeiceProduct'); // This only runs when you click the "One Piece" button
                          }
                        }}
                        style={{
                          fontFamily: SelectedCardFont || '',
                          backgroundColor:
                            SelectedCardColor?.FontColor || '#f00000ff',
                          color:
                            returnOnepcCount(
                              card?.ProductDetail?.[0]?.ProdName,
                              card?.OverAllPcs,
                              CartOrderDetails
                            ) > 0 ||
                            card?.ProductDetail?.some(
                              (product) => product?.StockAvailable !== 'Y'
                            )
                              ? true
                                ? SelectedCardColor?.BackgroundColor ||
                                  '#000000'
                                : '#fff'
                              : '#ff4d4f',
                        }}
                      >
                        <div>
                          {' '}
                          {AppName?.toLowerCase() === 'sports'
                            ? 'Single'
                            : '1PCS'}{' '}
                        </div>
                      </div>
                    )}
                  </div>
                )
            )}
        </div>
      </div>
      <div className="KioskCard-card-drawer">
        <Drawer
          title={<p className="cardpage-title">Select Quantity</p>}
          height={'max-content'}
          placement={'top'}
          closable={false}
          onClose={onClose}
          open={openQuantity}
          key={'top'}
        >
          <div className="CardPage3-varient-div">
            <div>
              <img
                className="CardPage3-varient-image"
                src={
                  qtydata?.ProductDetail?.[0]?.ProdLogo
                    ? qtydata?.ProductDetail?.[0]?.ProdLogo
                    : horizontal
                }
                alt=""
              />
              <p style={{ fontSize: '20px', fontWeight: '600' }}>
                {qtydata?.ProductDetail?.[0]?.ProdName
                  ? qtydata?.ProductDetail?.[0]?.ProdName
                  : ''}
              </p>
            </div>
            <div className="CardPage3-varient-text">
              <h2>Quantity List</h2>
              {Object.entries(brandMapping)?.map(([brandName, brandItems]) => {
                const isValidBrandName =
                  brandName !== 'null' && brandName !== 'undefined';
                return (
                  <div key={brandName} className="Brand-Card">
                    {isValidBrandName && (
                      <div className="Brandname">
                        <h4>{brandName}</h4>
                      </div>
                    )}
                    <div className="BrandDetail">
                      {brandItems.map((item, index) => {
                        const expired = item.OverAllExpStatus === 'N';
                        const qtyCount = returnQtyCount(
                          item?.ProdId,
                          item,
                          KioskOrderDetails
                        );
                        const isAvailable = item?.StockAvailable !== 'Y';
                        const isDisabled = qtyCount > 0 || isAvailable;
                        return (
                          expired && (
                            <div key={`${brandName}-${index}`}>
                              <div
                                className={
                                  isDisabled
                                    ? 'CardPage3-singlevarient-conatiner'
                                    : 'CardPage3-singlevarient-conatiner-dis'
                                }
                                onClick={() => VarientFun(item)}
                              >
                                <div
                                  style={{
                                    display: 'flex',
                                    cursor: 'pointer',
                                    flexDirection: 'column',
                                    border: '1px solid #eaeaea',
                                    padding: '0.5rem',
                                    height: '9rem',
                                    alignItems: 'center',
                                    textAlign: 'center',
                                    justifyContent: 'center',
                                  }}
                                >
                                  <img
                                    src={item?.ProdLogo || horizontal}
                                    className="CardPage3-singlevarient-img"
                                    alt={`Product ${index}`}
                                  />
                                  {isDisabled ? (
                                    <p>
                                      ₹{' '}
                                      {
                                        item?.ProdVariantDetails?.[0]
                                          ?.StockDetails?.[0]?.SellPrice
                                      }{' '}
                                      ({item?.Size} {item?.UomName})
                                    </p>
                                  ) : (
                                    <p>{'Out Of Stock'}</p>
                                  )}
                                </div>
                              </div>
                            </div>
                          )
                        );
                      })}
                    </div>
                  </div>
                );
              })}
              {Object.keys(brandMapping).length === 0 && (
                <p>No product details available</p>
              )}
            </div>
          </div>
        </Drawer>
      </div>
      <DefaultModal
        maskClosable={true}
        title={<p className="cardpage-title">Variants</p>}
        width={600}
        open={VariantOpen}
        top={20}
        footer={false}
        buttonText="Submit"
        handleCancel={handleClose}
        children={
          <>
            <div style={{ fontSize: '16px', fontWeight: '600' }}>
              {qtydata?.ProdName} ( {qtydata?.ProductDetail?.[QtyIndex]?.Size}{' '}
              {onePeiceFlow
                ? AppName?.toLowerCase() === 'sports'
                  ? 'Member'
                  : 'PCS'
                : qtydata?.ProductDetail?.[QtyIndex]?.UomName}
              )
            </div>
            <div
              style={{ display: 'flex', flexDirection: 'column', gap: '0' }}
            >
              {qtydata?.ProductDetail?.[QtyIndex]?.ProdVariantDetails?.map(
                (item, index) => {
                  const inStock =
                    returnVariantStock(
                      qtydata?.ProductDetail?.[QtyIndex]?.ProdId,
                      item?.OverAllQty,
                      KioskOrderDetails,
                      item?.ProdVariantName
                    ) > 0 ||
                    qtydata?.ProductDetail?.[QtyIndex]?.StockAvailable !== 'Y';
                  const isAvailble =
                    item?.StockDetails?.[0]?.SlotStatus == 'Available';
                  const cardClass =
                    AppName?.toLowerCase() === 'sports'
                      ? isAvailble
                        ? 'ProVariantCard ProVariantCardSports'
                        : 'ProVariantCardSports-dis'
                      : inStock
                        ? 'ProVariantCard'
                        : 'ProVariantCard-dis';

                  return (
                    <div
                      key={index}
                      className={cardClass}
                      onClick={() => Stockfun(item, index)}
                    >
                      <div>
                        {item?.ProdVariantName}
                        {AppName?.toLowerCase() === 'sports' && (
                          <div>
                            <span>{to12Hour(item?.AvailableFrom)}</span> -{' '}
                            <span>{to12Hour(item?.AvailableTo)}</span>
                          </div>
                        )}
                      </div>
                      {inStock ? (
                        <div className="sportsPriceCrad">
                          ₹{' '}
                          {onePeiceFlow
                            ? item?.StockDetails?.[0]?.OnePcsPrice
                            : item?.StockDetails?.[0]?.SellPrice}
                        </div>
                      ) : (
                        'Out Of Stock'
                      )}
                    </div>
                  );
                }
              )}
            </div>
          </>
        }
      />
    </div>
  );
};

export default CardPage1;
