import React, {
  useMemo,
  useState,
  useEffect,
  useRef,
  useCallback,
} from 'react';
import { Tooltip } from 'antd';
import {
  dateFormatChange1,
  extractLastNumberOrderId,
  getSession,
} from '../../../Services/Others';
import { useDispatch } from 'react-redux';
import {
  getCardDataWithoutSub,
  getCardDataWithoutSubmodule,
  getLayoutproductCard,
  getPreferenceData,
  getSelectedFavItems,
  GlobalProductCategorie,
  GlobalProductSubCategorie,
  GlobalSalesDetailData,
  PreferenceData,
} from '../../../Features/BookingScreen/BookingData/BookingData';
import './SalesCountComponent.scss';
import { Messages } from '../../../Components/Notifications/Messages';
import { useSelector } from 'react-redux';
import { ApplicationPreferences } from '../../../Features/BrachLogin/BranchLogin';
import { DefaultModal } from '../../../Components/Modal/DefaultModal';
import { Tables } from '../../../Components/Tables/Table';
import CustomisedInvoiceChange from '../Components/UtillComponents/CustomisedInvoiceChange.jsx';
import ProductPriceChange from '../Components/UtillComponents/ProductPriceChange.jsx';
import ReceivedStocksModal from '../../../Components/Modal/ReceivedStocksModal.jsx';
import ProductDetailsModal from '../../../Components/Modal/ProductDetailsModal.jsx';
import { MdOutlineCallReceived } from 'react-icons/md';
import { IoEye } from 'react-icons/io5';
import { TiTickOutline } from 'react-icons/ti';
import {
  getReceivedStocks,
  PostReceiveStocks,
} from '../../../Features/stockReceivedGodown/ReceivedStock.js';
import { GoPackageDependencies } from 'react-icons/go';
import { getTemplateData } from '../../../Features/ThemeChange/ThemeChange.js';
import ShortcutKeyHelper from '../Components/UtillComponents/ShortcutKeyHelper.jsx';
import AllSalesPageSettings from '../Components/UtillComponents/AllSalesPageSettings.jsx';

const SalesCountComponent = React.memo(
  ({ DineInAccess, GlobalsalesDetailData }) => {
    // Destructure to simplify access to required values
    const {
      DineInOrderCount,
      TakeAwayOrderCount,
      OverAllOrderCount,
      SelfDineInOrderCount,
      SelfTakeAwayOrderCount,
      DineInAmount,
      TakeAwayAmount,
      OverAllTakeAwayOfferAmount,
      OverAllDineInOfferAmount,
      SelfTakeAwayAmount,
      SelfDineInAmount,
      PreOrderAmount,
    } = GlobalsalesDetailData.length > 0 ? GlobalsalesDetailData[0] : {};

    const dispatch = useDispatch();
    const appPreferences = useSelector(ApplicationPreferences);
    const dailySalesData = useSelector(GlobalSalesDetailData);
    const ProdSubCat = useSelector(GlobalProductSubCategorie);
    const prodCat = useSelector(GlobalProductCategorie);
    const templateData = useSelector(getTemplateData);
    const preferencedata = useSelector(PreferenceData);

    console.log(preferencedata, 'preferencedatasalescount');
    const bookingTypePreference = appPreferences?.find(
      (preference) => preference?.PreferredCatName === 'Booking Type'
    )?.PreferenceCatDetails;
    const dinePreference = bookingTypePreference?.find(
      (type) =>
        type?.PreferredSubCatName?.toLowerCase() === 'dine in' &&
        type?.PreferredStatus === 'Y'
    );
    const takeAwayPreference = bookingTypePreference?.find(
      (type) =>
        type?.PreferredSubCatName?.toLowerCase() === 'take away' &&
        type?.PreferredStatus === 'Y'
    );
      const preferenceshortcutkey = preferencedata?.[0]?.[
    'SettingDtlDetails'
  ]?.some(
    (item) =>
      item.SettingIdName.toLowerCase() === 'shortcutkeys' &&
      item.SettingValue === 'Y'
  );

    const [messageType, setMessageType] = useState(null);
    const [messageData, setMessageData] = useState(null);
    const [page, setpage] = useState(1);
    const formRef = useRef(null);
    const [allowDecimal, setAllowDecimal] = useState(false);
    const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
    const AppId = getSession('AppId');
    const CompId = getSession('CompId');
    const BranchId = getSession('BranchId');
    const UserId = getSession('UserId');
    const [TableData, setTableData] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isNetAmtModalOpen, setIsNetAmtModalOpen] = useState(false);
    const [Customisebillno, setCustomisebillno] = useState(false);
    const [isReceivedModelOpen, setIsReceivedModelOpen] = useState(false);
    const [ProductDetailsModel, setProductDetailsModel] = useState(false);
    const [modalProductDetails, setModalProductDetails] = useState([]);
    const [AutoReceiveStock, setAutoReceiveStock] = useState(false);
    const [SelectedIndex, setSelectedIndex] = useState(null);
    const bookings = dailySalesData?.[0]?.BookedDetails;
    const orderDetails = dailySalesData?.[0]?.OrderDetails;
    const [currentPage, setCurrentPage] = useState(1);
    const rowsPerPage = 10;

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

    console.log(dailySalesData, 'dailySalesDatadailySalesData', bookings);

    function safeRound(amountStr) {
      if (amountStr == null) return allowDecimal ? '0.00' : '0';

      const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
      const num = Number(cleaned);

      if (isNaN(num)) return allowDecimal ? '0.00' : '0';

      return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
    }
    // Memoize the tooltip content
    const tooltipContent = useMemo(() => {
      if (
        DineInAccess?.SettingValue === 'Y' &&
        dinePreference &&
        (DineInOrderCount > 0 ||
          TakeAwayOrderCount > 0 ||
          SelfTakeAwayOrderCount > 0 ||
          SelfDineInOrderCount > 0)
      ) {
        return (
          <Tooltip
            title={
              <div style={{ display: 'flex', gap: '1rem' }}>
                {takeAwayPreference && (
                  <p>
                    Take Away:{' '}
                    {TakeAwayOrderCount + SelfTakeAwayOrderCount || 0}
                  </p>
                )}
                <p>Dine In: {DineInOrderCount + SelfDineInOrderCount || 0}</p>
              </div>
            }
          >
            <p
              style={{ fontSize: '14px', cursor: 'pointer' }}
              onClick={() =>
                (OverAllOrderCount || 0 > 0) && setIsModalOpen(true)
              }
            >
              {isMobile ? 'SC' : 'Sales Count'}:{' '}
              <span>{OverAllOrderCount || 0}</span>
            </p>
          </Tooltip>
        );
      }
      return (
        <p
          style={{ fontSize: '14px' }}
          onClick={() => (OverAllOrderCount || 0) > 0 && setIsModalOpen(true)}
        >
          {isMobile ? 'SC' : 'Sales Count'}:{' '}
          <span>{OverAllOrderCount || 0}</span>
        </p>
      );
    }, [
      DineInAccess?.SettingValue,
      DineInOrderCount,
      TakeAwayOrderCount,
      OverAllOrderCount,
      isMobile,
    ]);
    useEffect(() => {
      getPreference();
      getReceivedStock();

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

    const getPreference = async () => {
      // const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
      // const { data: res } = await dispatch(getPreferenceData(data)).unwrap();
      const decimalSetting = preferencedata?.[0]?.SettingDtlDetails?.find(
        (setting) =>
          setting?.SettingIdName?.toLowerCase() === 'decimal' &&
          setting?.SettingValue === 'Y'
      );
      if (decimalSetting) {
        setAllowDecimal(true);
      }
      let custombillsetting = preferencedata?.[0]?.SettingDtlDetails?.some(
        (s) =>
          s?.SettingIdName?.toLowerCase() === 'customisedbillnumber' &&
          s?.SettingValue === 'Y'
      );

      setCustomisebillno(custombillsetting);
    };
    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);
      }
    };
    useEffect(() => {
      const handleResize = () => setIsMobile(window.innerWidth < 768);
      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
    }, []);

    const onComplete = useCallback(() => {
      setMessageData(null);
      setMessageType(null);
    }, []);
    const columns = [
      {
        title: 'SL.NO',
        key: 'sno',
        align: 'center',
        width: '50px',
        render: (text, object, index) => (
          <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
        ),
      },
      {
        title: 'Req Id',
        key: 'RequestId',
        align: 'center',
        width: '70px',
        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',
        dataIndex: 'FromBranchName',
        key: 'FromBranchName',
        align: 'center',
        width: '50px',
        render: (text, record, index) => (
          <a style={{ color: 'black' }}>
            {record?.DispatchStockDetails?.length || 0}
          </a>
        ),
      },

      {
        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: 'Product Details',
      //   dataIndex: 'ProductDetails',
      //   key: 'ProductDetails',
      //   width: '120px',
      //   align: 'center',
      //   render: (text, record, index) => (
      //     <span
      //       style={{ cursor: 'pointer', color: '#1890ff', textAlign: "center" }}
      //       onClick={() => {

      //         handleModalOpen(index)
      //       }}
      //     >
      //       <IoEye style={{ fontSize: 18, verticalAlign: 'middle' }} />
      //     </span>
      //   ),

      // },
      {
        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 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([]);
    };
    return (
      <>
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="SalesCountComponent-Master">
          {tooltipContent}
          {DineInAccess?.SettingValue === 'Y' &&
            takeAwayPreference &&
            (TakeAwayOrderCount > 0 ||
              SelfTakeAwayOrderCount > 0 ||
              PreOrderAmount > 0) && (
              <Tooltip
                title={
                  <div
                    style={{
                      display: 'flex',
                      gap: '0.5rem',
                      flexDirection: 'column',
                    }}
                  >
                    <div style={{ display: 'flex', gap: '1rem' }}>
                      <div>
                        <p>Admin + Staff : </p>
                        {SelfTakeAwayAmount != 0 && <p>Self Booking : </p>}
                        {PreOrderAmount != 0 && <p>Preorder : </p>}
                        {OverAllTakeAwayOfferAmount != 0 && <p>Offer(-) : </p>}
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <p>{safeRound(TakeAwayAmount)}</p>
                        {SelfTakeAwayAmount != 0 && (
                          <p>{safeRound(SelfTakeAwayAmount)}</p>
                        )}
                        {PreOrderAmount != 0 && (
                          <p>{safeRound(PreOrderAmount)}</p>
                        )}
                        {OverAllTakeAwayOfferAmount != 0 && (
                          <p>{safeRound(OverAllTakeAwayOfferAmount)}</p>
                        )}
                      </div>
                    </div>
                    <div
                      style={{
                        flexGrow: 1,
                        borderBottom: '1px dotted #fff',
                        height: 0,
                      }}
                    ></div>
                    <div
                      style={{
                        display: 'flex',
                        gap: '1rem',
                        justifyContent: 'flex-end',
                        fontSize: '16px',
                        fontWeight: '600',
                        fontFamily: 'Poppins',
                      }}
                    >
                      <div>Total</div>
                      <div>
                        {safeRound(
                          TakeAwayAmount +
                            SelfTakeAwayAmount +
                            PreOrderAmount -
                            OverAllTakeAwayOfferAmount
                        )}
                      </div>
                    </div>
                  </div>
                }
              >
                <p style={{ fontSize: '14px' }}>
                  {isMobile ? 'TA' : 'Take Away'}:{' '}
                  <span>
                    {safeRound(
                      (TakeAwayAmount ||
                        0 + SelfTakeAwayAmount ||
                        0 + PreOrderAmount ||
                        0) - OverAllTakeAwayOfferAmount
                    )}
                  </span>
                </p>

                {/* <p>
            Take Away: <span>{Math.round(((TakeAwayAmount + SelfTakeAwayAmount + PreOrderAmount) - OverAllTakeAwayOfferAmount)) || 0}</span>
          </p> */}
              </Tooltip>
            )}
          {DineInAccess?.SettingValue === 'Y' &&
            dinePreference &&
            (DineInOrderCount > 0 || SelfDineInOrderCount > 0) && (
              <Tooltip
                title={
                  <div
                    style={{
                      display: 'flex',
                      gap: '0.5rem',
                      flexDirection: 'column',
                    }}
                  >
                    <div style={{ display: 'flex', gap: '1rem' }}>
                      <div>
                        <p>Admin + Staff : </p>
                        {SelfDineInAmount != 0 && <p>Self Booking : </p>}
                        {OverAllDineInOfferAmount != 0 && <p>Offer(-) : </p>}
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <p>{safeRound(DineInAmount)}</p>
                        {SelfDineInAmount != 0 && (
                          <p>{safeRound(SelfDineInAmount)}</p>
                        )}
                        {OverAllDineInOfferAmount != 0 && (
                          <p>{safeRound(OverAllDineInOfferAmount)}</p>
                        )}
                      </div>
                    </div>
                    <div
                      style={{
                        flexGrow: 1,
                        borderBottom: '1px dotted #fff',
                        height: 0,
                      }}
                    ></div>
                    <div
                      style={{
                        display: 'flex',
                        gap: '1rem',
                        justifyContent: 'flex-end',
                        fontSize: '16px',
                        fontWeight: '600',
                        fontFamily: 'Poppins',
                      }}
                    >
                      <div>Total</div>
                      <div>
                        {safeRound(
                          DineInAmount +
                            SelfDineInAmount -
                            OverAllDineInOfferAmount
                        )}
                      </div>
                    </div>
                  </div>
                }
              >
                <p style={{ fontSize: '14px' }}>
                  {isMobile ? 'DI' : 'Dine In'}:{' '}
                  <span>
                    {safeRound(
                      DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount
                    )}
                  </span>
                </p>
                {/* <p>
            Dine In: <span>{Math.round(((DineInAmount + SelfDineInAmount) - OverAllDineInOfferAmount)) || 0}</span>
          </p> */}
              </Tooltip>
            )}

          <p
            style={{ fontSize: '14px', cursor: 'pointer' }}
            onClick={() =>
              safeRound(
                (TakeAwayAmount +
                  SelfTakeAwayAmount +
                  PreOrderAmount -
                  OverAllTakeAwayOfferAmount || 0) +
                  (DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount)
              ) > 0 && setIsNetAmtModalOpen(true)
            }
          >
            {isMobile ? 'NA' : 'Net Amt'}:{' '}
            <span>
              {safeRound(
                (TakeAwayAmount +
                  SelfTakeAwayAmount +
                  PreOrderAmount -
                  OverAllTakeAwayOfferAmount || 0) +
                  (DineInAmount + SelfDineInAmount - OverAllDineInOfferAmount)
              )}
            </span>
          </p>
          {Customisebillno && <CustomisedInvoiceChange />}
          {/* 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>
    <Tooltip title="Receive Stock">
          {TableData?.length > 0 && AutoReceiveStock && (
            <button
              className="blink blinkStock"
              onClick={() => setIsReceivedModelOpen(true)}
              title="Received Stock"
            >
              <MdOutlineCallReceived />
               Stock
            </button>
          )}
            </Tooltip>
        </div>
      {preferenceshortcutkey &&  <ShortcutKeyHelper />}   
        <AllSalesPageSettings />
        <ProductPriceChange />
        <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,
            Created_By: TableData?.[SelectedIndex]?.Created_By,
            Dispatch_Id: TableData?.[SelectedIndex]?.DispatchId,
          }}
          onDataChange={(d) => setModalProductDetails(d)}
          onSubmit={handleModalSubmit}
        />
      </>
    );
  }
);

export default SalesCountComponent;
