import React, {
  useState,
  useEffect,
  useRef,
  useCallback,
  useContext,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { EditFilled, ArrowRightOutlined } from '@ant-design/icons';
import {
  Avatar,
  Flex,
  Segmented,
  Badge,
  Form,
  DatePicker,
  Input,
  Popconfirm,
  Table,
  Button,
  Checkbox,
  Modal,
  Space,
} from 'antd';
import Search from '../../../../Components/Forms/Search.jsx';
import { Tables } from '../../../../Components/Tables/Table.jsx';
import { RiCloseCircleFill } from 'react-icons/ri';
import { MdHistory } from 'react-icons/md';
import { FiPlus } from 'react-icons/fi';
import { BsClipboardCheckFill } from 'react-icons/bs';
import { MdOutlinePendingActions } from 'react-icons/md';
import BSCustomerSelect from './BSSelectCustomer.jsx';
import BSNavBarAddUser from './BSNavBarAddUser.jsx';
import { InputField } from '../../../../Components/Forms/InputField.jsx';
import TimePickers from '../../../../Components/Forms/TimePickerProduct.jsx';
import Buttons from '../../../../Components/Forms/Buttons.jsx';
import Imageupload from '../../../../Components/Forms/Upload.jsx';
import TextAreaInput from '../../../../Components/Forms/TextArea.jsx';
import WpIcon from '../../../../Images/message.png';
import QrinScreen from '../BookingFunctionality/DynamicScreenQr.jsx';
import {
  getConfigType,
  SendPaymentLink,
  GlobalSelCustId,
  GlobalSelOption,
  GlobalpaymentUpiOptionData,
  changeCustomerID,
  changeSelectedCustId,
  changeSelectedOption,
  changeSummeryTotalAmount,
  changealldata,
  changeBookingType,
  GlobalBookingType,
  GetPaymentdeviceResponse,
  PostPaymentdevice,
  PutBookingPaymentStatusChange,
  changeCompoPreOrderDtlStatus,
  changeDropDownStatus,
  GlobalCommonPaymentOptions,
  changePaymentloader,
  GlobalUpiIDprint,
  PutPendingPaymentList,
  ChangeSearchFocusPreOrder,
  PaymentCardGetdetail,
  GlobalCustId,
  changePaymentTransactionNumber,
  getSalesDetailData,
  PreferenceData,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
import {
  PreOrderBookingData,
  PreOrderGet,
  PreOrderBookingDataPut,
  GlobalPreOrderList,
  GlobalPreOrderAdditem,
  changePreOrderAdditem,
  GlobalPreOrderCusName,
  GlobalPreOrderCusMobNo,
  GlobalPreOrderDate,
  GlobalPreOrderAdvance,
  GlobalPreOrderMessage,
  GlobalPreOrderAdd1,
  GlobalPreOrderAdd2,
  GlobalPreOrderzip,
  GlobalPreOrderCity,
  GlobalPreOrderDistrict,
  GlobalPreOrderState,
  GlobalPreOrderTime,
  changePreOrderDate,
  changepreOrder,
  changepreOrderList,
  changePreOrderCusName,
  changePreOrderCusMob,
  changePreOrderAdvance,
  changePreOrderAdd1,
  changePreOrderAdd2,
  changePreOrderzip,
  changePreOrderCity,
  changePreOrderDistrict,
  changePreOrderState,
  changePreOrderTime,
  GlobalpreOrderOpen,
  changePreOrderPendingCount,
  PreOrderBookingDataCancel,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import { IoEye } from 'react-icons/io5';
import {
  ChangeTotalAmount,
  globalExtraTotalAmount,
} from '../../../../Features/ExteraCharges/ExtraCharges.js';
import {
  extractLastNumber,
  getSession,
  extractLastNumberOrderId,
  printDiv,
  encryptedValuesFun,
  validateSafeInput,
} from '../../../../Services/Others.js';
import { DropDowns } from '../../../../Components/Forms/DropDown.jsx';
import {
  GlobalSelectedColor,
  GlobalSelectedFont,
  SelectedPrintTemplate,
} from '../../../../Features/ThemeChange/ThemeChange.js';
import CountUp from 'react-countup';
import { isMobile } from 'react-device-detect';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
import BsBillingCreditCustomer from '../BookingFunctionality/BSBillingCreditCustomer.jsx';
import MobilePrint from '../BookingFunctionality/MobilePrint.jsx';
import { Messages } from '../../../../Components/Notifications/Messages.jsx';
import '../../../../Styles/BookingScreen/Components/UtillComponents/BSNavBarPreOrder.scss';
import { DatePicProd } from '../../../../Components/Forms/DatePickerProduct.jsx';
import { PrintStyleFunction } from '../../../paymentpdfPage/PrintStyleFunction.js';
import { GlobalAddCustomerDetails } from '../../../../Features/BookingScreen/Customer/addCustomer.js';
import SplitPayment from '../BookingFunctionality/SplitPaymentPreorder.jsx';
import PaymentPdfBooking from '../../../paymentpdfPage/PaymentPdfBooking.jsx';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import useCountUp from './useCountUp.jsx';

const MainHomeUrl = import.meta.env.ENV_MAIN_BASE_URL;

const BSComboNavBarPreOrder = () => {
  //other Hooks
  const dispatch = useDispatch();
  const splitRef = useRef();
  const formRef = useRef();
  const ViewformRef = useRef();
  const cancelformRef = useRef();
  const [Pendingform] = Form.useForm();
  const [Itemform] = Form.useForm();

  //useSelector
  const GlobalUpiID = useSelector(GlobalUpiIDprint);

  const preOrderOpen = useSelector(GlobalpreOrderOpen);
  const printerTemplateStyle = useSelector(SelectedPrintTemplate);
  const SelectedCust = useSelector(GlobalSelOption);
  const SelCustId = useSelector(GlobalSelCustId);
  const selOption = useSelector(GlobalSelOption);

  const PreOrderAdditem = useSelector(GlobalPreOrderAdditem);
  const PreOrderCusName = useSelector(GlobalPreOrderCusName);
  const PreOrderCusMobNo = useSelector(GlobalPreOrderCusMobNo);
  const PreOrderDate = useSelector(GlobalPreOrderDate);
  const PreOrderList = useSelector(GlobalPreOrderList);
  const PreOrderAdvance = useSelector(GlobalPreOrderAdvance);
  const PreOrderMessage = useSelector(GlobalPreOrderMessage);
  const PreOrderAdd1 = useSelector(GlobalPreOrderAdd1);
  const PreOrderAdd2 = useSelector(GlobalPreOrderAdd2);
  const PreOrderzip = useSelector(GlobalPreOrderzip);
  const PreOrderCity = useSelector(GlobalPreOrderCity);
  const PreOrderDistrict = useSelector(GlobalPreOrderDistrict);
  const PreOrderState = useSelector(GlobalPreOrderState);
  const PreOrderTime = useSelector(GlobalPreOrderTime);
  const preferenceData = useSelector(PreferenceData);
  const BookingTypeData = useSelector(GlobalBookingType);
  const GetCustId = useSelector(GlobalCustId);

  const preferCondition =
    preferenceData?.[0]?.['SettingDtlDetails']?.filter(
      (e) => e?.SettingIdName == 'PreOrderPriceChange'
    )?.[0]?.SettingValue == 'Y';
  // other Const
  dayjs.extend(customParseFormat);
  const AppId = getSession('AppId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserId = getSession('UserId');

  const FontFamily = useSelector(GlobalSelectedFont);
  const Color = useSelector(GlobalSelectedColor);
  const GlobalExtraCharge = useSelector(globalExtraTotalAmount);
  const EditableContext = React.createContext(null);
  const PendingEditableContext = React.createContext(null);
  const useOptions = useSelector(GlobalCommonPaymentOptions);
  // const AddCustomerDetails = useSelector(GlobalAddCustomerDetails);

  //useStates

  const [PendingData, setPendingData] = useState();
  const [BookingType, setBookingType] = useState();
  const [UpiOpen, setUpiOpen] = useState(false);
  const [UpiId, setUpiId] = useState();
  const [Edit, setEdit] = useState(false);
  const [qrcode, setqrcode] = useState(false);
  const [selectedPaymentOption, setselectedPaymentOption] = useState();
  const PaymentUpiOptions = useSelector(GlobalpaymentUpiOptionData);
  const [selectedUPIOption, setselectedUPIOption] = useState();
  const [PreOrder, setPreOrder] = useState(false);

  console.log(PreOrder, 'PreOrderPreOrder');
  const [zipCodeData, setZipCodeData] = useState(false);
  const [SelectedOption, setselectedOption] = useState('Booking');
  const [ImageUrl, setImageUrl] = useState('');
  const [addDetails, setAddDetails] = useState(false);
  const [ItemEditdata, setItemEditData] = useState([]);
  console.log(ItemEditdata, 'ItemEditdata');
  const [totalAmount, setTotalAmount] = useState(0);
  const [balanceAmount, setBalaceAmount] = useState(0);
  const CustDetails = SelectedCust ? SelectedCust : GetCustId;

  const [SetAsDefaultCust, setSetAsDefaultCust] = useState(false);
  const [CusName, setCusName] = useState();
  const [MobName, setMobName] = useState();
  const [add1, setAdd1] = useState();
  const [add2, setAdd2] = useState();
  const [zip, setZip] = useState();
  const [Index, setIndex] = useState();
  const [ShowDetails, setShowDetails] = useState(false);
  const [TotalTaxAmount, setTotalTaxAmount] = useState(0);
  const [MessageModel, setMessageModel] = useState();
  const [PendingOrderView, setPendingOrderView] = useState([]);
  const [OldAdvanceAmount, setOldAdvanceAmount] = useState(0);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [ModalProduct, setModalProduct] = useState(false);
  const [PreOrder_Pending_FromDate, setPreOrder_Pending_FromDate] = useState();
  const [PreOrder_Pending_ToDate, setPreOrder_Pending_ToDate] = useState();
  const [PreOrder_History_FromDate, setPreOrder_History_FromDate] = useState();
  const [PreOrder_History_ToDate, setPreOrder_History_ToDate] = useState();
  const [PendingsearchedText, setPendingSearchedText] = useState('');
  const [HistorysearchedText, HistorysetSearchedText] = useState('');
  const [HistoryData, setHistoryData] = useState();
  const [OrderDetail, setOrderDetail] = useState();
  const [Status, setStatus] = useState();
  const [FullPayment, setFullPayment] = useState(false);
  const [selectOptionName, setselectOptionName] = useState();
  const [pendingCustomerView, setPendingCustomerView] = useState({
    Data: null,
    status: false,
  });
  const [CreditCustomer, setCreditCustomer] = useState({
    basic: false,
    model: false,
  });
  const [HistoryDetailsView, setHistoryDetails] = useState({
    Data: null,
    status: false,
  });
  const [Keys, setKeys] = useState();
  const [Buttonicon, setButton] = useState(false);
  const [Payment_Device, setPayment_Device] = useState();
  const [Payment_Gateway, setPayment_Gateway] = useState();
  const [PaymentOptions, setPaymentOptions] = useState();
  const [GateWayOptions, setGetWayOptions] = useState();
  const [selectedGateWayOptions, setSelectedGetWayOptions] = useState();
  const [orderId, setorderId] = useState(null);
  const [failedOrderData, setFailedOrderData] = useState();
  const currentDateValue = moment()?.format('YYYY-MM-DD HH:mm:ss');

  //split Payment
  const [splitPayment, setSplitPayment] = useState(false);
  const [SplitSelPayMode, setSplitSelPayMode] = useState({});

  const [PrintOrderDetails, setPrintOrderDetails] = useState([]);

  const [CancelModal, setCancelModal] = useState(false);
  const [PreOrderData, setPreOrderData] = useState();
  const [PreOrderRefund, setPreOrderRefund] = useState(0);
  const [CancelPaymentOption, setCancelPaymentOption] = useState();
  const gatewayOptions = [
    { option: 'Default', value: 'Default' },
    { option: 'Payment Device', value: 'PaymentDevice' },
    { option: 'Payment Gateway', value: 'PaymentGateway' },
  ];
  //useCallback
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const containerRef = useRef(null);

  const ChangeMouseData = async (data) => {
    await dispatch(changeCompoPreOrderDtlStatus(data));
  };

  useEffect(() => {
    OnchangePreOrderIcon();
    const handleMouseEnter = async () => await ChangeMouseData(true);
    const handleMouseLeave = () => ChangeMouseData(false);

    const divElement = containerRef.current;

    if (divElement) {
      divElement.addEventListener('mouseenter', handleMouseEnter);
      divElement.addEventListener('mouseleave', handleMouseLeave);

      return () => {
        divElement.removeEventListener('mouseenter', handleMouseEnter);
        divElement.removeEventListener('mouseleave', handleMouseLeave);
      };
    }
  }, []);

  useEffect(() => {
    let data = selOption != null ? selOption : GetCustId;
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedData = {
        customer: data,
      };
      customerDisplayWindow.postMessage(updatedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
  }, [selOption, GetCustId]);

  useEffect(() => {
    if (selectedGateWayOptions !== undefined && Buttonicon) {
      const isCard = selectOptionName === 'Card';
      const isUPI =
        selectOptionName === 'UPI' && selectedGateWayOptions != 'Default';

      if (isCard || isUPI) {
        onFinish();
      }
    }
  }, [selectedGateWayOptions]);

  useEffect(() => {
    async function amoutchange() {
      let extra = GlobalExtraCharge?.reduce((accumulator, currentObject) => {
        return accumulator + currentObject.TotalAmt;
      }, 0);

      const Totalamount = ItemEditdata?.reduce((acc, item) => {
        return acc + item.TotalAmt;
      }, 0);
      const totalAmount =
        extra == undefined ? Totalamount : Totalamount + extra;
      if (PreOrderAdvance > totalAmount) {
        await dispatch(changePreOrderAdvance(totalAmount));
      }

      const Balance = totalAmount - PreOrderAdvance - OldAdvanceAmount;

      setTotalAmount(totalAmount);
      setBalaceAmount(Balance);
      await dispatch(
        changeSummeryTotalAmount(
          formRef?.current?.getFieldsValue()?.AdvanceAmount
        )
      );
    }

    amoutchange();
  }, [ItemEditdata]);

  useEffect(() => {
    UsePayments();
  }, [useOptions, CustDetails]);

  useEffect(() => {
    if (PreOrder) {
      if (SetAsDefaultCust) {
        formRef?.current?.setFieldsValue({
          Name: CustDetails?.CustName,
          MobileNo: CustDetails?.value || CustDetails?.CustMobile,
          Address1: CustDetails?.Address1,
          Address2: CustDetails?.Address2,
          Zip: CustDetails?.Zip,
        });
        dispatch(changePreOrderCusName(CustDetails?.CustName));
        dispatch(
          changePreOrderCusMob(CustDetails?.value || CustDetails?.CustMobile)
        );
        dispatch(changePreOrderAdd1(CustDetails?.Address1));
        dispatch(changePreOrderAdd2(CustDetails?.Address2));
        dispatch(changePreOrderzip(CustDetails?.Zip));
        if (CustDetails?.Zip?.toString().length === 6) {
          getPincodeValues(CustDetails?.Zip);
        }
      }
      setFullPayment(false);
    }
  }, [SelectedCust, SelectedOption]);

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

  useEffect(() => {
    // Define an async function
    const handleBookingTypeChange = async () => {
      if (BookingTypeData !== 'PreOrder') {
        setPreOrder(false);
        await dispatch(changepreOrder(false));
      }
    };

    // Call the async function inside useEffect
    handleBookingTypeChange();
  }, [BookingTypeData]);

  useEffect(() => {
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedData = {
        paymentMethod: selectOptionName,
        Paymentgateway: false,
      };
      customerDisplayWindow.postMessage(updatedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
  }, [selectOptionName]);

  useEffect(() => {
    ApiCall();
    if (Edit) setEdit(false);
    if (PreOrder) {
      if (SetAsDefaultCust) {
        formRef?.current?.setFieldsValue({
          Name: CustDetails?.CustName,
          MobileNo: CustDetails?.value || CustDetails?.CustMobile,
          Address1: CustDetails?.Address1,
          Address2: CustDetails?.Address2,
          Zip: CustDetails?.Zip,
        });
        dispatch(changePreOrderCusName(CustDetails?.CustName));
        dispatch(
          changePreOrderCusMob(CustDetails?.value || CustDetails?.CustMobile)
        );
        dispatch(changePreOrderAdd1(CustDetails?.Address1));
        dispatch(changePreOrderAdd2(CustDetails?.Address2));
        dispatch(changePreOrderzip(CustDetails?.Zip));
        if (CustDetails?.Zip?.toString().length === 6) {
          getPincodeValues(CustDetails?.Zip);
        }
      }
      setPreOrder_History_FromDate(null);
      setPreOrder_Pending_ToDate(null);
      setPreOrder_Pending_FromDate(null);
      setPreOrder_History_ToDate(null);
    }
  }, [SelectedOption]);

  useEffect(() => {
    TotalCalculation();
  }, [GlobalExtraCharge]);

  const OnChangeCancelPaymentOption = async (params) => {
    setCancelPaymentOption(params);
    cancelformRef?.current?.setFieldsValue({ CancelPayOptions: params });
  };

  useEffect(() => {
    if (Array.isArray(PreOrderList)) {
      const customerDisplayWindow = getCustomerDisplayWindow();
      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        const updatedData = {
          userData: [...PreOrderList],
        };
        customerDisplayWindow.postMessage(updatedData, '*');
      } else {
        console.error(
          'Customer display window is not available or has been closed.'
        );
      }
      setItemEditData([...PreOrderList]);
      TotalCalculation();
    }
  }, [PreOrderList]);

  useEffect(() => {
    const setFieldsIfNotEmpty = (field, value) => {
      if (value?.length !== 0) {
        formRef?.current?.setFieldsValue({ [field]: value });
      }
    };

    if (SetAsDefaultCust) {
      formRef?.current?.setFieldsValue({
        Name: CustDetails?.CustName,
        MobileNo: CustDetails?.value || CustDetails?.CustMobile,
        Address1: CustDetails?.Address1,
        Address2: CustDetails?.Address2,
        Zip: CustDetails?.Zip,
      });
      if (CustDetails?.Zip?.toString().length === 6) {
        getPincodeValues(CustDetails?.Zip);
      }
    } else {
      formRef?.current?.setFieldsValue({
        Name: CusName,
        MobileNo: MobName,
        Address1: add1,
        Address2: add2,
        Zip: zip,
      });

      if (zip?.toString().length === 6) {
        getPincodeValues(zip);
      }
    }

    let extra = GlobalExtraCharge?.reduce((accumulator, currentObject) => {
      return accumulator + currentObject.TotalAmt;
    }, 0);

    const Amount =
      ItemEditdata?.reduce(
        (accumulator, currentItem) =>
          accumulator + (currentItem?.TotalAmt || 0),
        0
      ) || 0;
    const TotalAmount = extra == undefined ? Amount : Amount + extra;

    const Balance = TotalAmount - PreOrderAdvance - OldAdvanceAmount;

    setTotalAmount(TotalAmount);
    setBalaceAmount(Balance);

    setFieldsIfNotEmpty('AdvanceAmount', PreOrderAdvance);
    setFieldsIfNotEmpty('Message', PreOrderMessage);
    setFullPayment(false);
  }, [PreOrderAdditem]);
  useEffect(() => {
    const first = async () => {
      if (Edit && PreOrderAdditem == 'AddDetails') {
        await formRef?.current?.setFieldsValue({
          MobileNo: Keys?.MobileNo,
        });
        await formRef?.current?.setFieldsValue({
          Name: Keys?.Name,
        });

        await setMobName(Keys?.MobileNo);
        await setCusName(Keys?.Name);
        await dispatch(changePreOrderCusName(Keys?.Name));
        await dispatch(changePreOrderCusMob(Keys?.MobileNo));
        await getPincodeValues(Keys?.CustomerDetails[0]?.ZipCode);
        await dispatch(changePreOrderzip(Keys?.CustomerDetails[0]?.ZipCode));

        if (Keys?.OrderPaymentDtls?.[0]?.PaymentTypeName === 'UPI') {
          await setselectedUPIOption();
          await formRef?.current?.setFieldsValue({
            UPIOptions: Keys?.OrderPaymentDtls?.[0]?.PaymentType,
          });
        }
      }
    };

    first();
  }, [Edit]);

  useEffect(() => {
    splitRef?.current?.setFieldsValue(SplitSelPayMode);
  }, [splitPayment]);

  useEffect(() => {
    if (PrintOrderDetails?.length > 0) {
      if (isMobile) {
        MobilePrint(PrintOrderDetails, UpiId, 'Booking', preferenceData);
      } else {
        Print();
      }
    } //changeby karthiga
  }, [PrintOrderDetails]);
  const fetchingsalesData = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      UserId: UserId,
      FromDate: currentDateValue,
      ToDate: currentDateValue,
    };
    await dispatch(getSalesDetailData(data));
  };
  const UsePayments = () => {
    if (useOptions?.length > 0) {
      let AllPaymentOptions = useOptions?.find(
        (item) => item.FlowName === 'Sales'
      );

      let PaymentDevice = AllPaymentOptions?.OptionDetails.find(
        (item) => item.OptionName === 'Payment Device'
      );
      let PaymentGateway = AllPaymentOptions?.OptionDetails.find(
        (item) => item.OptionName === 'Payment Gateway'
      );
      setPayment_Device(PaymentDevice);
      setPayment_Gateway(PaymentGateway);
      let object;
      if (CustDetails === undefined) {
        object = AllPaymentOptions?.OptionDetails?.find(
          (item) => item.OptionName === 'Pay at the counter'
        )?.ModeDetails?.filter((item) => item.ModeName !== 'Credit');
      } else {
        object = AllPaymentOptions?.OptionDetails?.find(
          (item) => item.OptionName === 'Pay at the counter'
        )?.ModeDetails;
      }

      setPaymentOptions(object);
      setselectedPaymentOption(
        object?.find((mode) => mode.ModeName == 'Cash')?.ModeId
      );
      setselectOptionName('Cash');
    }
  };
  const cardandUpi = async (e) => {
    if (Buttonicon) {
      setStatus('Edit');
    }
    setSelectedGetWayOptions(e);
    formRef?.current?.setFieldsValue({ GateWayOptions: e });
    formRef?.current?.resetFields(['UPIOptions']);
    setselectedUPIOption();
  };
  const Hcolumns = [
    {
      title: <div style={{ fontSize: '10px' }}>SI</div>,
      dataIndex: 'OrderId',
      key: 'OrderId',
      align: 'center',
      fixed: 'left',
      render: (text, object, index) => (
        <a style={{ color: 'black', fontSize: '10px' }}>{index + 1}</a>
      ),
    },
    {
      title: <div style={{ fontSize: '10px' }}>O.ID</div>,
      dataIndex: 'OrderId',
      key: 'OrderId',
      align: 'center',
      fixed: 'left',
      filteredValue: [HistorysearchedText],
      render: (text, record, index) => (
        <a style={{ color: 'black', fontSize: '10px' }}>
          {record.FYStatus === 'Y'
            ? extractThreeDigitNumber(text)
            : extractLastNumber(text)}
        </a>
      ),
      onFilter: (value, record) => {
        return (
          String(record.OrderId)
            ?.toLowerCase()
            .includes(value?.toLowerCase()) ||
          String(record?.CustomerDetails?.[0]?.CustSuppName)
            ?.toLowerCase()
            .includes(value?.toLowerCase()) ||
          String(record?.CustomerDetails?.[0]?.MobileNo)
            ?.toLowerCase()
            .includes(value?.toLowerCase()) ||
          String(formatDate(record?.DeliveryDate, record.DeliveryTime))
            ?.toLowerCase()
            .includes(value?.toLowerCase()) ||
          String(record.PaidAmount)
            ?.toLowerCase()
            .includes(value?.toLowerCase())
        );
      },
      ellipsis: true,
    },
    {
      title: (
        <div style={{ fontSize: '10px', textWrap: 'nowrap' }}>DATE/TIME</div>
      ),
      dataIndex: 'OrderId',
      key: 'OrderId',
      align: 'center',
      render: (_, record) => (
        <a style={{ color: 'black', fontSize: '10px' }}>
          {formatDate(record?.DeliveryDate, record.DeliveryTime)}
        </a>
      ),
    },
    {
      title: <div style={{ fontSize: '10px', textWrap: 'nowrap' }}>Name</div>,
      dataIndex: 'OrderId',
      key: 'OrderId',

      render: (_, record) => (
        <a style={{ color: 'black', fontSize: '10px' }}>
          {record?.CustomerDetails?.[0]?.CustSuppName || '-'}
        </a>
      ),
    },
    {
      title: <div style={{ fontSize: '10px', textWrap: 'nowrap' }}>Mobile</div>,
      dataIndex: 'OrderId',
      key: 'OrderId',
      align: 'right',
      render: (_, record) => (
        <a style={{ color: 'black', fontSize: '10px' }}>
          {record?.CustomerDetails?.[0]?.MobileNo || '-'}
        </a>
      ),
    },

    {
      title: <div style={{ fontSize: '10px', textWrap: 'nowrap' }}>Amount</div>,
      dataIndex: 'PaidAmount',
      key: 'PaidAmount',
      align: 'right',
      render: (text, object, index) => (
        <a style={{ color: 'black', fontSize: '10px' }}>{text}</a>
      ),
    },
    {
      title: <div style={{ fontSize: '10px' }}>Details</div>,
      dataIndex: 'OrderId',
      align: 'center',
      render: (_, record) => (
        <IoEye
          style={{ fontSize: '18px', color: '#000' }}
          onClick={() => setHistoryDetails({ Data: record, status: true })}
        />
      ),
    },
  ];

  const extractThreeDigitNumber = (str) => {
    const match = str.match(/(\d{3})-/);
    return match ? match[1] : null;
  };

  const handlerefundvalidator = (_, value) => {
    const paidAmount = parseFloat(PreOrderData?.PaidAmount ?? 0);
    const refundAmount = parseFloat(value ?? 0);

    if (refundAmount > paidAmount) {
      return Promise.reject('Refund amount cannot exceed advance paid');
    }
    return Promise.resolve();
  };

  const OnchangeRefund = async (e) => {
    setPreOrderRefund(e?.target?.value);
  };
  const TotalCalculation = async () => {
    let totalSum;
    let totaltax;

    totalSum = PreOrderList?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.TotalAmt || 0);
    }, 0);

    totaltax = PreOrderList?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.TaxAmt || 0);
    }, 0);

    let Totalamount = totaltax ? totalSum + totaltax : totalSum;

    let extra = GlobalExtraCharge?.reduce((accumulator, currentObject) => {
      return accumulator + currentObject.TotalAmt;
    }, 0);
    let AdvAmount =
      PreOrderAdvance != null
        ? parseInt(PreOrderAdvance)
        : 0 + parseInt(OldAdvanceAmount);
    let Total = extra == undefined ? Totalamount : Totalamount + extra;
    let balance = Total - AdvAmount;
    setBalaceAmount(balance);
    setTotalAmount(Total?.toFixed(2));
    setTotalTaxAmount(totaltax?.toFixed(2));
  };

  const OnOkView = () => {
    setShowDetails(false);
  };

  const OnCancelView = () => {
    setShowDetails(false);
  };

  const ApiCall = async () => {
    const today = new Date();
    const fromDate = today.toISOString().split('T')[0];
    if (SelectedOption == 'Pending') {
      PendingApiCall(fromDate, fromDate);
    } else if (SelectedOption == 'History') {
      HistoryApiCall(fromDate, fromDate);
    }
  };

  const FetchData = async () => {
    const today = new Date();
    const fromDate = today.toISOString().split('T')[0];
    BadgePendingApi();
    PendingApiCall();
    HistoryApiCall(fromDate, fromDate);
    let Response = await dispatch(
      getConfigType({ TypeName: 'Booking Type' })
    ).unwrap();
    if (Response?.data?.statusCode === 1) {
      setBookingType(
        Response?.data?.data?.find((item) => item?.ConfigName === 'TakeAway')
          ?.ConfigId
      );
    }
  };

  const BadgePendingApi = async () => {
    let Data = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      deliveryStatus: 'P',
    };
    let PendingResponse = await dispatch(PreOrderGet(Data)).unwrap();
    if (PendingResponse?.data?.statusCode === 1) {
      await dispatch(
        changePreOrderPendingCount(PendingResponse?.data?.data?.length)
      );
    }
  };
  const Print = async () => {
    const style = await PrintStyleFunction(
      printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle,
      'Sales'
    );
    const stylesMap = {
      'Style 1': 'PrintStyle1',
      'Style 2': 'PrintStyle2',
      'Style 3': 'PrintStyle3',
      'Style 4': 'PrintStyle4',
      'Style 5': 'PrintStyle5',
      'Style 6': 'PrintStyle6',
      'Style 7': 'PrintStyle7',
      'Style 8': 'PrintStyle8',
      'Style 9': 'PrintStyle9',
      'Style 10': 'PrintStyle10',
      'Style 11': 'PrintStyle11',
      'Style 12': 'PrintStyle12',
      'Style 13': 'RePrint',
    };

    const selectedStyle =
      stylesMap[
        printerTemplateStyle == undefined ? 'Style 13' : printerTemplateStyle
      ];

    if (selectedStyle) {
      await Promise.all(
        PrintOrderDetails?.[0]?.OrderDetails?.map(
          async (orderDetail, index) => {
            await printDiv(`${selectedStyle}-${index}`, style); // Use unique IDs for each print
          }
        )
      );
      setPrintOrderDetails([]);
    }
    fetchingsalesData();
  };

  const OnChangePaymentOption = async (params) => {
    formRef?.current?.resetFields(['GateWayOptions']);
    setSelectedGetWayOptions();
    formRef?.current?.resetFields(['UPIOptions']);
    setselectedUPIOption();
    let data = PaymentOptions?.filter((e) => e?.ModeId == params)?.[0]
      ?.ModeName;
    setCreditCustomer(
      data == 'Credit'
        ? { basic: true, model: false }
        : { basic: false, model: false }
    );
    setqrcode(data == 'UPI' ? true : false);
    setselectedPaymentOption(params);
    setselectOptionName(data);
    formRef?.current?.setFieldsValue({ PaymentOptions: params });
    let OptionData;
    let Device = Payment_Device?.ModeDetails?.some(
      (item) => item.ModeName === data
    );
    let Gateway;

    if (data === 'Card') {
      Gateway = Payment_Gateway?.ModeDetails?.some(
        (item) =>
          item.ModeName === 'CreditCard' || item.ModeName === 'DebitCard'
      );
    } else {
      Gateway = Payment_Gateway?.ModeDetails?.some(
        (item) => item.ModeName === data
      );
    }

    if (Device === false && Gateway === false) {
      OptionData = gatewayOptions.filter(
        (item) =>
          item.value !== 'PaymentDevice' && item.value !== 'PaymentGateway'
      );
    } else if (Device === false) {
      OptionData = gatewayOptions.filter(
        (item) => item.value !== 'PaymentDevice'
      );
    } else if (Gateway === false) {
      OptionData = gatewayOptions.filter(
        (item) => item.value !== 'PaymentGateway'
      );
    } else {
      OptionData = gatewayOptions;
    }

    if (data === 'Card') {
      OptionData = OptionData?.filter((item) => item.value !== 'Default');
    }

    if (!useOptions?.[0]?.PaymentDetails?.Payatthecounter?.length > 0) {
      OptionData = OptionData?.filter((item) => item.value !== 'Default');
    }
    setGetWayOptions(OptionData);
  };

  const OnChangeUPIOption = async (params) => {
    setselectedUPIOption(params);
    setUpiId(PaymentUpiOptions?.filter((e) => e?.Mode == params)?.[0]?.UPIId);
    formRef?.current?.setFieldsValue({ UPIOptions: params });
  };

  const Pending_onSearch = (value) => {
    setPendingSearchedText(value);
  };

  const Pending_onSearchChange = (e) => {
    setPendingSearchedText(e?.target?.value);
  };

  const PendingApiCall = async (Fromdate, Todate) => {
    let Data = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      deliveryStatus: 'P',
      fromDate: Fromdate,
      toDate: Todate,
    };
    let PendingResponse = await dispatch(PreOrderGet(Data)).unwrap();
    if (PendingResponse?.data?.statusCode === 1) {
      setPendingData(PendingResponse?.data?.data);
    } else if (PendingResponse?.data?.statusCode === 0) {
      setPendingData();
    }
  };

  const HistoryApiCall = async (Fromdate, Todate) => {
    let Data = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      deliveryStatus: 'D',
      fromDate: Fromdate,
      toDate: Todate,
    };
    let HistoryResponse = await dispatch(PreOrderGet(Data)).unwrap();
    if (HistoryResponse?.data?.statusCode === 1) {
      setHistoryData(HistoryResponse?.data?.data);
    } else if (HistoryResponse?.data?.statusCode === 0) {
      setHistoryData();
    }
  };

  const OnchangeAdvance = async (e) => {
    await dispatch(changePreOrderAdvance(e?.target?.value));
    let extra = GlobalExtraCharge?.reduce((accumulator, currentObject) => {
      return accumulator + currentObject.TotalAmt;
    }, 0);

    const Total =
      PreOrderList?.reduce(
        (accumulator, currentItem) =>
          accumulator + (currentItem?.TotalAmt || 0),
        0
      ) || 0;
    let TotalAmount = extra == undefined ? Total : Total + extra;

    setTotalAmount(TotalAmount);
    setBalaceAmount(
      TotalAmount -
        formRef?.current?.getFieldsValue()?.AdvanceAmount -
        OldAdvanceAmount
    );
    await dispatch(
      changeSummeryTotalAmount(
        formRef?.current?.getFieldsValue()?.AdvanceAmount
      )
    );
  };

  const updateImageUrl = async (url) => {
    setImageUrl(url);

    let data = [...ItemEditdata];

    // Create a shallow copy of the object at the specified index
    let updatedObject = { ...data[Index], Image: url };

    // Update the array with the modified object
    data[Index] = updatedObject;
    setItemEditData(data);

    // Dispatch the updated array
    // await dispatch(changepreOrderList(data));
  };

  const NameOnChange = (e) => {
    setCusName(e?.target?.value);
    dispatch(changePreOrderCusName(e?.target?.value));
    formRef?.current?.setFieldsValue({ Name: e?.target?.value });
  };

  const MobOnChange = (e) => {
    setMobName(e?.target?.value);
    dispatch(changePreOrderCusMob(e?.target?.value));
    formRef?.current?.setFieldsValue({ MobileNo: e?.target?.value });
  };

  const onChangeTime = async (_, timeString) => {
    if (timeString) {
      formRef.current?.setFieldsValue({});
      const fromTime = moment(timeString, ['h:mm a']).format('HH:mm:ss');
      await dispatch(changePreOrderTime(fromTime));
    } else {
      await dispatch(changePreOrderTime(null));
    }
  };

  const onChangeDate = async (_, dateString) => {
    dispatch(changeDropDownStatus(false));
    if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      await dispatch(changePreOrderDate(Date1));
    }
  };

  const OnChangeMessage = async (e) => {
    setMessageModel(e?.target?.value);
    ViewformRef.current?.setFieldsValue({ Message: e?.target?.value });

    let data = [...ItemEditdata];

    // Create a shallow copy of the object at the specified index
    let updatedObject = { ...data[Index], Description: e?.target?.value };

    // Update the array with the modified object
    data[Index] = updatedObject;

    // Dispatch the updated array
    setItemEditData(data);
  };

  const OnChangeAddress1 = async (e) => {
    setAdd1(e?.target?.value);
    await dispatch(changePreOrderAdd1(e?.target?.value));
  };

  const OnChangeAddress2 = async (e) => {
    setAdd2(e?.target?.value);
    await dispatch(changePreOrderAdd2(e?.target?.value));
  };

  const pinCodeChange = async (e) => {
    setZip(e?.target?.value);
    if (e.target.value.length < 6) {
      setZipCodeData(false);
      return false;
    }
    await getPincodeValues(e?.target?.value);
    await dispatch(changePreOrderzip(e?.target?.value));
  };

  const getPincodeValues = async (pinCode) => {
    let response = '';
    await fetch(`https://api.postalpincode.in/pincode/${pinCode}`)
      .then((res) => res.text())
      .then((text) => (response = JSON.parse(text)));

    if (response[0]['Status'] === 'Success') {
      setZipCodeData(true);
      formRef.current?.setFieldsValue({
        City: response[0]['PostOffice'][0]['Block'],
        Dist: response[0]['PostOffice'][0]['District'],
        State: response[0]['PostOffice'][0]['State'],
      });
      await dispatch(changePreOrderCity(response[0]['PostOffice'][0]['Block']));
      await dispatch(
        changePreOrderDistrict(response[0]['PostOffice'][0]['District'])
      );
      await dispatch(
        changePreOrderState(response[0]['PostOffice'][0]['State'])
      );
    } else {
      setZipCodeData(false);
    }
  };
  const UpiPayment = () => {
    if (
      selectedUPIOption &&
      selectedGateWayOptions == 'Default' &&
      !CreditCustomer?.basic
    ) {
      setUpiOpen(true);
      const customerDisplayWindow = getCustomerDisplayWindow();
      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        const updatedData = {
          OrderTotalAmount: PreOrderAdvance,
          paymentMethod: 'UPI',
          upi: UpiId,
        };
        customerDisplayWindow.postMessage(updatedData, '*');
      } else {
        console.error(
          'Customer display window is not available or has been closed.'
        );
      }
    } else if (CreditCustomer?.basic) {
      setCreditCustomer({ basic: true, model: true });
      const customerDisplayWindow = getCustomerDisplayWindow();
      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        const updatedData = {
          OrderTotalAmount: PreOrderAdvance,
        };
        customerDisplayWindow.postMessage(updatedData, '*');
      } else {
        console.error(
          'Customer display window is not available or has been closed.'
        );
      }
    } else {
      setMessageType('error');
      setMessageData('Please Select Upi Option');
    }
  };
  const removestates = () => {
    const updatedData = {
      userData: [...PreOrderList],
      ExtraCharges: GlobalExtraCharge,
      customer: selOption != null ? selOption : GetCustId,
      Paymentgateway: false,
    };
    setFailedOrderData(updatedData);
    setSplitPayment(true);
    setSelectedGetWayOptions();
    setselectedPaymentOption();
  };
  const handlesplitpaymentclose = () => {
    setSplitPayment(false);
  };
  const AddBookingDetails = async (values, Status1) => {
    const FormValues = formRef?.current?.getFieldsValue();
    const DeliveryDate = dayjs(FormValues?.DeliveryDate).format('DD-MM-YYYY');

    let data = ItemEditdata.map((item) => ({
      OfferValue: item?.OfferValue,
      OfferAmt: item?.TotalOfferPrice || item?.OfferAmt,
      OfferType: item?.OfferType,
      ProdId: item.ProdId,
      Type: item.Type,
      OrderQty: item.OrderQty || item.SalesQty,
      OrderRate: item.OrderRate || item.Rate,
      TotalAmt: item.TotalAmt,
      TaxAmt: item.TaxAmt,
      RefundQty: 0,
      InwardDtlId: item.InwardDtlId,
      TaxId: item.TaxId,
      ProdNameQty: item.ProdName
        ? `${item.ProdName} ${item.Type != 'C' ? item.Size : '1'} ${item.Type != 'C' ? item.UomName : 'Combo'}`
        : '',
      OrderStatus: 'S',
      OrderType: 'PRE',
      SinglePc: item.SinglePc,
      BookingType: BookingType, // Assuming 1 if BookingTypeName exists, otherwise 0
      PaymentStatus: 'N',
      Image: item.Image,
      Description: item.Description,
    }));
    let stocklimitExceeded = false;

    const NewOrderDetailDelivery = [];

    if (Status == 'Delivery' || Status1 == 'Delivery') {
      ItemEditdata.forEach((item) => {
        const StockDetail = item?.StockDetail;
        const FoundInwardDtlIdData = StockDetail?.find(
          (detail) => detail.InwardDtlId === item?.InwardDtlId
        );

        let OrderDtl = {
          OfferValue: item?.OfferValue,
          OfferAmt: item?.TotalOfferPrice || item?.OfferAmt,
          OfferType: item?.OfferType,
          ProdId: item.ProdId,
          Type: item.Type,
          OrderQty: item.OrderQty || item.SalesQty,
          TotalAmt: item.TotalAmt,
          TaxAmt: item.TaxAmt,
          RefundQty: 0,
          InwardDtlId: item.inwardDtlId,
          TaxId: item.TaxId,
          ProdNameQty: item.ProdName
            ? `${item.ProdName} ${item.Type != 'C' ? item.Size : '1'} ${item.Type != 'C' ? item.UomName : 'Combo'}`
            : '',
          OrderStatus: 'S',
          OrderType: 'PRE',
          SinglePc: item.SinglePc,
          BookingType: BookingType,
          PaymentStatus: 'N',
          Image: item.Image,
          Description: item.Description,
        };

        if (item.StockAvailable === 'N') {
          OrderDtl.InwardDtlId = item?.InwardDtlId;
          OrderDtl.OrderRate = preferCondition
            ? StockDetail?.[0]?.SellPrice
            : item.OrderQty || item.SalesQty;
          NewOrderDetailDelivery.push(OrderDtl);
        } else if (item.StockAvailable === 'Y' && StockDetail?.length > 0) {
          if (
            FoundInwardDtlIdData?.BalanceQty >= (item.OrderQty || item.SalesQty)
          ) {
            OrderDtl.OrderRate = preferCondition
              ? FoundInwardDtlIdData.SellPrice
              : OrderDtl.OrderRate;
            OrderDtl.InwardDtlId = FoundInwardDtlIdData.InwardDtlId;
            NewOrderDetailDelivery.push(OrderDtl);
          } else {
            const totalAvailableQty = StockDetail.reduce(
              (total, detail) => total + (detail?.BalanceQty || 0),
              0
            );
            if (totalAvailableQty < Number(item.OrderQty || item.SalesQty)) {
              setMessageData(
                `${item?.ProdName + ' ' + item?.Size + ' ' + item?.UomName} Dont have Enough Stock`
              );
              setMessageType('warning');
              stocklimitExceeded = true;
            } else {
              let accumulatedQty = 0;
              const targetIndex = StockDetail.findIndex(
                (detail) => detail.InwardDtlId === item?.InwardDtlId
              );

              const accumulateQty = (startIndex) => {
                for (
                  let i = startIndex;
                  i < StockDetail.length &&
                  accumulatedQty < Number(item.OrderQty || item.SalesQty);
                  i++
                ) {
                  const stockDetail = StockDetail[i];
                  if (stockDetail?.BalanceQty > 0) {
                    const qtyToAdd = Math.min(
                      stockDetail.BalanceQty,
                      Number(item.OrderQty || item.SalesQty) - accumulatedQty
                    );

                    NewOrderDetailDelivery.push({
                      // ...stockDetail,
                      InwardDtlId: stockDetail?.InwardDtlId,
                      OrderRate: preferCondition
                        ? stockDetail?.SellPrice
                        : item.Rate,
                      OrderQty: qtyToAdd,
                      ProdId: item.ProdId,
                      Type: item.Type,
                      TotalAmt: item.TotalAmt,
                      TaxAmt: item.TaxAmt,
                      RefundQty: 0,
                      TaxId: item.TaxId,
                      ProdNameQty: item.ProdName
                        ? `${item.ProdName} ${item.Size} ${item.UomName}`
                        : '',
                      OrderStatus: 'S',
                      OrderType: 'PRE',
                      SinglePc: item.SinglePc,
                      BookingType: BookingType,
                      PaymentStatus: 'N',
                      Image: item.Image,
                      Description: item.Description,
                    });
                    accumulatedQty += qtyToAdd;
                  }
                }
              };

              if (targetIndex !== -1) accumulateQty(targetIndex);
              if (accumulatedQty < item.OrderQty || item.SalesQty)
                accumulateQty(0);
            }
          }
        } else {
          alert('fill the Product ');
        }
      });
    }
    function changeDateFormat(dateStr) {
      let dateParts = dateStr.split('-');
      return `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`;
    }

    const ModeName = PaymentOptions?.find(
      (item) => item.ModeId === selectedPaymentOption
    )?.ModeName;
    let PaymentType;
    let PaymentOptionType;
    if (ModeName === 'Card') {
      if (selectedGateWayOptions === 'PaymentDevice') {
        PaymentType = Payment_Device?.ModeDetails.find(
          (item) => item.ModeName === 'Card'
        )?.ModeId;
        PaymentOptionType = 'PD';
      } else if (selectedGateWayOptions === 'PaymentGateway') {
        PaymentType = selectedPaymentOption;
        PaymentOptionType = 'PG';
      }
    } else if (ModeName === 'UPI') {
      if (selectedGateWayOptions === 'Default') {
        PaymentType = selectedPaymentOption;
        PaymentOptionType = 'PC';
      } else if (selectedGateWayOptions === 'PaymentDevice') {
        PaymentType = Payment_Device?.ModeDetails.find(
          (item) => item.ModeName === 'UPI'
        )?.ModeId;
        PaymentOptionType = 'PD';
      } else if (selectedGateWayOptions === 'PaymentGateway') {
        PaymentType = Payment_Gateway?.ModeDetails.find(
          (item) => item.ModeName === 'UPI'
        )?.ModeId;
        PaymentOptionType = 'PG';
      }
    } else {
      PaymentType = selectedPaymentOption;
      PaymentOptionType = 'PC';
    }
    const commonOrderDetails = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      BookingType: BookingType,
      ServiceProvider: 0,
      ActiveStatus: 'A',
      RefundAmount: 0,
      AddInfo: 'test',
      BillAmount: FullPayment ? 0 : totalAmount - TotalTaxAmount,
      OverallDisc: 0,
      TaxAmount: FullPayment ? 0 : TotalTaxAmount,
      VatAmount: 0,
      NetAmount: FullPayment ? 0 : totalAmount,
      PaymentType: selectedPaymentOption || null,
      GivenAmt: 0,
      BalGiven: 0,
      BookingMedia: 'DW',
      ExtraChargeDetails: GlobalExtraCharge,
      Type: 'P',
      Debit: 0,
      Credit: PreOrderAdvance,
      DeliveryDate: changeDateFormat(DeliveryDate),
      DeliveryTime: PreOrderTime,
      Address1: FormValues?.Address1,
      Address2: FormValues?.Address2,
      City: FormValues?.City,
      Dist: FormValues?.Dist,
      State: FormValues?.State,
      Zip: FormValues?.Zip,
      AdvanceAmount: FullPayment ? 0 : FormValues?.AdvanceAmount,
      MobileNo: PreOrderCusMobNo,
      Name: PreOrderCusName,
      DefaultStatus: SetAsDefaultCust ? 'Y' : 'N',
      SalesPaymentType: 'normal',
      PaymentStatus: 'P',
      PaymentDetail: FullPayment
        ? []
        : !splitPayment
          ? [
              {
                PaymentType: PaymentType || null,
                Amount: FormValues?.AdvanceAmount,
                PaymentOptionType: PaymentOptionType || null,
                ModeOfPayment:
                  selectedGateWayOptions === 'Default'
                    ? useOptions?.[0]?.PaymentDetails?.Payatthecounter?.find(
                        (upipay) => upipay?.UPIId === UpiId
                      )?.UPIDetailId
                    : null,
                AccountDtl:
                  ModeName === 'UPI' && selectedGateWayOptions === 'Default'
                    ? useOptions?.[0]?.PaymentDetails?.Payatthecounter?.find(
                        (upipay) => upipay?.UPIId === UpiId
                      )
                    : (ModeName === 'UPI' && PaymentOptionType === 'PD') ||
                        (ModeName === 'Card' && PaymentOptionType === 'PD')
                      ? useOptions?.[0]?.PaymentDetails?.PaymentDevice
                      : (ModeName === 'UPI' && PaymentOptionType === 'PG') ||
                          (ModeName === 'Card' && PaymentOptionType === 'PG')
                        ? useOptions?.[0]?.PaymentDetails?.PaymentGateway
                        : [],
                PaymentStatus:
                  ModeName?.toLowerCase() === 'card' ||
                  (ModeName?.toLowerCase() === 'upi' &&
                    selectedGateWayOptions != 'Default')
                    ? 'P'
                    : 'S',
                Debit: 0,
                Credit:
                  ModeName?.toLowerCase() === 'credit'
                    ? FormValues?.AdvanceAmount
                    : 0,
              },
            ]
          : values,
    };

    if (Buttonicon) {
      if (
        Status == 'Delivery' ||
        (Status1 == 'Delivery' && !stocklimitExceeded)
      ) {
        const Put = {
          ...commonOrderDetails,
          OrderId: OrderDetail?.OrderId,
          OrderType: OrderDetail?.OrderType,
          UpdatedBy: UserId,
          CustSuppId: CustDetails?.CustId,
          Reference: 'test',
          OrderDtlDetails: data,
          NewOrderDtlDetails: NewOrderDetailDelivery,
          OrderStatus: 'S',
          DeliveryStatus: 'D',
          PaymentStatus:
            (ModeName?.toLowerCase() === 'card' ||
              ModeName?.toLowerCase() === 'upi') &&
            selectedGateWayOptions !== 'Default'
              ? 'P'
              : 'S',
        };

        let Response = await dispatch(PreOrderBookingDataPut(Put)).unwrap();
        if (Response?.data?.statusCode === 1) {
          // if (!FullPayment) {
          let fullpayment;
          let data = Response?.data?.PaymentOrderDtl?.filter(
            (e) => e?.PaymentStatus == 'S'
          )?.reduce((total, item) => {
            return total + item.Amount;
          }, 0);
          if (Response?.data?.OrderDetails?.[0]?.NetAmount === data) {
            fullpayment = true;
          } else {
            fullpayment = false;
          }
          if (!fullpayment) {
            if (
              (ModeName === 'Card' || ModeName === 'UPI') &&
              selectedGateWayOptions !== 'Default'
            ) {
              await PaymentDiviceFlow(
                Response?.data,
                selectedGateWayOptions,
                ModeName,
                PreOrderCusMobNo,
                'Delivery'
              );
            }
            if (
              ModeName == 'Cash' ||
              ModeName == 'Credit' ||
              selectedGateWayOptions == 'Default'
            ) {
              successFunction(Response);
            }
          } else {
            successFunction(Response);
            setFullPayment(false);
          }
        } else {
          setMessageType('error');
          setMessageData(Response?.data?.response);
        }
      }
      if (Status == 'Edit' || Status1 == 'Edit') {
        const Put = {
          ...commonOrderDetails,
          OrderId: OrderDetail?.OrderId,
          OrderType: OrderDetail?.OrderType,
          UpdatedBy: UserId,
          CustSuppId: CustDetails?.CustId,
          Reference: 'test',
          OrderDtlDetails: data,
          NewOrderDtlDetails: NewOrderDetailDelivery,
          OrderStatus: 'P',
          DeliveryStatus: 'P',
          PaymentStatus:
            ModeName?.toLowerCase() === 'card' ||
            ModeName?.toLowerCase() === 'upi'
              ? 'P'
              : 'P',
        };

        let Response = await dispatch(PreOrderBookingDataPut(Put)).unwrap();
        if (Response?.data?.statusCode === 1) {
          if (splitPayment) {
            return Response;
          } else {
            if (!FullPayment) {
              if (
                (ModeName === 'Card' || ModeName === 'UPI') &&
                selectedGateWayOptions !== 'Default'
              ) {
                await PaymentDiviceFlow(
                  Response?.data,
                  selectedGateWayOptions,
                  ModeName,
                  PreOrderCusMobNo
                );
              }
              if (
                ModeName == 'Cash' ||
                ModeName == 'Credit' ||
                selectedGateWayOptions == 'Default'
              ) {
                successFunction();
              }
            } else {
              successFunction();
              setFullPayment(false);
            }
          }
        } else {
          setMessageType('error');
          setMessageData(Response?.data?.response);
        }
      }

      // Handle response...
    } else {
      const POST = {
        ...commonOrderDetails,
        CreatedBy: UserId,
        OrderType: 'PRE',
        CustSuppId: CustDetails?.CustId,
        Reference: 'test',
        OrderDtlDetails: PreOrderList?.map((item) => ({
          OfferValue: item?.OfferValue,
          OfferAmt: item?.TotalOfferPrice || item?.OfferAmt,
          OfferType: item?.OfferType,
          ProdId: item.ProdId,
          Type: item.Type,
          OrderQty: item.OrderQty,
          OrderRate: item.OrderRate,
          TotalAmt: item.TotalAmt,
          TaxAmt: item.TaxAmt,
          RefundQty: 0,
          InwardDtlId: item.InwardDtlId,
          TaxId: item.TaxId,
          ProdNameQty: item.ProdName
            ? `${item.ProdName} ${item.Type != 'C' ? item.Size : '1'} ${item.Type != 'C' ? item.UomName : 'Combo'}`
            : '',
          OrderStatus: 'S',
          OrderType: 'PRE',
          SinglePc: item.SinglePc,
          BookingType: BookingType,
          Image: item.Image,
          Description: item.Description,
        })),
        OrderStatus: 'O',
        DeliveryStatus: 'P',
      };

      let Response = await dispatch(PreOrderBookingData(POST)).unwrap();
      if (Response?.data?.statusCode === 1) {
        if (splitPayment) {
          return Response;
        } else {
          if (
            (ModeName === 'Card' || ModeName === 'UPI') &&
            selectedGateWayOptions !== 'Default'
          ) {
            await PaymentDiviceFlow(
              Response?.data,
              selectedGateWayOptions,
              ModeName,
              PreOrderCusMobNo
            );
          }

          if (
            ModeName == 'Cash' ||
            ModeName == 'Credit' ||
            selectedGateWayOptions == 'Default'
          ) {
            successFunction();
          }
        }
      } else {
        setMessageType('error');
        setMessageData(Response?.data?.response);
      }
    }
  };

  const successFunction = async (Response) => {
    setMessageType('success');
    setMessageData('Order Added Sccessfully');
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      let updatedRemovedData;
      if (PreOrderAdvance == 0) {
        updatedRemovedData = {
          userData: [],
          ExtraCharges: [],
          Paymentgateway: false,
          paymentMethod: 'Cash',
          type: 'remove',
          keyValue: 'customer',
        };
      } else {
        updatedRemovedData = {
          userData: [],
          ExtraCharges: [],
          Paymentgateway: false,
          paymentMethod: 'Cash',
          upioption1: 'okk',
          type: 'remove',
          keyValue: 'customer',
        };
      }
      customerDisplayWindow.postMessage(updatedRemovedData, '*');
      const updatedRemovedDataNew = {
        type: 'remove',
        keyValue: 'OrderTotalAmount',
      };
      customerDisplayWindow.postMessage(updatedRemovedDataNew, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
    setOldAdvanceAmount(0);
    setBalaceAmount(0);
    setButton(false);
    setStatus();
    await formRef?.current?.resetFields();
    await dispatch(changepreOrderList(null));
    await dispatch(changepreOrder(true));
    await dispatch(changePreOrderCusName(null));
    await dispatch(changePreOrderCusMob(null));
    await dispatch(changePreOrderAdd1(null));
    await dispatch(changePreOrderAdd2(null));
    await dispatch(changePreOrderAdvance(null));
    await dispatch(changePreOrderzip(null));
    await dispatch(changePreOrderCity(null));
    await dispatch(changePreOrderDistrict(null));
    await dispatch(changePreOrderState(null));
    await dispatch(changePreOrderAdditem('AddDetails'));
    await dispatch(changeCustomerID(null));
    await dispatch(changeSelectedCustId(null));
    await dispatch(changeSelectedOption(null));

    setItemEditData([]);
    setselectedOption('Booking');
    setZipCodeData(false);
    setSetAsDefaultCust(false);
    setCusName();
    setMobName();
    setTotalAmount();
    setBalaceAmount();
    setAdd1();
    setAdd2();
    setZip();
    Response ? setPrintOrderDetails([Response?.data]) : '';

    setImageUrl('');
    cancelEdit();
    BadgePendingApi();
    PendingApiCall();
    const today = new Date();
    const fromDate = today.toISOString().split('T')[0];
    HistoryApiCall(fromDate, fromDate);
    await dispatch(ChangeTotalAmount([]));
    setGetWayOptions();
    setSelectedGetWayOptions();
    setselectedUPIOption();
    setselectedPaymentOption();
    fetchingsalesData();

    ///
  };
  const PaymentDiviceFlow = async (params, type, ModeName, MobNo) => {
    await dispatch(changePaymentloader(true));
    let Paymentdevicefilter = params?.PaymentOrderDtl?.filter(
      (item) => item.PaymentOptionType === 'PD' && item.PaymentStatus === 'P'
    );
    let PaymentGatewayfilter = params?.PaymentOrderDtl?.filter(
      (item) => item.PaymentOptionType === 'PG' && item.PaymentStatus === 'P'
    );

    if (type === 'PaymentDevice') {
      await dispatch(
        changePaymentTransactionNumber(Paymentdevicefilter?.[0]?.PaymentOrderId)
      );
      let paymentdetail = {
        TransactionNumber: Paymentdevicefilter?.[0]?.PaymentOrderId,
        SequenceNumber: 1,
        AllowedPaymentMode:
          Paymentdevicefilter?.[0]?.PaymentTypeName?.toLowerCase() === 'card'
            ? '1'
            : Paymentdevicefilter?.[0]?.PaymentTypeName?.toLowerCase() === 'upi'
              ? '10'
              : '',
        Amount: `${parseInt(Paymentdevicefilter?.[0]?.Amount) * 100}`,
        ClientID: useOptions?.[0]?.PDConfigDetails?.[0]?.ClientId,
        StoreID: useOptions?.[0]?.PDConfigDetails?.[0]?.StoreId,
        UserID: useOptions?.[0]?.PDConfigDetails?.[0]?.UserId,
        MerchantID: useOptions?.[0]?.PDConfigDetails?.[0]?.MerchantId,
        SecurityToken: useOptions?.[0]?.PDConfigDetails?.[0]?.SecurityToken,
        IMEI: useOptions?.[0]?.PDConfigDetails?.[0]?.IMEI,
        AutoCancelDurationInMinutes:
          useOptions?.[0]?.PDConfigDetails?.[0]?.AutoCancelDurationInMinutes,
      };
      let apiresponse = await dispatch(
        PostPaymentdevice(paymentdetail)
      ).unwrap();
      if (apiresponse?.ResponseMessage?.toLowerCase() === 'approved') {
        let pendingPaymentList = {
          MerchantID: useOptions?.[0]?.PDConfigDetails?.[0]?.MerchantId,
          SecurityToken: useOptions?.[0]?.PDConfigDetails?.[0]?.SecurityToken,
          ClientID: useOptions?.[0]?.PDConfigDetails?.[0]?.ClientId,
          StoreID: useOptions?.[0]?.PDConfigDetails?.[0]?.StoreId,
          IMEI: useOptions?.[0]?.PDConfigDetails?.[0]?.IMEI,
          PlutusTransactionReferenceId:
            apiresponse?.PlutusTransactionReferenceID,
          PaymentOrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
          UpdatedBy: UserId,
        };
        await dispatch(PutPendingPaymentList(pendingPaymentList)).unwrap();
        let isApproved = false;
        const startTime = Date.now();
        let postpaymentdata = {
          MerchantID: useOptions?.[0]?.PDConfigDetails?.[0]?.MerchantId,
          SecurityToken: useOptions?.[0]?.PDConfigDetails?.[0]?.SecurityToken,
          ClientID: useOptions?.[0]?.PDConfigDetails?.[0]?.ClientId,
          StoreID: useOptions?.[0]?.PDConfigDetails?.[0]?.StoreId,
          IMEI: useOptions?.[0]?.PDConfigDetails?.[0]?.IMEI,
          PlutusTransactionReferenceID:
            apiresponse?.PlutusTransactionReferenceID,
        };
        // Loop to call the second API every 3 seconds
        while (!isApproved) {
          let ApiResponseget = await dispatch(
            GetPaymentdeviceResponse(postpaymentdata)
          ).unwrap();

          if (
            ApiResponseget?.ResponseMessage?.toLowerCase() === 'txn approved'
          ) {
            let putbookingdata = {
              OrderBookingId: Paymentdevicefilter?.[0]?.OrderId,
              OrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
              PaymentStatus: 'S',
              Amount: Paymentdevicefilter?.[0]?.Amount,
              ResponseDtl: [ApiResponseget],
              PaymentType: Paymentdevicefilter?.[0]?.PaymentType,
              UpdatedBy: UserId,
            };

            let bookingpaymentupdate = await dispatch(
              PutBookingPaymentStatusChange(putbookingdata)
            ).unwrap();
            if (bookingpaymentupdate?.data?.statusCode === 1) {
              setMessageType('success');
              setMessageData(
                bookingpaymentupdate?.data?.response +
                  ' ' +
                  (bookingpaymentupdate?.data?.OrderDetails?.length > 0
                    ? bookingpaymentupdate?.data?.OrderId &&
                      extractLastNumberOrderId(
                        bookingpaymentupdate?.data?.OrderId,
                        response?.data?.bookingpaymentupdate?.[0]?.FYStatus
                      )
                    : '')
              );
              dispatch(changePaymentloader(false));
              let getpaymentgatewaydetail = await dispatch(
                PaymentCardGetdetail(bookingpaymentupdate?.data?.OrderId)
              ).unwrap();
              let data =
                getpaymentgatewaydetail?.data?.data?.[0]?.OrderPaymentDtls.reduce(
                  (total, item) => {
                    return total + item.Amount;
                  },
                  0
                );

              if (totalAmount == data && Buttonicon) {
                setFullPayment(true);
                await dispatch(changePreOrderAdvance(0));
              } else {
                successFunction();
              }
            }

            isApproved = true;
            console.log('Transaction Approved!');
            // Exit the loop
            break;
          }

          // Check if 1 minute has passed
          if (
            Date.now() - startTime >
            useOptions?.[0]?.PDConfigDetails?.[0]?.AutoCancelDurationInMinutes *
              60000
          ) {
            // 60,000 ms = 1 minute
            console.error('Transaction not approved within 1 minute.');
            let putbookingdata = {
              OrderBookingId: Paymentdevicefilter?.[0]?.OrderId,
              OrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
              PaymentStatus: 'F',
              Amount: Paymentdevicefilter?.[0]?.Amount,
              ResponseDtl: [ApiResponseget],
              PaymentType: Paymentdevicefilter?.[0]?.PaymentType,
              UpdatedBy: UserId,
            };

            let bookingpaymentupdate = await dispatch(
              PutBookingPaymentStatusChange(putbookingdata)
            ).unwrap();
            if (bookingpaymentupdate?.data?.statusCode === 1) {
              setMessageType('error');
              setMessageData(
                `Payment Failed. Your Transaction Number is ${Paymentdevicefilter?.[0]?.PaymentOrderId}`
              );
              dispatch(changePaymentloader(false));
              let AllPaymentOptions = useOptions?.find(
                (item) => item.FlowName === 'Sales'
              );
              let object = AllPaymentOptions?.OptionDetails?.find(
                (item) => item.OptionName === 'Pay at the counter'
              )?.ModeDetails;

              setselectedPaymentOption(
                object?.find((mode) => mode.ModeName == 'Cash')?.ModeId
              );
              setselectOptionName('Cash');
            }
            break;
          }

          // Wait for 3 seconds before making the next call
          await new Promise((resolve) => setTimeout(resolve, 3000));
        }
      } else {
        let putbookingdata = {
          OrderBookingId: Paymentdevicefilter?.[0]?.OrderId,
          OrderId: Paymentdevicefilter?.[0]?.PaymentOrderId,
          PaymentStatus: 'F',
          Amount: Paymentdevicefilter?.[0]?.Amount,
          PaymentType: Paymentdevicefilter?.[0]?.PaymentType,
          UpdatedBy: UserId,
        };
        let bookingpaymentupdate = await dispatch(
          PutBookingPaymentStatusChange(putbookingdata)
        ).unwrap();
        if (bookingpaymentupdate?.data?.statusCode === 1) {
          setMessageType('error');
          setMessageData(apiresponse?.ResponseMessage);
          await dispatch(changePaymentloader(false));
          let AllPaymentOptions = useOptions?.find(
            (item) => item.FlowName === 'Sales'
          );
          let object = AllPaymentOptions?.OptionDetails?.find(
            (item) => item.OptionName === 'Pay at the counter'
          )?.ModeDetails;
          setselectedPaymentOption(
            object?.find((mode) => mode.ModeName == 'Cash')?.ModeId
          );
          setselectOptionName('Cash');
        }
      }
    } else if (type === 'PaymentGateway') {
      const checkPaymentStatus = async () => {
        const intervalId = setInterval(async () => {
          try {
            let getpaymentgatewaydetail = await dispatch(
              PaymentCardGetdetail(PaymentGatewayfilter?.[0]?.OrderId)
            ).unwrap();

            if (getpaymentgatewaydetail?.data?.statusCode === 1) {
              let paymentdataget =
                getpaymentgatewaydetail?.data?.data?.[0]?.OrderPaymentDtls?.find(
                  (item) =>
                    item?.PaymentOrderId ===
                    PaymentGatewayfilter?.[0]?.PaymentOrderId
                )?.PaymentStatus;

              if (paymentdataget === 'S') {
                setMessageType('success');
                setMessageData('Payment Success');
                await dispatch(changePaymentloader(false));
                clearInterval(intervalId); // Stop the loop when payment is successful
                let data =
                  getpaymentgatewaydetail?.data?.data?.[0]?.OrderPaymentDtls.reduce(
                    (total, item) => {
                      return total + item.Amount;
                    },
                    0
                  );
                if (totalAmount == data && Buttonicon) {
                  setFullPayment(true);
                  await dispatch(changePreOrderAdvance(0));
                } else {
                  successFunction();
                }
              } else if (paymentdataget === 'F') {
                setMessageType('error');
                setMessageData('Payment Failed');
                await dispatch(changePaymentloader(false));
                let AllPaymentOptions = useOptions?.find(
                  (item) => item.FlowName === 'Sales'
                );
                let object = AllPaymentOptions?.OptionDetails?.find(
                  (item) => item.OptionName === 'Pay at the counter'
                )?.ModeDetails;
                setselectedPaymentOption(
                  object?.find((mode) => mode.ModeName == 'Cash')?.ModeId
                );
                setselectOptionName('Cash');
                clearInterval(intervalId); // Stop the loop when payment fails
                const customerDisplayWindow = getCustomerDisplayWindow();
                if (customerDisplayWindow && !customerDisplayWindow.closed) {
                  const updatedData = {
                    userData: [...PreOrderList],
                    ExtraCharges: GlobalExtraCharge,
                    customer: selOption != null ? selOption : GetCustId,
                    paymentMethod: selectOptionName,
                    Paymentgateway: false,
                  };
                  customerDisplayWindow.postMessage(updatedData, '*');
                }
              }
            }
          } catch (error) {
            console.error('Error fetching payment details: ', error);
          }
        }, 3000); // Call the API every 3 seconds
      };

      // Call the function to start checking payment status
      checkPaymentStatus();
      const GateWay = PaymentGatewayfilter?.[0];

      const customerDisplayWindow = getCustomerDisplayWindow();

      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        const updatedData = {
          OrderBookingId: GateWay?.OrderId,
          Paymentgateway: true,
          OrderPaymentId: GateWay?.PaymentOrderId,
          OrderTotalAmount: GateWay?.Amount,
          paymentMethod: ModeName,
        };
        customerDisplayWindow.postMessage(updatedData, '*');
      } else {
        console.error(
          'Customer display window is not available or has been closed.'
        );
      }
    }
  };

  const cancelEdit = async () => {
    setEdit(false);
    setButton(false);
    setselectedPaymentOption();
    setOldAdvanceAmount(0);
    setBalaceAmount(0);
    await formRef?.current?.resetFields();
    await dispatch(changepreOrderList(null));
    await dispatch(changepreOrder(true));
    await dispatch(changePreOrderCusName(null));
    await dispatch(changePreOrderCusMob(null));
    await dispatch(changePreOrderDate());
    await dispatch(changePreOrderTime(null));
    await dispatch(changePreOrderAdd1(null));
    await dispatch(changePreOrderAdd2(null));
    await dispatch(changePreOrderAdvance(null));
    await dispatch(changePreOrderzip(null));
    await dispatch(changePreOrderCity(null));
    await dispatch(changePreOrderDistrict(null));
    await dispatch(changePreOrderState(null));
    await dispatch(changePreOrderAdditem('AddDetails'));
    await dispatch(changeCustomerID(null));
    await dispatch(changeSelectedCustId(null));
    await dispatch(changeSelectedOption(null));

    setItemEditData([]);
    setselectedOption('Booking');
    setZipCodeData(false);
    setSetAsDefaultCust(false);
    setCusName();
    setMobName();
    setTotalAmount();
    setBalaceAmount();
    setAdd1();
    setAdd2();
    setZip();
    setImageUrl('');
    setGetWayOptions();
    setSelectedGetWayOptions();
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedRemovedData = {
        userData: [],
        ExtraCharges: [],
        paymentMethod: 'Cash',
        type: 'remove',
        keyValue: 'customer',
      };
      customerDisplayWindow.postMessage(updatedRemovedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
  };
  const onFinish = async () => {
    let formattedPreOrderDate = null;

    if (PreOrderDate !== null && PreOrderDate !== undefined) {
      const day = String(PreOrderDate.$D).padStart(2, '0');
      const month = String(PreOrderDate.$M + 1).padStart(2, '0'); // Month is zero-based
      const year = PreOrderDate.$y;
      const dateString = `${day}-${month}-${year}`;
      formattedPreOrderDate = moment(dateString, 'DD-MM-YYYY').format(
        'DD-MM-YYYY'
      );
    }
    if (formattedPreOrderDate === null && PreOrderTime === null) {
      setMessageType('error');
      setMessageData('Select Date And Time');
    } else if (formattedPreOrderDate === null) {
      setMessageType('error');
      setMessageData('Select Date');
    } else if (PreOrderTime === null) {
      setMessageType('error');
      setMessageData('Select Time');
    } else if (SelCustId === null) {
      setMessageType('error');
      setMessageData('Select Customer');
    } else if (splitPayment) {
      Buttonicon ? setStatus('Edit') : setStatus('Delivery');
    } else if (
      PreOrderAdvance > 0 &&
      PreOrderAdvance != null &&
      (selectedPaymentOption === ' ' ||
        selectedPaymentOption === undefined ||
        selectedPaymentOption === null)
    ) {
      setMessageType('error');
      setMessageData('Select Payment Option');
    } else {
      if (
        PaymentOptions?.find((item) => item.ModeId === selectedPaymentOption)
          ?.ModeName === 'Cash' ||
        PaymentOptions?.find((item) => item.ModeId === selectedPaymentOption)
          ?.ModeName === 'Credit'
      ) {
        FurderFlow();
      } else if (
        PaymentOptions?.find((item) => item.ModeId === selectedPaymentOption)
          ?.ModeName === 'Card'
      ) {
        if (GateWayOptions?.length > 1) {
          if (selectedGateWayOptions != undefined) {
            FurderFlow();
          } else {
            setMessageType('error');
            setMessageData('Select GateWay Option');
          }
        } else {
          FurderFlow();
        }
      } else if (
        PaymentOptions?.find((item) => item.ModeId === selectedPaymentOption)
          ?.ModeName === 'UPI'
      ) {
        if (
          selectedGateWayOptions === 'Default' ||
          GateWayOptions?.length === 1
        ) {
          if (selectedGateWayOptions != undefined) {
            if (selectedUPIOption != null) {
              FurderFlow();
            } else {
              setMessageType('error');
              setMessageData('Select UPI Option');
            }
          } else {
            setMessageType('error');
            setMessageData('Select GateWay Option');
          }
        } else {
          FurderFlow();
        }
      }
    }
  };

  const FurderFlow = () => {
    if (
      (selectedUPIOption && selectedGateWayOptions == 'Default' && qrcode) ||
      CreditCustomer?.basic
    ) {
      UpiPayment();
    } else {
      AddBookingDetails();
    }
  };

  const onChange_Pending_FromDate = async (_, dateString) => {
    if (dateString) {
      const formattedDateTime = moment(
        dateString,
        'DD-MM-YYYY HH:mm:ss'
      ).format('DD-MM-YYYY HH:mm:ss');
      setPreOrder_Pending_FromDate(formattedDateTime);
      const FromDateApi = moment(dateString, 'DD-MM-YYYY HH:mm:ss').format(
        'YYYY-MM-DD'
      );
      const ToDateApi = moment(
        PreOrder_Pending_ToDate,
        'DD-MM-YYYY HH:mm:ss'
      ).format('YYYY-MM-DD');

      if (PreOrder_Pending_ToDate != undefined) {
        PendingApiCall(FromDateApi, ToDateApi);
      }
    } else {
      setPreOrder_Pending_FromDate(undefined);

      PendingApiCall();
    }
  };

  const onChange_Pending_ToDate = async (_, dateString) => {
    dispatch(changeDropDownStatus(false));
    if (dateString) {
      const formattedDateTime = moment(
        dateString,
        'DD-MM-YYYY HH:mm:ss'
      ).format('DD-MM-YYYY HH:mm:ss');
      setPreOrder_Pending_ToDate(formattedDateTime);
      const ToDateApi = moment(dateString, 'DD-MM-YYYY HH:mm:ss').format(
        'YYYY-MM-DD'
      );
      const FromDateApi = moment(
        PreOrder_Pending_FromDate,
        'DD-MM-YYYY HH:mm:ss'
      ).format('YYYY-MM-DD');

      if (PreOrder_Pending_FromDate != undefined) {
        PendingApiCall(FromDateApi, ToDateApi);
      }
    } else {
      setPreOrder_Pending_ToDate(undefined);
      PendingApiCall();
    }
  };

  const onChangeDate_History_FromDate = async (_, dateString) => {
    if (dateString) {
      const formattedDateTime = moment(
        dateString,
        'DD-MM-YYYY HH:mm:ss'
      ).format('DD-MM-YYYY HH:mm:ss');
      setPreOrder_History_FromDate(formattedDateTime);
      const FromDateApi = moment(dateString, 'DD-MM-YYYY HH:mm:ss').format(
        'YYYY-MM-DD'
      );
      const ToDateApi = moment(
        PreOrder_History_ToDate,
        'DD-MM-YYYY HH:mm:ss'
      ).format('YYYY-MM-DD');

      if (PreOrder_History_ToDate != undefined) {
        HistoryApiCall(FromDateApi, ToDateApi);
      }
    } else {
      setPreOrder_History_FromDate(undefined);
      HistoryApiCall();
    }
  };

  const onChangeDate_History_ToDate = async (_, dateString) => {
    if (dateString) {
      const formattedDateTime = moment(
        dateString,
        'DD-MM-YYYY HH:mm:ss'
      ).format('DD-MM-YYYY HH:mm:ss');
      setPreOrder_History_ToDate(formattedDateTime);
      const ToDateApi = moment(dateString, 'DD-MM-YYYY HH:mm:ss').format(
        'YYYY-MM-DD'
      );
      const FromDateApi = moment(
        PreOrder_History_FromDate,
        'DD-MM-YYYY HH:mm:ss'
      ).format('YYYY-MM-DD');

      if (PreOrder_History_FromDate != undefined) {
        HistoryApiCall(FromDateApi, ToDateApi);
      }
    } else {
      setPreOrder_History_ToDate(undefined);
      HistoryApiCall();
    }
  };

  const OnchangePreOrderIcon = async () => {
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedData = {
        userData: [],
        ExtraCharges: [],
        type: 'remove',
        keyValue: 'customer',
        paymentMethod: null,
      };
      customerDisplayWindow.postMessage(updatedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
    await dispatch(changeBookingType('PreOrder'));
    await dispatch(changePreOrderAdditem('AddItems'));
    setPreOrder(true);
    setZipCodeData(false);
    setSetAsDefaultCust(false);
    formRef.current?.resetFields();
    await dispatch(changepreOrderList(null));
    await dispatch(changepreOrder(true));
    await dispatch(changePreOrderCusName(null));
    await dispatch(changePreOrderCusMob(null));
    await dispatch(changePreOrderDate(null));
    await dispatch(changePreOrderAdd1(null));
    await dispatch(changePreOrderAdd2(null));
    await dispatch(changePreOrderAdvance(null));
    await dispatch(changePreOrderzip(null));
    await dispatch(changePreOrderCity(null));
    await dispatch(changePreOrderDistrict(null));
    await dispatch(changePreOrderState(null));
    await dispatch(changePreOrderTime(null));
    setCusName();
    setMobName();
    setTotalAmount();
    setBalaceAmount();
    setAdd1();
    setAdd2();
    setZip();
    // }
    await dispatch(changeCustomerID(null));
    await dispatch(changeSelectedCustId(null));
    await dispatch(changeSelectedOption(null));
    await dispatch(changealldata(false));
    setselectedOption('Booking');
    setItemEditData();
  };

  const productModalCancel = () => {
    setModalProduct(!ModalProduct);
    setPendingOrderView();
  };

  const SelectDefaultCaustmer = async (e) => {
    setSetAsDefaultCust(e.target.checked);

    const setZipCodeAddress = async () => {
      setZipCodeData(true);
      formRef.current?.setFieldsValue({
        City: CustDetails?.City,
        Dist: CustDetails?.Dist,
        State: CustDetails?.State,
      });
      await dispatch(changePreOrderCity(CustDetails?.City));
      await dispatch(changePreOrderDistrict(CustDetails?.Dist));
      await dispatch(changePreOrderState(CustDetails?.State));
    };

    if (e.target.checked && CustDetails != undefined) {
      await dispatch(changePreOrderCusName(CustDetails?.CustName));
      await dispatch(
        changePreOrderCusMob(CustDetails?.value || CustDetails?.CustMobile)
      );
      await dispatch(changePreOrderAdd1(CustDetails?.Address1));
      await dispatch(changePreOrderAdd2(CustDetails?.Address2));
      await dispatch(changePreOrderzip(CustDetails?.Zip));
      formRef?.current?.setFieldsValue({
        Name: CustDetails?.CustName,
        MobileNo: CustDetails?.value || CustDetails?.CustMobile,
        Address1: CustDetails?.Address1,
        Address2: CustDetails?.Address2,
        Zip: CustDetails?.Zip,
      });
      if (CustDetails?.Zip?.toString().length === 6) {
        setZipCodeAddress();
      }
    } else {
      setZipCodeData(false);
      await dispatch(changePreOrderCusName(null));
      await dispatch(changePreOrderCusMob(null));
      await dispatch(changePreOrderAdd1(null));
      await dispatch(changePreOrderAdd2(null));
      await dispatch(changePreOrderzip(null));
      await dispatch(changePreOrderCity(null));
      await dispatch(changePreOrderDistrict(null));
      await dispatch(changePreOrderState(null));
      formRef?.current?.setFieldsValue({
        Name: '',
        MobileNo: '',
        Address1: '',
        Address2: '',
        Zip: '',
        City: '',
        Dist: '',
        State: '',
      });
    }
  };

  const EditableRow = ({ index, ...props }) => {
    return (
      <Form form={Itemform} component={false}>
        <EditableContext.Provider value={Itemform}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };

  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);

    useEffect(() => {
      if (editing) {
        inputRef?.current?.focus();
      }
    }, [editing]);

    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };

    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({
          ...record,
          ...values,
        });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };

    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              pattern: /^[1-9]\d*(\.\d+)?$/,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }

    return <td {...restProps}>{childNode}</td>;
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const handleDelete = async (key) => {
    const newData1 = PreOrderList?.filter(
      (item) =>
        !(
          item.SinglePc === key?.SinglePc &&
          item.InwardDtlId === key?.InwardDtlId
        )
    );
    await dispatch(changepreOrderList(newData1));
  };
  const Icolumns = [
    {
      title: 'SI',
      key: 'ProdName',
      align: 'center',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{index + 1}</a>
      ),
    },
    {
      title: 'PRODUCT',
      dataIndex: 'ProdName',
      key: 'ProdName',
    },
    {
      title: 'QTY',
      dataIndex: 'OrderQty',
      key: 'OrderQty',
      width: '100px',
      editable: true,
      render: (_, record, index) => (
        <>
          <div>{record?.OrderQty || record?.SalesQty} </div>
        </>
      ),
    },
    {
      title: 'UOM',
      dataIndex: 'UomName',
      key: 'UomName',
    },
    {
      title: 'AMT',
      dataIndex: 'MRP',
      key: 'MRP',
      align: 'right',
      render: (_, record, index) => (
        <>
          <div>{record?.OrderRate || record?.MRP} </div>
        </>
      ),
    },
    {
      title: '%',
      dataIndex: 'OfferPrice',
      key: 'OfferPrice',
      align: 'right',
      render: (_, record, index) => (
        <>
          <div>
            {record?.TotalOfferPrice || record?.OfferAmt
              ? record?.TotalOfferPrice || record?.OfferAmt
              : '-'}{' '}
          </div>
        </>
      ),
    },
    {
      title: 'TOTAL',
      dataIndex: 'TotalAmt',
      key: 'TotalAmt',
      align: 'right',
    },
    {
      title: 'Details',
      dataIndex: 'Details',
      key: 'Details',
      width: '50px',
      render: (_, record, index) => (
        <>
          <div style={{ display: 'flex' }}>
            <a
              onClick={() =>
                ShowDetailFn(record?.Image, record?.Description, index)
              }
            >
              <IoEye style={{ fontSize: '20px' }} />
            </a>
            {ItemEditdata.length >= 1 && (
              <Popconfirm
                title="Are you sure you want to delete?"
                onConfirm={() => handleDelete(record)}
              >
                <a style={{ paddingLeft: '10px' }}>
                  <RiCloseCircleFill
                    style={{ color: '#FF4D4F', fontSize: '20px' }}
                  />
                </a>
              </Popconfirm>
            )}
          </div>
        </>
      ),
    },
  ];

  const ShowDetailFn = (img, mess, index) => {
    setShowDetails(!ShowDetails);
    setImageUrl(img);
    setIndex(index);
    setMessageModel(mess);
    ViewformRef.current?.setFieldsValue({ Message: mess });
  };

  const columns = Icolumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  const handleSave = async (row) => {
    let off =
      row?.Type != 'P'
        ? row.OfferValue
        : (row?.OrderRate * row?.OfferValue) / 100;

    const newData = [...ItemEditdata];
    const index = newData.findIndex((item) => row.ProdId === item.ProdId);
    const item = newData[index];
    const UpdatedData = {
      ProdName: row.ProdName,
      OrderQty: row.OrderQty,
      UomName: row.UomName,
      Amount: row.Amount,
      TotalAmt:
        row?.Type != 'P'
          ? (row.OrderRate || row.MRP) * row.OrderQty - row.OrderQty * off
          : (row.OrderRate || row.MRP) * row.OrderQty,
      TotalOfferPrice: row?.Type != 'P' ? row.OrderQty * off : '-',
    };
    newData.splice(index, 1, {
      ...item,
      ...UpdatedData,
    });
    await dispatch(changepreOrderList(newData));
  };

  const handleEdit = async (key) => {
    setorderId(key?.OrderId);

    await dispatch(changepreOrderList(key?.productDetails));
    setKeys(key);
    await dispatch(changePreOrderAdditem('AddDetails'));
    setEdit(true);
    await setCusName(key?.Name);
    setButton(true);

    await dispatch(ChangeTotalAmount(key?.ExtraChargeDetails));
    setSetAsDefaultCust(key?.DefaultStatus == 'Y' ? true : false);
    let data = key?.CustomerDetails?.[0];
    let data1 = {
      Address1: data?.Address1,
      Address2: data?.Address2,
      City: '',
      CustId: key?.CustSuppId,
      CustName: data?.CustSuppName,
      Dist: '',
      State: '',
      Zip: data?.ZipCode,
      label: data?.CustSuppName || data?.MobileNo,
      value: data?.MobileNo,
    };

    const fromTime = moment(key?.DeliveryTime, ['h:mm a']).format('HH:mm:ss');

    setOldAdvanceAmount(key?.PaidAmount);
    setselectedOption('Booking');
    setOrderDetail({ OrderId: key?.OrderId, OrderType: key?.OrderType });
    await dispatch(changeSelectedOption(data1));
    await dispatch(changePreOrderTime(fromTime));
    await dispatch(changePreOrderDate(key?.DeliveryDate));
    await dispatch(changeSelectedCustId(key?.CustSuppId));
    let AllPaymentOptions = useOptions?.find(
      (item) => item.FlowName === 'Sales'
    );
    let object = AllPaymentOptions?.OptionDetails?.find(
      (item) => item.OptionName === 'Pay at the counter'
    )?.ModeDetails;
    setselectedPaymentOption(
      object?.find((mode) => mode.ModeName == 'Cash')?.ModeId
    );
    setselectOptionName('Cash');
  };

  const PendingEditableRow = ({ index, ...props }) => {
    return (
      <Form form={Pendingform} component={false}>
        <EditableContext.Provider value={Pendingform}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };

  const PendingEditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(PendingEditableContext);

    useEffect(() => {
      if (editing) {
        inputRef?.current?.focus();
      }
    }, [editing]);

    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };

    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({
          ...record,
          ...values,
        });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };

    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              pattern: /^[1-9]\d*(\.\d+)?$/,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }

    return <td {...restProps}>{childNode}</td>;
  };

  const Pendingcomponents = {
    body: {
      row: PendingEditableRow,
      cell: PendingEditableCell,
    },
  };

  const handlePreOrderDelete = async (params) => {
    if (params?.PaidAmount > 0) {
      setCancelModal(true);
      setPreOrderData(params);
    } else {
      PreOrderCancel(params);
    }
  };

  const PreOrderCancel = async (params) => {
    const CancelDat = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      OrderId: params?.OrderId,
      ...(params?.PaidAmount > 0 && {
        OrderPaymentDtl: [
          {
            PaymentType:
              cancelformRef?.current?.getFieldsValue()?.CancelPayOptions,
            Amount: cancelformRef?.current?.getFieldsValue()?.RefundAmount || 0,
            PaymentStatus: 'S',
          },
        ],
      }),
      CreatedBy: UserId,
    };
    let DeleteResponse = await dispatch(PreOrderBookingDataCancel(CancelDat));
    if (DeleteResponse?.payload?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData('OrderStatus Deleted Successfully');
      PendingApiCall();
      cancelformRef?.current?.resetFields();
      setCancelModal(false);
      setPreOrderData();
      setCancelPaymentOption(null);
      setPreOrderRefund(null);
    } else {
      setMessageType('error');
      setMessageData(DeleteResponse?.payload?.data?.response);
    }
  };

  const History_onSearch = (value) => {
    HistorysetSearchedText(value);
  };

  const History_onSearchChange = (e) => {
    HistorysetSearchedText(e?.target?.value);
  };

  const formatDate = (paramdate, time) => {
    const date = new Date(paramdate);

    if (isNaN(date.getTime())) {
      return 'Invalid Date';
    }
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-indexed
    const year = date.getFullYear();

    return `${day}-${month}-${year} ${time}`;
  };
  const Pcolumns = [
    {
      title: <div style={{ fontSize: '10px' }}>SI</div>,
      dataIndex: 'OrderId',
      key: 'OrderId',
      align: 'center',
      fixed: 'left',
      render: (text, object, index) => (
        <a style={{ color: 'black', fontSize: '10px' }}>{index + 1}</a>
      ),
    },
    {
      title: <div style={{ fontSize: '10px' }}>O.ID</div>,
      dataIndex: 'OrderId',
      key: 'OrderId',
      align: 'center',
      fixed: 'left',
      filteredValue: [PendingsearchedText],
      render: (text, record, index) => (
        <a style={{ color: 'black', fontSize: '10px' }}>
          {record.FYStatus === 'Y'
            ? extractThreeDigitNumber(text)
            : extractLastNumber(text)}
        </a>
      ),
      onFilter: (value, record) => {
        return (
          String(record.OrderId).toLowerCase().includes(value.toLowerCase()) ||
          String(record.DeliveryDate)
            .toLowerCase()
            .includes(value.toLowerCase()) ||
          String(record.DeliveryTime)
            .toLowerCase()
            .includes(value.toLowerCase()) ||
          String(formatDate(record?.DeliveryDate, record.DeliveryTime))
            .toLowerCase()
            .includes(value.toLowerCase())
        );
      },
      ellipsis: true,
    },
    {
      title: <div style={{ fontSize: '10px' }}>DATE/TIME</div>,
      dataIndex: 'OrderId',
      key: 'ProdNameQty',
      align: 'center',

      render: (_, record) => (
        <a style={{ color: 'black', fontSize: '10px' }}>
          {formatDate(record?.DeliveryDate, record.DeliveryTime)}
        </a>
      ),
    },
    {
      title: <div style={{ fontSize: '10px' }}>Customer</div>,
      dataIndex: 'OrderId',
      align: 'center',
      render: (_, record) => (
        <IoEye
          style={{ fontSize: '18px', color: '#000' }}
          onClick={() =>
            setPendingCustomerView({
              Data: record?.CustomerDetails?.[0],
              status: true,
            })
          }
        />
      ),
    },
    {
      title: <div style={{ fontSize: '10px' }}>Order</div>,
      dataIndex: 'OrderId',
      align: 'center',
      render: (_, record) => (
        <IoEye
          style={{ fontSize: '18px', color: '#000' }}
          onClick={() => viewproductModel(record?.productDetails)}
        />
      ),
    },
    {
      title: <div style={{ fontSize: '10px' }}>Action</div>,
      dataIndex: 'operation',

      fixed: 'right',
      align: 'center',
      render: (_, record) => (
        <>
          <Space size="middle">
            <Popconfirm
              title="Are you sure you want to edit?"
              onConfirm={() => handleEdit(record)}
            >
              <EditFilled
                style={{
                  color: '#1292EE',
                  fontSize: '18px',
                }}
              />
            </Popconfirm>
            {!Buttonicon && (
              <Popconfirm
                title="Are you sure you want to delete?"
                onConfirm={() => handlePreOrderDelete(record)}
              >
                <RiCloseCircleFill
                  style={{
                    color: '#FF4D4F',
                    fontSize: '18px',
                  }}
                />
              </Popconfirm>
            )}
          </Space>
        </>
      ),
    },
  ];

  const Upimodel = (type) => {
    setUpiOpen(false);
    if (type == 'Submit') {
      AddBookingDetails();
    }
    if (type == 'Cancel') {
      setselectedUPIOption();
    }
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedRemovedData = {
        type: 'remove',
        keyValue: 'OrderTotalAmount',
        Paymentgateway: false,
        upi: GlobalUpiID,
        paymentMethod: selectOptionName,
      };
      customerDisplayWindow.postMessage(updatedRemovedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
  };
  const handleCreditCustomer = (type) => {
    if (type == 'Submit') {
      setCreditCustomer({
        basic: false,
        model: false,
      });
      AddBookingDetails();
    }
    if (type == 'Cancel') {
      setCreditCustomer({
        basic: true,
        model: false,
      });
    }
    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedRemovedData = {
        type: 'remove',
        keyValue: 'OrderTotalAmount',
      };
      customerDisplayWindow.postMessage(updatedRemovedData, '*');
    } else {
      console.error(
        'Customer display window is not available or has been closed.'
      );
    }
  };
  const onFinalSubmit = async () => {
    let MobileNo = selOption?.value;
    let BrachName = PaymentUpiOptions?.[0]?.BrName;
    let url = `${MainHomeUrl}payment-page?amt=${PreOrderAdvance}&Id=${MobileNo}&cus=${SelCustId} &CusN=${selOption?.CustName}&Br=${BrachName}`;
    let response = await dispatch(SendPaymentLink({ MobileNo, url })).unwrap();
    if (response?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData('Link Sent Successfully');
    }
  };

  const viewproductModel = (value) => {
    setModalProduct(true);
    setPendingOrderView(value);
  };

  const Productcolumns = [
    { title: 'Product ', dataIndex: 'ProdName', key: 'ProdName' },
    { title: 'Quantity', dataIndex: 'OrderQty', key: 'OrderQty' },
    { title: 'Rate', dataIndex: 'MRP', key: 'MRP' },
    { title: 'Total Amount', dataIndex: 'TotalAmt', key: 'TotalAmt' },
    {
      title: 'Image',
      dataIndex: 'Image',
      key: 'Image',
      render: (text, record) =>
        record?.Image ? (
          <img
            src={record?.Image}
            alt="Product"
            style={{ width: '100px', height: 'auto' }}
          />
        ) : (
          ''
        ),
    },
    { title: 'Description', dataIndex: 'Description', key: 'Description' },
  ];

  const Pendingcolumns = Pcolumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  const handleAdvancevalidator = (rule, value, callback) => {
    if (totalAmount - OldAdvanceAmount - value < 0) {
      callback('Please Enter AdvanceAmount less than or equal to TotalAmount');
    } else {
      callback();
    }
  };

  const MouseFunction = async (e) => {
    dispatch(changeDropDownStatus(e));
  };
  const openMenuClick = async () => {
    await dispatch(ChangeSearchFocusPreOrder(true));
  };

  const CountUp = useCountUp(Math.round(PreOrderAdvance));

  return (
    <>
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />
      <div ref={containerRef}>
        {preOrderOpen && (
          <div className="ComboPreOrder-MasterDiv">
            <div className="PreOrder-subContainer">
              <div>
                <h1 class="formHeader PreOrderFormHeader">Pre Booking</h1>
                <Flex
                  gap="small"
                  align="flex-start"
                  vertical
                  className="PreOrder-Flex"
                >
                  <Segmented
                    options={[
                      {
                        label: (
                          <div className="PreOrder-LableDiv">
                            <Avatar
                              className="PreOrder-LableAvatar"
                              icon={<BsClipboardCheckFill />}
                            />
                            <div>
                              Booking
                              <Badge className="PreOrder-LableText" />
                            </div>
                          </div>
                        ),
                        value: 'Booking',
                      },
                      {
                        label: (
                          <div className="PreOrder-LableDiv">
                            <Avatar
                              className="PreOrder-LableAvatar"
                              icon={<MdOutlinePendingActions />}
                            />
                            <div>
                              Pending{' '}
                              <Badge
                                className="PreOrder-LableText"
                                count={PendingData?.length}
                              />
                            </div>
                          </div>
                        ),
                        value: 'Pending',
                      },
                      {
                        label: (
                          <div className="PreOrder-LableDiv">
                            <Avatar
                              className="PreOrder-LableAvatar"
                              icon={<MdHistory />}
                            />
                            <div>
                              History
                              <Badge
                                className="PreOrder-LableText"
                                count={HistoryData?.length}
                              />
                            </div>
                          </div>
                        ),
                        value: 'History',
                      },
                    ]}
                    value={SelectedOption}
                    onChange={(e) => {
                      setselectedOption(e);
                    }}
                  />
                </Flex>
              </div>

              {SelectedOption == 'Booking' && (
                <>
                  <div className="PreOrder-TwoButtons">
                    <Button
                      icon={<FiPlus />}
                      onClick={async () => {
                        (await dispatch(changePreOrderAdditem('AddItems')),
                          setTotalAmount(),
                          setBalaceAmount());
                      }}
                    >
                      Add Item
                    </Button>
                    <Button
                      icon={<FiPlus />}
                      onClick={async () => {
                        await dispatch(changePreOrderAdditem('AddDetails'));
                      }}
                    >
                      Add Details
                    </Button>
                  </div>
                  {PreOrderAdditem == 'AddDetails' && (
                    <div className="PreOrder-BookingForm-div">
                      <div>
                        <Form
                          ref={formRef}
                          onFinish={onFinish}
                          className="PreOrder-Combo"
                        >
                          <div
                            className="PreOrder-FormDiv3"
                            onMouseEnter={() => MouseFunction(true)}
                            onMouseLeave={() => MouseFunction(false)}
                            // onClick={() => openMenuClick()}
                          >
                            <Form.Item name="DeliveryDate">
                              <DatePicProd
                                canSelectPast={false}
                                onChange={onChangeDate}
                                valueData={PreOrderDate}
                              />
                            </Form.Item>

                            <Form.Item name="DeliveryTime">
                              <TimePickers
                                label={
                                  <label class="required">Delivery Time</label>
                                }
                                isOnChange={true}
                                onChange={onChangeTime}
                                valueData={PreOrderTime}
                              />
                            </Form.Item>
                          </div>
                          <div className="PreOrder-FormDiv">
                            <BSCustomerSelect Focus="false" />
                            <BSNavBarAddUser />
                            <div className="PreOrder-SetDefault">
                              <p className="Ptag">Set As Customer </p>
                              <Checkbox
                                onChange={SelectDefaultCaustmer}
                                checked={SetAsDefaultCust}
                                disabled={
                                  CustDetails === undefined ? true : false
                                }
                              />
                            </div>
                          </div>
                          <div className="PreOrder-FormDiv">
                            <Form.Item
                              name="Name"
                              rules={[
                                {
                                  // required: true,
                                  pattern: /^(?!\s*$).+/,
                                  message: 'Please Enter Name',
                                },
                                {
                                  validator: async (_, value) => {
                                    await validateSafeInput(value); // To block HTML tags & SQL keywords
                                    return Promise.resolve();
                                  },
                                },
                              ]}
                              onClick={() => openMenuClick()}
                            >
                              <InputField
                                field="Name"
                                name="Name"
                                label={<label>Name</label>}
                                fieldState={true}
                                fieldApi={true}
                                autocomplete="off"
                                value={PreOrderCusName}
                                onChange={NameOnChange}
                                disabled={SetAsDefaultCust ? true : false}
                                isOnChange={
                                  (CustDetails?.CustName?.length > 0 &&
                                    SetAsDefaultCust) ||
                                  CusName
                                    ? true
                                    : false
                                }
                              />
                            </Form.Item>

                            <Form.Item
                              name="MobileNo"
                              rules={[
                                {
                                  required: true,
                                  pattern: /^\d{10}$/,
                                  message: 'Please Enter a Valid Mobile Number',
                                },
                                {
                                  validator: async (_, value) => {
                                    await validateSafeInput(value); // To block HTML tags & SQL keywords
                                    return Promise.resolve();
                                  },
                                },
                              ]}
                              onClick={() => openMenuClick()}
                            >
                              <InputField
                                field="MobileNo"
                                label={
                                  <label class="required">Mobile No</label>
                                }
                                fieldState={true}
                                maxLength="10"
                                fieldApi={true}
                                autocomplete="off"
                                onChange={MobOnChange}
                                disabled={SetAsDefaultCust ? true : false}
                                value={PreOrderCusMobNo}
                                isOnChange={
                                  CustDetails?.value ||
                                  (CustDetails?.CustMobile?.length > 0 &&
                                    SetAsDefaultCust) ||
                                  MobName
                                    ? true
                                    : false
                                }
                              />
                            </Form.Item>
                          </div>

                          <div className="PreOrder-FormDiv">
                            <Form.Item
                              name="AdvanceAmount"
                              rules={[
                                {
                                  pattern: /^\d+$/,
                                  message:
                                    'Please enter a valid Advance Amount (only numbers)',
                                },
                                { validator: handleAdvancevalidator },
                              ]}
                              onClick={() => openMenuClick()}
                            >
                              <InputField
                                field="AdvanceAmount"
                                autoComplete="off"
                                label={<label>Advance / Delivery Amount</label>}
                                maxLength="10"
                                fieldState={true}
                                value={PreOrderAdvance}
                                fieldApi={true}
                                onChange={OnchangeAdvance}
                                isOnChange={PreOrderAdvance ? true : false}
                              />
                            </Form.Item>
                          </div>
                          {Buttonicon && (
                            <div
                              style={{
                                display: 'flex',
                                justifyContent: 'center',
                              }}
                            >
                              <p className="Ptag">
                                Old Advance Amount : {OldAdvanceAmount}
                              </p>
                            </div>
                          )}
                          <div className="PreOrder-FormDiv5">
                            <p className="Ptag">Total Amount : {totalAmount}</p>
                            <p className="Ptag">
                              Balance Amount : {balanceAmount}
                            </p>
                          </div>
                          {ItemEditdata !== null &&
                            ItemEditdata?.length > 0 && (
                              <>
                                {PreOrderAdvance > 0 && (
                                  <>
                                    <div className="PreOrder-FormDiv6">
                                      <Form.Item
                                        name="PaymentOptions"
                                        onMouseEnter={() => openMenuClick()}
                                      >
                                        <DropDowns
                                          options={PaymentOptions?.map(
                                            (option) => ({
                                              value: option.ModeId,
                                              label: option.ModeName,
                                            })
                                          )}
                                          label={
                                            <label class="required">
                                              Payment Options
                                            </label>
                                          }
                                          isOnchanges={
                                            selectedPaymentOption ? true : false
                                          }
                                          onChangeFunction={(e) => {
                                            OnChangePaymentOption(e);
                                          }}
                                          valueData={selectedPaymentOption}
                                        />
                                      </Form.Item>
                                      {(PaymentOptions?.find(
                                        (item) =>
                                          item.ModeId === selectedPaymentOption
                                      )?.ModeName === 'UPI' ||
                                        PaymentOptions?.find(
                                          (item) =>
                                            item.ModeId ===
                                            selectedPaymentOption
                                        )?.ModeName === 'Card') &&
                                        GateWayOptions?.length > 0 && (
                                          <Form.Item
                                            name="GateWayOptions"
                                            rules={[
                                              {
                                                required: true,
                                                message:
                                                  'Please Select GateWay Option',
                                              },
                                            ]}
                                            onMouseEnter={() => openMenuClick()}
                                          >
                                            <DropDowns
                                              options={GateWayOptions?.map(
                                                (option) => ({
                                                  value: option.value,
                                                  label: option.option,
                                                })
                                              )}
                                              label={
                                                <label class="required">
                                                  Payment Methods
                                                </label>
                                              }
                                              isOnchanges={
                                                selectedGateWayOptions
                                                  ? true
                                                  : false
                                              }
                                              onChangeFunction={(e) => {
                                                cardandUpi(e);
                                              }}
                                              valueData={selectedGateWayOptions}
                                            />
                                          </Form.Item>
                                        )}
                                    </div>
                                    <div
                                      style={{
                                        display: 'flex',
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                        width: '90%',
                                        marginTop: '0.5rem',
                                      }}
                                      onMouseEnter={() => openMenuClick()}
                                    >
                                      {PaymentOptions?.find(
                                        (item) =>
                                          item.ModeId === selectedPaymentOption
                                      )?.ModeName === 'UPI' &&
                                        selectedGateWayOptions ===
                                          'Default' && (
                                          <Form.Item
                                            name="UPIOptions"
                                            rules={[
                                              {
                                                required: true,
                                                message:
                                                  'Please Select UPI Options',
                                              },
                                            ]}
                                          >
                                            <DropDowns
                                              options={useOptions?.[0]?.PaymentDetails?.Payatthecounter?.map(
                                                (option) => ({
                                                  value: option.UPIId,
                                                  label: option.ModeName,
                                                })
                                              )}
                                              label={
                                                <label class="required">
                                                  UPI Options
                                                </label>
                                              }
                                              isOnchanges={
                                                selectedUPIOption ? true : false
                                              }
                                              onChangeFunction={(e) => {
                                                OnChangeUPIOption(e);
                                              }}
                                              valueData={selectedUPIOption}
                                            />
                                          </Form.Item>
                                        )}
                                    </div>
                                  </>
                                )}
                              </>
                            )}
                          {addDetails && (
                            <>
                              <div className="PreOrder-FormAddivtionalDiv">
                                <div className="PreOrder-FormDiv">
                                  <Form.Item
                                    name="Address1"
                                    rules={[
                                      {
                                        pattern: /^(?!\s*$).+/,
                                        message: 'Please Enter Address1',
                                      },
                                      {
                                        validator: async (_, value) => {
                                          await validateSafeInput(value); // To block HTML tags & SQL keywords
                                          return Promise.resolve();
                                        },
                                      },
                                    ]}
                                  >
                                    <InputField
                                      field="Address1"
                                      autoComplete="off"
                                      label={
                                        <label class="required">
                                          Address Line1
                                        </label>
                                      }
                                      fieldState={true}
                                      fieldApi={true}
                                      isOnChange={PreOrderAdd1 ? true : false}
                                      onChange={OnChangeAddress1}
                                    />
                                  </Form.Item>
                                  <Form.Item
                                    name="Address2"
                                    rules={[
                                      {
                                        pattern: /^(?!\s*$).+/,
                                        message: 'Please Enter Address2',
                                      },
                                      {
                                        validator: async (_, value) => {
                                          await validateSafeInput(value); // To block HTML tags & SQL keywords
                                          return Promise.resolve();
                                        },
                                      },
                                    ]}
                                  >
                                    <InputField
                                      field="Address2"
                                      autoComplete="off"
                                      label="Address Line2"
                                      fieldState={true}
                                      fieldApi={true}
                                      isOnChange={PreOrderAdd2 ? true : false}
                                      onChange={OnChangeAddress2}
                                    />
                                  </Form.Item>
                                </div>
                                <div>
                                  <Form.Item
                                    name="Zip"
                                    rules={[
                                      {
                                        pattern: /^(?!\s*$).+/,
                                        message: 'Please Enter Zipcode',
                                      },
                                      {
                                        validator: async (_, value) => {
                                          await validateSafeInput(value); // To block HTML tags & SQL keywords
                                          return Promise.resolve();
                                        },
                                      },
                                    ]}
                                  >
                                    <InputField
                                      field="Zip"
                                      autoComplete="off"
                                      label={
                                        <label class="required">Zipcode</label>
                                      }
                                      maxLength="6"
                                      fieldState={true}
                                      fieldApi={true}
                                      isOnChange={PreOrderzip ? true : false}
                                      onChange={pinCodeChange}
                                    />
                                  </Form.Item>
                                </div>
                                {zipCodeData ? (
                                  <>
                                    <div className="PreOrder-FormDiv">
                                      <Form.Item
                                        name="City"
                                        rules={[
                                          {
                                            required: true,
                                          },
                                          {
                                            validator: async (_, value) => {
                                              await validateSafeInput(value); // To block HTML tags & SQL keywords
                                              return Promise.resolve();
                                            },
                                          },
                                        ]}
                                      >
                                        <InputField
                                          field="City"
                                          disabled={true}
                                          label="City"
                                          fieldState={true}
                                          fieldApi={true}
                                          isOnChange={
                                            PreOrderCity ? true : false
                                          }
                                        />
                                      </Form.Item>
                                      <Form.Item
                                        name="Dist"
                                        rules={[
                                          {
                                            required: true,
                                          },
                                          {
                                            validator: async (_, value) => {
                                              await validateSafeInput(value); // To block HTML tags & SQL keywords
                                              return Promise.resolve();
                                            },
                                          },
                                        ]}
                                      >
                                        <InputField
                                          field="Dist"
                                          disabled={true}
                                          label="District"
                                          fieldState={true}
                                          fieldApi={true}
                                          isOnChange={
                                            PreOrderDistrict ? true : false
                                          }
                                        />
                                      </Form.Item>
                                    </div>
                                    <div>
                                      <Form.Item
                                        name="State"
                                        rules={[
                                          {
                                            required: true,
                                          },
                                          {
                                            validator: async (_, value) => {
                                              await validateSafeInput(value); // To block HTML tags & SQL keywords
                                              return Promise.resolve();
                                            },
                                          },
                                        ]}
                                      >
                                        <InputField
                                          field="State"
                                          disabled={true}
                                          label="State"
                                          fieldState={true}
                                          fieldApi={true}
                                          isOnChange={
                                            PreOrderState ? true : false
                                          }
                                        />
                                      </Form.Item>
                                    </div>
                                  </>
                                ) : (
                                  ''
                                )}
                              </div>
                            </>
                          )}
                          <div
                            className="PreOrder-Additional"
                            onClick={() => {
                              addDetails
                                ? setAddDetails(false)
                                : setAddDetails(true);
                            }}
                          >
                            Additional Details
                          </div>

                          {Buttonicon ? (
                            <div>
                              <div>
                                <div
                                  style={{
                                    display: 'flex',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    gap: '0.5rem',
                                    width: '97%',
                                  }}
                                >
                                  <button
                                    type="submit"
                                    className="PreOrder-FormDiv7"
                                    style={{
                                      cursor: 'pointer',
                                      fontFamily: FontFamily['head'],
                                      backgroundColor: Color['darkColor'],
                                      color: Color['lightColor'],
                                    }}
                                    onClick={() => setStatus('Edit')}
                                  >
                                    Update Order
                                  </button>

                                  {balanceAmount === 0 &&
                                    (selectOptionName == 'Cash' ||
                                      selectOptionName == 'Credit' ||
                                      (selectOptionName == 'Card' &&
                                        FullPayment) ||
                                      (selectOptionName === 'UPI' &&
                                        selectedGateWayOptions === 'Default' &&
                                        selectedUPIOption != undefined)) && (
                                      <button
                                        type="submit"
                                        className="PreOrder-FormDiv7"
                                        style={{
                                          cursor: 'pointer',
                                          fontFamily: FontFamily['head'],
                                          backgroundColor: Color['darkColor'],
                                          color: Color['lightColor'],
                                        }}
                                        onClick={() => setStatus('Delivery')}
                                      >
                                        Delivery
                                      </button>
                                    )}
                                </div>

                                {PreOrderAdvance > 1 &&
                                  PreOrderAdvance != null &&
                                  !FullPayment &&
                                  PaymentOptions?.length > 1 && (
                                    <div
                                      className="PreOrder-FormDiv7"
                                      style={{
                                        cursor: 'pointer',
                                        fontFamily: FontFamily['head'],
                                        backgroundColor: Color['darkColor'],
                                        color: Color['lightColor'],
                                      }}
                                      onClick={() => {
                                        removestates();
                                      }}
                                    >
                                      Split Payment
                                    </div>
                                  )}
                              </div>
                              <div
                                className="PreOrder-FormDiv7"
                                style={{
                                  cursor: 'pointer',
                                  fontFamily: FontFamily['head'],
                                  backgroundColor: ' #ff7875',
                                }}
                                onClick={cancelEdit}
                              >
                                Cancel
                              </div>
                            </div>
                          ) : (
                            <div>
                              <>
                                <button
                                  type="submit"
                                  className="PreOrder-FormDiv7"
                                  style={{
                                    cursor: 'pointer',
                                    fontFamily: FontFamily['head'],
                                    backgroundColor: Color['darkColor'],
                                    color: Color['lightColor'],
                                  }}
                                >
                                  ₹ {CountUp}
                                  {/* <CountUp
                                    duration={0.4}
                                    className="counter"
                                    end={Math.round(PreOrderAdvance)}
                                  /> */}
                                </button>
                                {PreOrderAdvance > 1 &&
                                  PreOrderAdvance != null &&
                                  !FullPayment &&
                                  PaymentOptions?.length > 1 && (
                                    <div
                                      className="PreOrder-FormDiv7"
                                      style={{
                                        cursor: 'pointer',
                                        fontFamily: FontFamily['head'],
                                        backgroundColor: Color['darkColor'],
                                        color: Color['lightColor'],
                                      }}
                                      onClick={() => {
                                        removestates();
                                      }}
                                    >
                                      Split Payment
                                    </div>
                                  )}
                                <div
                                  className="PreOrder-FormDiv7"
                                  style={{
                                    cursor: 'pointer',
                                    fontFamily: FontFamily['head'],
                                    backgroundColor: ' #ff7875',
                                  }}
                                  onClick={() => {
                                    cancelEdit();
                                  }}
                                >
                                  Cancel
                                </div>
                              </>
                            </div>
                          )}
                        </Form>
                      </div>
                      <div></div>
                    </div>
                  )}

                  {PreOrderAdditem == 'AddItems' && (
                    <div>
                      <div className="ComboPreOrder-PendingDiv">
                        <Table
                          components={components}
                          rowClassName={() => 'editable-row'}
                          bordered
                          dataSource={ItemEditdata}
                          columns={columns}
                        />
                      </div>
                    </div>
                  )}
                </>
              )}

              {SelectedOption == 'Pending' && (
                <>
                  <Form
                    style={{ display: 'flex', gap: '0.5rem' }}
                    initialValues={{
                      FromDate: PreOrder_Pending_FromDate,
                      ToDate: PreOrder_Pending_ToDate,
                    }}
                  >
                    <div className="Pre-Order-Search">
                      <Search
                        placeholder="Search"
                        onSearch={Pending_onSearch}
                        onSearchChange={Pending_onSearchChange}
                      />
                    </div>

                    <div
                      style={{
                        display: 'flex',
                        gap: '0.5rem',
                        marginRight: '0.5rem',
                      }}
                    >
                      <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <p>From Date</p>
                        <Form.Item name="FromDate">
                          <DatePicker
                            defaultValue={
                              PreOrder_Pending_FromDate
                                ? dayjs(PreOrder_Pending_FromDate, 'DD-MM-YYYY')
                                : null
                            }
                            isOnChange={true}
                            onChange={onChange_Pending_FromDate}
                            value={
                              PreOrder_Pending_FromDate
                                ? dayjs(PreOrder_Pending_FromDate, 'DD-MM-YYYY')
                                : null
                            }
                            disabledDate={false}
                            format={'DD/MM/YYYY'}
                          />
                        </Form.Item>
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <p>To Date</p>
                        <Form.Item name="ToDate">
                          <DatePicker
                            defaultValue={
                              PreOrder_Pending_ToDate
                                ? dayjs(PreOrder_Pending_ToDate, 'DD-MM-YYYY')
                                : null
                            }
                            isOnChange={true}
                            onChange={onChange_Pending_ToDate}
                            value={
                              PreOrder_Pending_ToDate
                                ? dayjs(PreOrder_Pending_ToDate, 'DD-MM-YYYY')
                                : null
                            }
                            disabledDate={false}
                            format={'DD/MM/YYYY'}
                          />
                        </Form.Item>
                      </div>
                    </div>
                  </Form>
                  <div className="Pre-Order-PendingTable">
                    <Table
                      components={Pendingcomponents}
                      rowClassName={() => 'editable-row'}
                      bordered
                      dataSource={PendingData}
                      columns={Pendingcolumns}
                      size="small"
                    />
                  </div>
                </>
              )}

              {SelectedOption == 'History' && (
                <div className="ComboPreOrder-PendingDiv">
                  <>
                    <Form
                      style={{ display: 'flex', gap: '0.5rem' }}
                      initialValues={{
                        FromDate: PreOrder_History_FromDate,
                        ToDate: PreOrder_History_ToDate,
                      }}
                    >
                      <div className="Pre-Order-Search">
                        <Search
                          placeholder="Search"
                          onSearch={History_onSearch}
                          onSearchChange={History_onSearchChange}
                        />
                      </div>

                      <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <p>From Date</p>
                        <Form.Item name="FromDate">
                          <DatePicker
                            defaultValue={
                              PreOrder_History_FromDate
                                ? dayjs(PreOrder_History_FromDate, 'DD-MM-YYYY')
                                : null
                            }
                            isOnChange={true}
                            onChange={onChangeDate_History_FromDate}
                            value={
                              PreOrder_History_FromDate
                                ? dayjs(PreOrder_History_FromDate, 'DD-MM-YYYY')
                                : null
                            }
                            disabledDate={false}
                            format={'DD/MM/YYYY'}
                          />
                        </Form.Item>
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <p>To Date</p>
                        <Form.Item name="ToDate">
                          <DatePicker
                            defaultValue={
                              PreOrder_History_ToDate
                                ? dayjs(PreOrder_History_ToDate, 'DD-MM-YYYY')
                                : null
                            }
                            isOnChange={true}
                            onChange={onChangeDate_History_ToDate}
                            value={
                              PreOrder_History_ToDate
                                ? dayjs(PreOrder_History_ToDate, 'DD-MM-YYYY')
                                : null
                            }
                            disabledDate={false}
                            format={'DD/MM/YYYY'}
                          />
                        </Form.Item>
                      </div>
                    </Form>
                    <div className="Pre-Order-PendingTable">
                      <Table
                        columns={Hcolumns}
                        dataSource={HistoryData}
                        size="small"
                      />
                    </div>
                  </>
                </div>
              )}
            </div>
          </div>
        )}
        <Modal
          title={'Upload image & Message'}
          open={ShowDetails}
          onOk={OnOkView}
          onCancel={OnCancelView}
          width={700}
        >
          <div>
            <Form ref={ViewformRef} onFinish={OnOkView}>
              <div className="PreOrder-FormUploadImageDiv">
                <div>
                  <p>Upload Image</p>
                  <Imageupload
                    singleImage={true}
                    updateImageUrl={updateImageUrl}
                    ImageLink={ImageUrl}
                  />
                </div>
                <Form.Item
                  name="Message"
                  rules={[
                    {
                      pattern: /^(?!\s*$).+/,
                      message: 'Please Enter Message',
                    },
                    {
                      validator: async (_, value) => {
                        await validateSafeInput(value);
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <TextAreaInput
                    autoComplete="off"
                    label={<label>Message..</label>}
                    onChange={OnChangeMessage}
                    isOnChange={MessageModel ? true : false}
                    value={MessageModel}
                  />
                </Form.Item>
              </div>
            </Form>
          </div>
        </Modal>
        <Modal
          title={<h2 className="PreOrder-title">Customer Details</h2>}
          open={pendingCustomerView?.status === true}
          onCancel={() => {
            setPendingCustomerView({ Data: null, status: false });
          }}
          footer={false}
          width={700}
        >
          <div className="PreOrder-customer-details">
            {pendingCustomerView?.Data?.Address1 && (
              <div className="PreOrder-detail-item">
                Address1: {pendingCustomerView?.Data?.Address1}
              </div>
            )}
            {pendingCustomerView?.Data?.Address2 && (
              <div className="PreOrder-detail-item">
                Address2: {pendingCustomerView?.Data?.Address2}
              </div>
            )}
            {pendingCustomerView?.Data?.City && (
              <div className="PreOrder-detail-item">
                City: {pendingCustomerView?.Data?.City}
              </div>
            )}
            {pendingCustomerView?.Data?.CustSuppName && (
              <div className="PreOrder-detail-item">
                Customer: {pendingCustomerView?.Data?.CustSuppName}
              </div>
            )}
            {pendingCustomerView?.Data?.District && (
              <div className="PreOrder-detail-item">
                District: {pendingCustomerView?.Data?.District}
              </div>
            )}
            {pendingCustomerView?.Data?.Email && (
              <div className="PreOrder-detail-item">
                Email: {pendingCustomerView?.Data?.Email}
              </div>
            )}
            {pendingCustomerView?.Data?.MobileNo && (
              <div className="PreOrder-detail-item">
                Mobile No: {pendingCustomerView?.Data?.MobileNo}
              </div>
            )}
            {pendingCustomerView?.Data?.State && (
              <div className="PreOrder-detail-item">
                State: {pendingCustomerView?.Data?.State}
              </div>
            )}
            {pendingCustomerView?.Data?.ZipCode && (
              <div className="PreOrder-detail-item">
                Zip Code: {pendingCustomerView?.Data?.ZipCode}
              </div>
            )}
          </div>
        </Modal>

        <Modal
          title={<h2 className="PreOrder-title">Product Details</h2>}
          open={ModalProduct}
          onCancel={() => productModalCancel()}
          footer={false}
          width={700}
        >
          <div className="PreOrder-product-details">
            <Tables
              columns={Productcolumns}
              data={PendingOrderView}
              dataSource={PendingOrderView}
              pagination={false}
            />
          </div>
        </Modal>
        <DefaultModal
          open={UpiOpen}
          title="UPI PAYMENT"
          width={500}
          handleCancel={() => {
            Upimodel('Cancel');
          }}
          footer={false}
          children={
            <div style={{ overflow: 'scroll' }}>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'space-evenly',
                  alignItems: 'center',
                }}
              >
                <div>
                  <QrinScreen
                    Amount={PreOrderAdvance ? PreOrderAdvance : 0}
                    UpiId={UpiId}
                  />
                </div>

                <div>
                  <h1> RS :{PreOrderAdvance ? PreOrderAdvance : 0} </h1>
                </div>
              </div>

              <div className="sentok">
                {(selOption || SelCustId) && (
                  <div className="sentLink" onClick={onFinalSubmit}>
                    Sent Payment Link
                    <img
                      src={WpIcon}
                      alt="Your Alt Text"
                      style={{ width: '30px', height: '30px' }}
                    />
                  </div>
                )}

                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'row-reverse',
                    width: '100px',
                  }}
                >
                  <Buttons
                    buttonText="OK"
                    color="901D77"
                    icon={<ArrowRightOutlined />}
                    handleSubmit={() => {
                      Upimodel('Submit');
                    }}
                  />
                </div>
              </div>
            </div>
          }
        />

        {CreditCustomer?.model && (
          <div style={{ display: 'none' }}>
            <BsBillingCreditCustomer
              ModalCreditCustomer={CreditCustomer?.model}
              handlemodalclose={() => {
                handleCreditCustomer('Cancel');
              }}
              handleOk={() => {
                handleCreditCustomer('Submit');
              }}
            />
          </div>
        )}

        <Modal
          title={<h2 className="PreOrder-title">History Details</h2>}
          open={HistoryDetailsView?.status === true}
          onCancel={() => {
            setHistoryDetails({ Data: null, status: false });
          }}
          footer={false}
          width={900}
        >
          <div
            style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}
          >
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              <div
                className="PreOrder-customer-details"
                style={{ width: '100%', height: '150px', overflow: 'scroll' }}
              >
                <h2 className="PreOrder-History-title">Customer Details</h2>
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.Address1 && (
                  <div className="PreOrder-detail-item">
                    Address1:{' '}
                    {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.Address1}
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.Address2 && (
                  <div className="PreOrder-detail-item">
                    Address2:{' '}
                    {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.Address2}
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.City && (
                  <div className="PreOrder-detail-item">
                    City: {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.City}
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]
                  ?.CustSuppName && (
                  <div className="PreOrder-detail-item">
                    Customer:{' '}
                    {
                      HistoryDetailsView?.Data?.CustomerDetails?.[0]
                        ?.CustSuppName
                    }
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.District && (
                  <div className="PreOrder-detail-item">
                    District:{' '}
                    {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.District}
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.Email && (
                  <div className="PreOrder-detail-item">
                    Email:{' '}
                    {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.Email}
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.MobileNo && (
                  <div className="PreOrder-detail-item">
                    Mobile No:{' '}
                    {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.MobileNo}
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.State && (
                  <div className="PreOrder-detail-item">
                    State:{' '}
                    {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.State}
                  </div>
                )}
                {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.ZipCode && (
                  <div className="PreOrder-detail-item">
                    Zip Code:{' '}
                    {HistoryDetailsView?.Data?.CustomerDetails?.[0]?.ZipCode}
                  </div>
                )}
              </div>

              <div
                className="PreOrder-customer-details"
                style={{ width: '100%', height: '150px', overflow: 'scroll' }}
              >
                <h2 className="PreOrder-History-title">Payment Details</h2>
                {HistoryDetailsView?.Data?.OrderPaymentDtls?.[0]?.OrderId && (
                  <div className="PreOrder-detail-item">
                    OrderId:{' '}
                    {HistoryDetailsView?.Data?.OrderPaymentDtls?.[0]?.OrderId}
                  </div>
                )}
                {HistoryDetailsView?.Data?.OrderPaymentDtls?.[0]?.Amount && (
                  <div className="PreOrder-detail-item">
                    Amount:{' '}
                    {HistoryDetailsView?.Data?.OrderPaymentDtls?.[0]?.Amount}
                  </div>
                )}
                {HistoryDetailsView?.Data?.OrderPaymentDtls?.[0]
                  ?.PaymentTypeName && (
                  <div className="PreOrder-detail-item">
                    Payment Type Name:{' '}
                    {
                      HistoryDetailsView?.Data?.OrderPaymentDtls?.[0]
                        ?.PaymentTypeName
                    }
                  </div>
                )}
              </div>
            </div>
            <div
              className="PreOrder-product-details"
              style={{ width: '900px', height: '250px', overflow: 'scroll' }}
            >
              <h2 className="PreOrder-History-title">Product Details</h2>
              <Tables
                columns={Productcolumns}
                data={HistoryDetailsView?.Data?.productDetails}
                dataSource={HistoryDetailsView?.Data?.productDetails}
                pagination={true}
              />
            </div>
          </div>
        </Modal>
        {PrintOrderDetails?.length > 0 &&
          PrintOrderDetails?.[0]?.OrderDetails?.map((orderDetail, index) => (
            <div style={{ display: 'none' }}>
              <PaymentPdfBooking
                index={index}
                table2Data={orderDetail}
                singleData2={orderDetail?.productDetails}
                orderId={
                  orderDetail?.OrderId &&
                  extractLastNumberOrderId(
                    orderDetail?.OrderId,
                    orderDetail?.FYStatus
                  )
                }
                CreatedDate={orderDetail?.CreatedDate}
                PaymentStatus={PrintOrderDetails?.[0]?.PaymentOrderDtl}
                PreOrder={false}
                Preference={preferenceData}
              />
            </div>
          ))}
        {splitPayment && (
          <SplitPayment
            SplitPaymentModal={splitPayment}
            handlesplitpaymentclose={handlesplitpaymentclose}
            value={PreOrderAdvance}
            AddBookingDetails={AddBookingDetails}
            edit={Buttonicon}
            orderId={orderId}
            cancelEdit={cancelEdit}
            balanceAmount={balanceAmount}
            failedOrderData={failedOrderData}
          />
        )}

        {CancelModal && (
          <Modal
            title={<h2 className="PreOrder-title">Cancel Pre Booking</h2>}
            open={CancelModal}
            onCancel={() => setCancelModal(false)}
            footer={false}
            width={700}
          >
            <div className="PreOrder-cancel-details">
              {/* Summary Block */}
              <div className="summary-box">
                <div className="summary-row">
                  <span className="summary-label">Bill Amount:</span>
                  <span className="summary-value">
                    ₹ {PreOrderData?.NetAmount ?? 0}
                  </span>
                </div>
                <div className="summary-row">
                  <span className="summary-label">Advance Paid:</span>
                  <span className="summary-value">
                    ₹ {PreOrderData?.PaidAmount ?? 0}
                  </span>
                </div>
              </div>

              {/* Refund Amount Input */}
              <Form
                style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}
                ref={cancelformRef}
                onFinish={() => {
                  PreOrderCancel(PreOrderData);
                }}
              >
                <Form.Item
                  name="RefundAmount"
                  rules={[
                    {
                      required: true,
                      message: 'Please enter refund amount',
                    },
                    {
                      pattern: /^\d+(\.\d{1,2})?$/,
                      message: 'Only valid numbers allowed (max 2 decimals)',
                    },
                    {
                      validator: handlerefundvalidator,
                    },
                  ]}
                >
                  <InputField
                    field="RefundAmount"
                    autoComplete="off"
                    label={<label className="required">Refund Amount</label>}
                    maxLength={10}
                    fieldState={true}
                    value={PreOrderRefund}
                    fieldApi={true}
                    onChange={OnchangeRefund}
                    isOnChange={!!PreOrderRefund}
                    onKeyPress={(e) => {
                      const char = String.fromCharCode(e.charCode);
                      const isValid = /[0-9.]$/.test(char);
                      if (!isValid) e.preventDefault();
                      if (char === '.' && e.currentTarget.value.includes('.')) {
                        e.preventDefault();
                      }
                    }}
                  />
                </Form.Item>

                {/* Payment Method Dropdown */}
                <Form.Item
                  name="CancelPayOptions"
                  rules={[
                    {
                      required: true,
                      message: 'Please select a payment method',
                    },
                  ]}
                >
                  <DropDowns
                    options={PaymentOptions?.filter(
                      (option) =>
                        option.ModeName !== 'Credit' &&
                        option.ModeName !== 'Card'
                    )?.map((option) => ({
                      value: option.ModeId,
                      label: option.ModeName,
                    }))}
                    label={<label className="required">Payment Method</label>}
                    isOnchanges={!!CancelPaymentOption}
                    onChangeFunction={OnChangeCancelPaymentOption}
                    valueData={CancelPaymentOption}
                  />
                </Form.Item>

                <div
                  style={{
                    display: 'flex',
                    flexWrap: 'wrap',
                    justifyContent: 'end',
                    width: '100%',
                  }}
                >
                  <Buttons
                    buttonText="Refund"
                    color="901D77"
                    icon={<ArrowRightOutlined />}
                  />
                </div>
              </Form>
            </div>
          </Modal>
        )}
      </div>
    </>
  );
};

export default BSComboNavBarPreOrder;
