import {
  useEffect,
  useState,
  useMemo,
  useCallback,
  lazy,
  Suspense,
  useRef,
} from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { FaChartLine, FaRupeeSign } from 'react-icons/fa';
import { Badge, Popconfirm, Tooltip } from 'antd';
import { isMobile } from 'react-device-detect';
import { ApplicationPreferences } from '../../../Features/BrachLogin/BranchLogin';
import {
  getCardDataWithoutSub,
  getCardDataWithoutSubmodule,
  getLayoutproductCard,
  getPreferenceData,
  getSelectedFavItems,
  GlobalOrderStatus,
  GlobalOtherSevices,
  GlobalProductCategorie,
  GlobalProductSubCategorie,
  GlobalSalesDetailData,
  PreferenceData,
} from '../../../Features/BookingScreen/BookingData/BookingData';
import {
  dateFormatChange1,
  extractLastNumberOrderId,
  getSession,
} from '../../../Services/Others';
import { useDateStore } from '../../../Features/BookingScreen/BookingData/DateStore';
import dayjs from 'dayjs';
import moment from 'moment';
import PozoKioskIcon from '../Components/UtillComponents/Pozo retail icons/PozoKioskIcon';
import { globalKioskSalesCount } from '../../../Features/Kiosk/kiosk';
import BSKioskCounterPayment from '../Components/UtillComponents/BSKioskCounterPayment';
import TooltipWrapper from '../../../Components/Tooltip/Tooltip';
import {
  getTemplateData,
  StoredSessionData,
} from '../../../Features/ThemeChange/ThemeChange';
import BookingCloseIcon from '../Components/UtillComponents/BookingCloseIcon';
import RetailBookingClosing from './RetailBookingClose';
import {
  getBookingStatus,
  GlobalBookingStatus,
} from '../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail';
import { PutBookingClose } from '../../../Features/BookingScreen/RetailBookingClose';
import BSEwayBillicon from '../../BookingScreen/Components/UtillComponents/BSEwayBillicon.jsx';
import { DefaultModal } from '../../../Components/Modal/DefaultModal.jsx';
import { MdOutlineCallReceived } from 'react-icons/md';
import {
  getReceivedStocks,
  PostReceiveStocks,
} from '../../../Features/stockReceivedGodown/ReceivedStock.js';
import { GoPackageDependencies } from 'react-icons/go';
import { Messages } from '../../../../ownLib/my-ui-lib.js';
// Jsx File
const BSExpireProductsList = lazy(
  () => import('../Components/UtillComponents/BSExpireProductsList')
);

const ListOfSalesInvoices = lazy(
  () =>
    import('../Components/BSBillingTables/ListofInvoices/ListOfSalesInvoices.jsx')
);

const CustomisedInvoiceChange = lazy(
  () => import('../Components/UtillComponents/CustomisedInvoiceChange.jsx')
);

const ProductPriceChange = lazy(
  () => import('../Components/UtillComponents/ProductPriceChange.jsx')
);

const ReceivedStocksModal = lazy(
  () => import('../../../Components/Modal/ReceivedStocksModal.jsx')
);

const ProductDetailsModal = lazy(
  () => import('../../../Components/Modal/ProductDetailsModal.jsx')
);

const ShortcutKeyHelper = lazy(
  () => import('../Components/UtillComponents/ShortcutKeyHelper.jsx')
);

const AllSalesPageSettings = lazy(
  () => import('../Components/UtillComponents/AllSalesPageSettings.jsx')
);

// Scss
import '../../../Styles/BookingScreen/Template/BSLayout2/BSLayout2.scss';
import useWhyDidYouUpdate from '../../../Services/findrerender.js';
import React from 'react';

const SalesCountForStandard = React.memo(() => {
  const dispatch = useDispatch();

  const AppId = getSession('AppId');
  const CompId = getSession('CompId');

  const BranchId = getSession('BranchId');
  const UserId = getSession('UserId');
  const ProdSubCat = useSelector(GlobalProductSubCategorie);
  const prodCat = useSelector(GlobalProductCategorie);
  const templateData = useSelector(getTemplateData);
  const [allowDecimal, setAllowDecimal] = useState(false);
  const [BookingModalOpen, setBookingModalOpen] = useState(false);
  const [ListOfInvoices, setListOfInvoices] = useState(false);

  const [Kioskopen, setKioskopen] = useState(false);
  const badgeCount = useSelector(globalKioskSalesCount);
  const OtherServicesglobal = useSelector(GlobalOtherSevices);
  const appPreferences = useSelector(ApplicationPreferences);
  const SessionData = useSelector(StoredSessionData);
  const OrderStatus = useSelector(GlobalOrderStatus);
  const dailySalesData = useSelector(GlobalSalesDetailData);

  const [page, setpage] = useState(1);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isNetAmtModalOpen, setIsNetAmtModalOpen] = useState(false);
  const [isReceivedModelOpen, setIsReceivedModelOpen] = useState(false);
  const [Customisebillno, setCustomisebillno] = useState(false);
  const bookings = dailySalesData?.[0]?.BookedDetails;
  const orderDetails = dailySalesData?.[0]?.OrderDetails;
  const [currentPage, setCurrentPage] = useState(1);
  const [TableData, setTableData] = useState([]);
  const [ProductDetailsModel, setProductDetailsModel] = useState(false);
  const [modalProductDetails, setModalProductDetails] = useState([]);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [SelectedIndex, setSelectedIndex] = useState(null);
  const [AutoReceiveStock, setAutoReceiveStock] = useState(false);
  const rowsPerPage = 10;

  const totalPages = Math.ceil((bookings?.length || 0) / rowsPerPage);
  const startIndex = (currentPage - 1) * rowsPerPage;
  const currentData = bookings?.slice(startIndex, startIndex + rowsPerPage);
  const preferencedata = useSelector(PreferenceData);

  const DineInAccess = useMemo(() => {
    return preferencedata?.[0]?.SettingDtlDetails?.filter(
      (i) => i.SettingIdName === 'DineIn'
    )?.[0];
  }, [preferencedata]);
  console.log(dailySalesData, 'dailySalesDatadailySalesData', bookings);

  const bookingTypePreference =
    appPreferences?.find((p) => p?.PreferredCatName === 'Booking Type')
      ?.PreferenceCatDetails || [];

  const dinePreference = bookingTypePreference.find(
    (p) =>
      p?.PreferredSubCatName?.toLowerCase() === 'dine in' &&
      p?.PreferredStatus === 'Y'
  );
  const takeAwayPreference = bookingTypePreference.find(
    (p) =>
      p?.PreferredSubCatName?.toLowerCase() === 'take away' &&
      p?.PreferredStatus === 'Y'
  );
  const commonModulePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Common Module'
  )?.PreferenceCatDetails;
  const sportsAppPreference = commonModulePreference?.find(
    (preference) =>
      preference?.PreferredSubCatName === 'SportsApp' &&
      preference?.PreferredStatus === 'Y'
  );
  const salespagefields = appPreferences?.find(
    (pref) => pref?.PreferredCatName === 'Sales Page Fields'
  )?.PreferenceCatDetails;

  const BookingStatus = useSelector(GlobalBookingStatus);
  const CheckBookingStatus =
    BookingStatus?.find((item) => item.ScreenType === 'Booking')
      ?.ScreenStatus ?? 'Open';
  const preferenceshortcutkey = preferencedata?.[0]?.[
    'SettingDtlDetails'
  ]?.some(
    (item) =>
      item.SettingIdName.toLowerCase() === 'shortcutkeys' &&
      item.SettingValue === 'Y'
  );
  const sales = dailySalesData?.[0] || {};
  const {
    DineInOrderCount = 0,
    TakeAwayOrderCount = 0,
    OverAllOrderCount = 0,
    SelfDineInOrderCount = 0,
    SelfTakeAwayOrderCount = 0,
    DineInAmount = 0,
    TakeAwayAmount = 0,
    OverAllTakeAwayOfferAmount = 0,
    OverAllDineInOfferAmount = 0,
    SelfTakeAwayAmount = 0,
    SelfDineInAmount = 0,
    PreOrderAmount = 0,
  } = sales;
  useEffect(() => {
    if (preferencedata?.length > 0) {
      const decimalSetting = preferencedata?.[0]?.SettingDtlDetails?.find(
        (s) =>
          s?.SettingIdName?.toLowerCase() === 'decimal' &&
          s?.SettingValue === 'Y'
      );
      setAllowDecimal(!!decimalSetting);
      let custombillsetting = preferencedata?.[0]?.SettingDtlDetails?.some(
        (s) =>
          s?.SettingIdName?.toLowerCase() === 'customisedbillnumber' &&
          s?.SettingValue === 'Y'
      );
      setCustomisebillno(custombillsetting);

      let AutoReceiveStock = preferencedata?.[0]?.SettingDtlDetails?.some(
        (s) =>
          s?.SettingIdName?.toLowerCase() === 'autoreceivestock' &&
          s?.SettingValue === 'Y'
      );

      setAutoReceiveStock(!AutoReceiveStock);
    }
  }, [preferencedata]);

  useEffect(() => {
    if (AppId && CompId && BranchId && UserId) {
      fetchBookingStatus();
      getReceivedStock();
    }
  }, [AppId, CompId, BranchId, UserId]);

  const getReceivedStock = async () => {
    try {
      const response = await dispatch(
        getReceivedStocks({ CompId, BranchId, AppId })
      ).unwrap();

      if (response?.data?.statusCode === 1) {
        setTableData(
          response.data.data?.map((e) => {
            return {
              ...e,
              DispatchStockDetails: e?.DispatchStockDetails?.map((e) => {
                return {
                  ...e,
                  AcceptedQty: e?.DispatchedQty,
                };
              }),
            };
          })
        );
      } else {
        setTableData([]);
        console.warn('API returned unsuccessful status', response);
      }
    } catch (error) {
      console.error('Failed to fetch received stock:', error);
    }
  };
  const columns = [
    {
      title: 'SL.NO',
      key: 'sno',
      align: 'center',
      width: '40px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Req Id',
      key: 'RequestId',
      align: 'center',
      width: '80px',
      render: (text, record, index) => record?.RequestId?.split('-')?.pop(),
    },
    {
      title: 'Date & Time',
      dataIndex: 'dateTime',
      key: 'dateTime',
      align: 'center',
      width: '150px',
      render: (text, record, index) => dateFormatChange1(record.CreatedDate),
    },
    {
      title: 'Received From',
      dataIndex: 'FromBranchName',
      key: 'FromBranchName',
      align: 'center',
      width: '120px',
    },
    {
      title: 'Item',
      // title: 'Item ',
      dataIndex: 'FromBranchName',
      key: 'FromBranchName',
      align: 'center',
      width: '50px',
      render: (text, record, index) => (
        <a style={{ color: 'black' }}>
          {record?.DispatchStockDetails?.length || 0}
        </a>
      ),
    },

    {
      title: 'Qty',
      // title: 'Qty',
      dataIndex: 'FromBranchName',
      key: 'FromBranchName',
      align: 'center',
      width: '50px',
      render: (text, record, index) => (
        <div>
          {(record?.DispatchStockDetails ?? []).reduce(
            (total, item) => total + (item?.DispatchedQty || 0),
            0
          )}
        </div>
      ),
    },
    {
      title: 'dispatched By',
      dataIndex: 'DispatcherName',
      key: 'DispatcherName',
      align: 'center',
      width: '120px',
    },

    {
      title: 'Actions',
      dataIndex: 'fromBranch',
      key: 'fromBranch',
      align: 'center',
      width: '100px',
      render: (_, record, index) => (
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <div
            className="sr-stock-recieve-button"
            title="Receive Stock"
            onClick={() => handleModalOpen(index)}
          >
            {' '}
            <span>Receive</span>
            <GoPackageDependencies size={18} />
          </div>
        </div>
      ),
    },
  ];
  const handlePageChange = (current) => {
    setpage(current);
  };
  const getstockbadge = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    await dispatch(getSelectedFavItems(data)).unwrap();

    let data1 = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ProdSubCat: ProdSubCat,
    };

    let data2 = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      prodCat: prodCat,
    };

    if (
      templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      ) &&
      ProdSubCat
    ) {
      await dispatch(getLayoutproductCard(data1)).unwrap();
    } else if (
      !templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      )
    ) {
      await dispatch(getCardDataWithoutSubmodule(data2)).unwrap();
    } else {
      await dispatch(getCardDataWithoutSub(data2)).unwrap();
    }
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);
  const postApi = async (data, index) => {
    try {
      let postData = {
        AppId: AppId,
        CompId: CompId,
        FromLocationId: data?.FromLocationId,
        ToLocationId: data?.ToLocationId,

        RequestId: data?.RequestId,
        DispatchId: data?.DispatchId,
        ReceiveStockDetails: data?.DispatchStockDetails?.map((e) => {
          return {
            ProdId: e?.ProdId,
            InwardDtlId: e?.InwardDtlId,
            ReceivedQty: e?.DispatchedQty,
            AcceptedQty: e?.AcceptedQty,
            CreatedBy: UserId,
          };
        }),
        CreatedBy: UserId,
      };

      let res = await dispatch(PostReceiveStocks(postData))?.unwrap();
      if (res?.data?.statusCode == 1) {
        setMessageData(res?.data?.response);
        setMessageType('success');
        await getReceivedStock();
        await getstockbadge();
      } else {
        setMessageData(res?.data?.response);
        setMessageType('error');
      }
    } catch (error) {
      console.log(error);
    }
  };
  const handleModalOpen = (index) => {
    setSelectedIndex(index);
    const pd = TableData?.[index]?.DispatchStockDetails || [];
    setModalProductDetails(
      Array.isArray(pd) ? JSON.parse(JSON.stringify(pd)) : []
    );
    setProductDetailsModel(true);
    setIsReceivedModelOpen(false);
  };

  const handleModalCancel = () => {
    setProductDetailsModel(false);
    setModalProductDetails([]);
    setIsReceivedModelOpen(true);
  };
  const handleModalSubmit = () => {
    const updatedData = {
      ...TableData[SelectedIndex],
      DispatchStockDetails: modalProductDetails,
    };
    setTableData((prev) => {
      const copy = Array.isArray(prev) ? [...prev] : [];
      const idx = SelectedIndex ?? 0;
      if (copy[idx]) {
        copy[idx] = updatedData;
      }
      return copy;
    });
    setProductDetailsModel(false);
    // setIsReceivedModelOpen(true)
    postApi(updatedData, SelectedIndex);
    setModalProductDetails([]);
  };
  const safeRound = (value) => {
    const num = Number(String(value).replace(/[^0-9.-]+/g, ''));
    if (isNaN(num)) return allowDecimal ? '0.00' : '0';
    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  };

  const totalTakeAway =
    TakeAwayAmount +
    SelfTakeAwayAmount +
    PreOrderAmount -
    OverAllTakeAwayOfferAmount;
  const totalDineIn =
    DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount;
  const netAmount = totalTakeAway + totalDineIn;

  const showSalesTooltip = useMemo(() => {
    return (
      DineInAccess?.SettingValue === 'Y' &&
      DineInOrderCount +
      TakeAwayOrderCount +
      SelfTakeAwayOrderCount +
      SelfDineInOrderCount >
      0 &&
      (takeAwayPreference || dinePreference)
    );
  }, [DineInAccess, sales, dinePreference, takeAwayPreference]);

  const renderBreakdown = (labelMap) => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
      <div style={{ display: 'flex', gap: '1rem' }}>
        <div>
          {labelMap.map(
            (item) => item.value !== 0 && <p key={item.label}>{item.label}</p>
          )}
        </div>
        <div style={{ textAlign: 'right' }}>
          {labelMap.map(
            (item) =>
              item.value !== 0 && (
                <p key={item.label}>{safeRound(item.value)}</p>
              )
          )}
        </div>
      </div>
      <div style={{ borderBottom: '1px dotted #fff', height: 0 }} />
      <div
        style={{
          display: 'flex',
          justifyContent: 'flex-end',
          gap: '1rem',
          fontSize: '16px',
          fontWeight: '600',
          fontFamily: 'Poppins',
        }}
      >
        <div>Total</div>
        <div>
          {safeRound(
            labelMap.reduce(
              (sum, item) => sum + (item.includeInTotal ? item.value : 0),
              0
            )
          )}
        </div>
      </div>
    </div>
  );

  const fetchBookingStatus = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      UserId: UserId,
    };
    await dispatch(getBookingStatus(data));
  };
  const BookingOpenFun = async (status) => {
    let Postdata = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      UserId: UserId,
      ScreenType: 'Booking',
      ScreenStatus: status,
      CreatedBy: UserId,
      Date: new Date(),
    };
    let Postresponse = await dispatch(PutBookingClose(Postdata)).unwrap();
    if (Postresponse?.data?.statusCode === 1) {
      fetchBookingStatus();
    } else {
    }
  };
  const openModalKiosk = () => {
    setKioskopen(true);
  };
  const closeModalKiosk = () => {
    setKioskopen(false);
  };

  const OpenBookingModal = () => {
    setBookingModalOpen(true);
  };
  const HandleBookingModalClose = () => {
    setBookingModalOpen(false);
  };

  const OpenListOfInvoices = () => {
    setListOfInvoices(true);
  };
  const handleInvoiceClose = () => {
    setListOfInvoices(false);
  };

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <div className="NewLayoutBillContainer">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="LicenseActive">
          <div>
            {showSalesTooltip ? (
              <Tooltip
                className="NetAmountNew"
                placement="bottom"
                title={
                  <div style={{ display: 'flex', gap: '1rem' }}>
                    {takeAwayPreference && (
                      <div style={{ display: 'flex', gap: '5px' }}>
                        <div>Takeaway:</div>
                        <div>{TakeAwayOrderCount + SelfTakeAwayOrderCount}</div>
                      </div>
                    )}
                    {dinePreference && (
                      <div style={{ display: 'flex', gap: '5px' }}>
                        <div>Dine-in:</div>
                        <div>{DineInOrderCount + SelfDineInOrderCount}</div>
                      </div>
                    )}
                  </div>
                }
                onClick={() =>
                  (OverAllOrderCount || 0) > 0 && setIsModalOpen(true)
                }
              >
                <FaChartLine color="#fde047" />
                <div className="NetAmountNew">
                  {isMobile ? 'Count' : 'Sales Count'} : {OverAllOrderCount}
                </div>
              </Tooltip>
            ) : (
              <div
                style={{
                  display: 'flex',
                  gap: '5px',
                  alignItems: 'center',
                  fontSize: '0.9rem',
                  cursor: 'pointer',
                }}
                onClick={() =>
                  (OverAllOrderCount || 0) > 0 && setIsModalOpen(true)
                }
              >
                <FaChartLine color="#ffffffff" />
                <div className="NetAmountNew">
                  {isMobile ? 'Count' : 'Sales Count'} : {OverAllOrderCount}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Rest of your component remains the same */}
        {DineInAccess?.SettingValue === 'Y' &&
          takeAwayPreference &&
          (TakeAwayOrderCount || SelfTakeAwayOrderCount || PreOrderAmount) >
          0 && (
            <Tooltip
              className="standardTooltipDineIN"
              title={renderBreakdown([
                {
                  label: 'Admin + Staff :',
                  value: TakeAwayAmount,
                  includeInTotal: true,
                },
                {
                  label: 'Self Booking :',
                  value: SelfTakeAwayAmount,
                  includeInTotal: true,
                },
                {
                  label: 'Preorder :',
                  value: PreOrderAmount,
                  includeInTotal: true,
                },
                {
                  label: 'Offer(-) :',
                  value: -OverAllTakeAwayOfferAmount,
                  includeInTotal: true,
                },
              ])}
            >
              <div
                className="standardTooltipDineIN"
                style={{
                  display: 'flex',
                  gap: '5px',
                  fontSize: '14px',
                  color: '#fff',
                }}
              >
                <div>{isMobile ? 'TA' : 'Take Away'} : </div>
                <div>{`₹ ${safeRound(totalTakeAway)}`}</div>
              </div>
            </Tooltip>
          )}

        {DineInAccess?.SettingValue === 'Y' &&
          dinePreference &&
          (DineInOrderCount || SelfDineInOrderCount) > 0 && (
            <Tooltip
              className="standardTooltipDineIN"
              title={renderBreakdown([
                {
                  label: 'Admin + Staff :',
                  value: DineInAmount,
                  includeInTotal: true,
                },
                {
                  label: 'Self Booking :',
                  value: SelfDineInAmount,
                  includeInTotal: true,
                },
                {
                  label: 'Offer(-) :',
                  value: -OverAllDineInOfferAmount,
                  includeInTotal: true,
                },
              ])}
            >
              <div
                className="standardTooltipDineIN"
                style={{
                  display: 'flex',
                  gap: '5px',
                  fontSize: '14px',
                  color: '#fff',
                }}
              >
                <div>{isMobile ? 'DI' : 'Dine In'} : </div>
                <div>{`₹ ${safeRound(totalDineIn)}`}</div>
              </div>
            </Tooltip>
          )}

        <div className="NetAmountIcons-Main">
          <div
            className="FaRupeeSign"
            onClick={() => netAmount > 0 && setIsNetAmtModalOpen(true)}
            style={{ cursor: 'pointer' }}
          >
            <FaRupeeSign color="#ffffffff" />
            <div className="NetAmountNew">
              {isMobile ? 'NA' : 'Net Amount'} : ₹ {safeRound(netAmount)}
            </div>
          </div>
        </div>
        {TableData?.length > 0 && !sportsAppPreference && AutoReceiveStock && (
          <button
            className="blink blinkStock"
            onClick={() => setIsReceivedModelOpen(true)}
          >
            <MdOutlineCallReceived />
            Stock
          </button>
        )}
        {preferenceshortcutkey && (
          <div className="KeyshortCutNav3">
            <ShortcutKeyHelper />
          </div>
        )}
        <AllSalesPageSettings />
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {Customisebillno && <CustomisedInvoiceChange />}
          {SessionData?.FeatureAddonData?.FeatureDtls?.find(
            (item) => item?.FeatureAddonName?.toLowerCase() === 'kiosk sales'
          ) &&
            !sportsAppPreference && (
              <div
                style={{
                  pointerEvents: OrderStatus > 0 ? 'none' : 'auto',
                  opacity: OrderStatus > 0 ? 0.5 : 1,
                }}
              >
                {!OtherServicesglobal && (
                  <Tooltip title={'Kiosk Sales'}>
                    <Badge count={badgeCount} offset={[-10, 3]} size="small">
                      <PozoKioskIcon
                        onClick={() => openModalKiosk()}
                        style={{ cursor: 'pointer', fontSize: '1.5rem' }}
                        className="iconsize"
                      />
                    </Badge>
                  </Tooltip>
                )}
              </div>
            )}
          {Kioskopen && (
            <BSKioskCounterPayment
              Kioskopen={Kioskopen}
              closeKioskModal={closeModalKiosk}
            />
          )}
          <ProductPriceChange />
          {!OtherServicesglobal && !sportsAppPreference && (
            <TooltipWrapper title={'Low Stock Alerts'} isMobile={isMobile}>
              {' '}
              <BSExpireProductsList />
            </TooltipWrapper>
          )}

          {!OtherServicesglobal && (
            <>
              {CheckBookingStatus == 'Open' ? (
                <div style={{ marginLeft: '10px' }}>
                  <TooltipWrapper title={'Booking Close'} isMobile={isMobile}>
                    {' '}
                    <BookingCloseIcon
                      onClick={OpenBookingModal}
                      bgFill={'#52c41a'}
                      style={{
                        fontSize: '16px',
                        marginTop: '4px',
                        color: '#52c41a',
                        cursor: 'pointer',
                      }}
                    />
                  </TooltipWrapper>
                </div>
              ) : (
                <div style={{ marginLeft: '10px' }}>
                  <TooltipWrapper title="Booking Open" isMobile={isMobile}>
                    <Popconfirm
                      placement="leftTop"
                      title="Booking Open"
                      description="Are you sure you want to Open the sales?"
                      okText="Yes"
                      cancelText="No"
                      onConfirm={() => BookingOpenFun('Open')}
                    >
                      <span>
                        <BookingCloseIcon
                          bgFill="red"
                          style={{
                            fontSize: '16px',
                            marginTop: '4px',
                            color: '#52c41a',
                            cursor: 'pointer',
                          }}
                        />
                      </span>
                    </Popconfirm>
                  </TooltipWrapper>
                </div>
              )}
              {!sportsAppPreference && (
                <div style={{ marginLeft: '10px' }}>
                  <TooltipWrapper title={'E-way Bill'} isMobile={isMobile}>
                    {''}
                    <BSEwayBillicon
                      style={{ cursor: 'pointer', marginTop: '5px' }}
                      onClick={OpenListOfInvoices}
                    />
                  </TooltipWrapper>
                </div>
              )}
            </>
          )}

          {BookingModalOpen && (
            <RetailBookingClosing
              PaymentOpen={BookingModalOpen}
              PaymentClose={HandleBookingModalClose}
            />
          )}
          {ListOfInvoices && (
            <ListOfSalesInvoices
              ListOfInvoicesOpen={ListOfInvoices}
              handleInvoiceClose={handleInvoiceClose}
            />
          )}
        </div>

        {/* Modal with table for multiple bookings */}

        <DefaultModal
          open={isModalOpen}
          title="Sales Details"
          handleCancel={() => setIsModalOpen(false)}
          handleSubmit={() => setIsModalOpen(false)}
          width={700}
          footer={false}
        >
          <div style={{ overflowX: 'auto' }}>
            <table
              style={{
                width: '100%',
                borderCollapse: 'collapse',
                fontFamily: "'Segoe UI', Roboto, sans-serif",
                fontSize: '14px',
                borderRadius: '8px',
                overflow: 'hidden',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              }}
            >
              <thead>
                <tr style={{ backgroundColor: '#003366', color: '#fff' }}>
                  <th style={{ border: '1px solid #ddd', padding: '10px' }}>
                    S.No
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '10px' }}>
                    Order ID
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '10px' }}>
                    Customer
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '10px' }}>
                    Mobile
                  </th>
                  {/* <th style={{ border: "1px solid #ddd", padding: "10px" }}>Booked By</th> */}
                  <th style={{ border: '1px solid #ddd', padding: '10px' }}>
                    Payment Type
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '10px' }}>
                    Amount (₹)
                  </th>
                </tr>
              </thead>

              <tbody>
                {currentData?.length > 0 ? (
                  currentData?.map((item, index) => (
                    <tr
                      key={item.OrderId}
                      style={{
                        backgroundColor:
                          index % 2 === 0 ? '#f7faff' : '#e9f1ff',
                        textAlign: 'center',
                        transition: 'background 0.3s',
                      }}
                      onMouseEnter={(e) =>
                        (e.currentTarget.style.backgroundColor = '#d6e4ff')
                      }
                      onMouseLeave={(e) =>
                      (e.currentTarget.style.backgroundColor =
                        index % 2 === 0 ? '#f7faff' : '#e9f1ff')
                      }
                    >
                      <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                        {startIndex + index + 1}
                      </td>
                      <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                        {extractLastNumberOrderId(item.OrderId)}
                      </td>
                      <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                        {item.CustName || '—'}
                      </td>
                      <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                        {item.CustMobile || '—'}
                      </td>
                      {/* <td style={{ border: "1px solid #ddd", padding: "8px" }}>
                                            {item.BookedBy || "—"}
                                        </td> */}
                      <td style={{ border: '1px solid #ddd', padding: '8px' }}>
                        {item.PaymentTypeName || '—'}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          padding: '8px',
                          fontWeight: '600',
                          color: '#2e7d32',
                          backgroundColor: '#eaf6ea',
                        }}
                      >
                        ₹{item.Amount?.toLocaleString()}
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td
                      colSpan="7"
                      style={{
                        textAlign: 'center',
                        padding: '12px',
                        border: '1px solid #ddd',
                        color: '#888',
                      }}
                    >
                      No booking data available
                    </td>
                  </tr>
                )}
              </tbody>
            </table>

            {/* Pagination */}
            {totalPages > 1 && (
              <div
                style={{
                  marginTop: '12px',
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  gap: '8px',
                }}
              >
                {currentPage == 1 ? (
                  ''
                ) : (
                  <button
                    onClick={() => setCurrentPage((p) => Math.max(p - 1, 1))}
                    disabled={currentPage === 1}
                    style={{
                      padding: '5px 10px',
                      backgroundColor: '#003366',
                      color: '#fff',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
                      opacity: currentPage === 1 ? 0.5 : 1,
                    }}
                  >
                    Prev
                  </button>
                )}

                <span style={{ fontWeight: '600' }}>
                  Page {currentPage} of {totalPages}
                </span>

                <button
                  onClick={() =>
                    setCurrentPage((p) => Math.min(p + 1, totalPages))
                  }
                  disabled={currentPage === totalPages}
                  style={{
                    padding: '5px 10px',
                    backgroundColor: '#003366',
                    color: '#fff',
                    border: 'none',
                    borderRadius: '4px',
                    cursor:
                      currentPage === totalPages ? 'not-allowed' : 'pointer',
                    opacity: currentPage === totalPages ? 0.5 : 1,
                  }}
                >
                  Next
                </button>
              </div>
            )}
          </div>
        </DefaultModal>

        {/* Modal with table for multiple Net Amt */}

        <DefaultModal
          open={isNetAmtModalOpen}
          title="Sales Net Amount"
          handleCancel={() => setIsNetAmtModalOpen(false)}
          handleSubmit={() => setIsNetAmtModalOpen(false)}
          width={800}
          footer={false}
        >
          <div style={{ overflowX: 'auto' }}>
            <table
              style={{
                width: '100%',
                borderCollapse: 'collapse',
                textAlign: 'center',
                fontFamily: "'Segoe UI', Roboto, sans-serif",
                fontSize: '14px',
                borderRadius: '8px',
                overflow: 'hidden',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              }}
            >
              <thead>
                <tr style={{ backgroundColor: '#003366', color: '#fff' }}>
                  <th
                    colSpan="2"
                    style={{ border: '1px solid #ddd', padding: '10px' }}
                  >
                    Cash
                  </th>
                  <th
                    colSpan="2"
                    style={{ border: '1px solid #ddd', padding: '10px' }}
                  >
                    UPI
                  </th>
                  <th
                    colSpan="2"
                    style={{ border: '1px solid #ddd', padding: '10px' }}
                  >
                    Card
                  </th>
                  <th
                    colSpan="2"
                    style={{ border: '1px solid #ddd', padding: '10px' }}
                  >
                    Credit
                  </th>
                  <th
                    colSpan="2"
                    style={{ border: '1px solid #ddd', padding: '10px' }}
                  >
                    Business UPI
                  </th>
                  <th
                    rowSpan="2"
                    style={{
                      border: '1px solid #ddd',
                      padding: '10px',
                      backgroundColor: '#002244',
                      color: '#fff',
                    }}
                  >
                    Total
                  </th>
                </tr>
                <tr style={{ backgroundColor: '#004080', color: '#fff' }}>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Count
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Amt
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Count
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Amt
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Count
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Amt
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Count
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Amt
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Count
                  </th>
                  <th style={{ border: '1px solid #ddd', padding: '8px' }}>
                    Amt
                  </th>
                </tr>
              </thead>

              <tbody>
                {orderDetails?.map((item, index) => {
                  const total =
                    (item.CashAmount || 0) +
                    (item.UpiAmount || 0) +
                    (item.CardAmount || 0) +
                    (item.CreditAmount || 0);

                  return (
                    <tr
                      key={index}
                      style={{
                        backgroundColor:
                          index % 2 === 0 ? '#f7faff' : '#ffffff',
                        transition: 'background 0.3s',
                      }}
                      onMouseEnter={(e) =>
                        (e.currentTarget.style.backgroundColor = '#e6f2ff')
                      }
                      onMouseLeave={(e) =>
                      (e.currentTarget.style.backgroundColor =
                        index % 2 === 0 ? '#f7faff' : '#ffffff')
                      }
                    >
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.CashCount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.CashAmount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.UpiCount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.UpiAmount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.CardCount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.CardAmount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.CreditCount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.CreditAmount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.BusinessUpiCount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          fontWeight: '700',
                          padding: '8px',
                        }}
                      >
                        {item.BusinessUpiAmount}
                      </td>
                      <td
                        style={{
                          border: '1px solid #ddd',
                          padding: '8px',
                          fontWeight: '700',
                          backgroundColor: '#eaf6ea',
                          color: '#2e7d32',
                        }}
                      >
                        {total}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </DefaultModal>

        <ReceivedStocksModal
          open={isReceivedModelOpen}
          onClose={() => {
            setIsReceivedModelOpen(false);
          }}
          columns={columns}
          tableData={TableData}
          handlePageChange={handlePageChange}
          customTable={false}
        />

        <ProductDetailsModal
          open={ProductDetailsModel}
          onClose={handleModalCancel}
          productDetails={modalProductDetails}
          headerData={{
            dateTime: dateFormatChange1(
              TableData?.[SelectedIndex]?.CreatedDate
            ),
            fromBranch: TableData?.[SelectedIndex]?.FromBranchName,
            Dispatch_Id: TableData?.[SelectedIndex]?.DispatchId,
            Created_By: TableData?.[SelectedIndex]?.Created_By,
          }}
          onDataChange={(d) => setModalProductDetails(d)}
          onSubmit={handleModalSubmit}
        />
      </div>
    </Suspense>
  );
});

export default SalesCountForStandard;
