import React, {
  useState,
  useRef,
  useEffect,
  useCallback,
  useContext,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  Button,
  Form,
  Input,
  Table,
  Space,
  Select,
  Checkbox,
  AutoComplete,
  Switch,
  Tooltip,
  Popconfirm,
} from 'antd';
import { TiDelete } from 'react-icons/ti';
import { CiCalculator1 } from 'react-icons/ci';
import { Tables } from '../../../../Components/Tables/Table';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal';
import { DeleteFilled } from '@ant-design/icons';
import { Radio } from 'antd';
import moment from 'moment';
import FormHeader from '../../../PageComponents/FormHeader';
import {
  changeCustomerDelete,
  changeCustomerID,
  changeReorderHoldDetails,
  ChangeWSProduct,
  getSelectedFavItems,
  GlobalProductCategorie,
  getLayoutproductCard,
  GlobalProductSubCategorie,
  getAllCustomer,
  getCardDataWithoutSub,
  getCardDataWithoutSubmodule,
  changeSelectedCustId,
  changeSelectedOption,
  changeHoldOrderDtl,
  changeCombofocus,
  ChangeSelectedCustDisable,
  GlobalReorderHoldDetails,
  GlobalBookingType,
  GlobalEstimateBooking,
  GlobalSelProdWiseEst,
  changeSelProdWiseEst,
  changeEstimateBooking,
  changeOrderType,
  GlobalBookingTypeBoth,
  changeReorderProductDetails,
  ChangeOverAllDiscEstimate,
  ChangeOverAllDiscSales,
  PreferenceData,
  ChangeComboCarddata,
  getPreferenceData,
  getCustomerForHold,
  PostBlockSlots,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import { getTemplateData } from '../../../../Features/ThemeChange/ThemeChange';
import { DropDowns } from '../../../../Components/Forms/DropDown.jsx';
import { ArrowRightOutlined, CloseSquareFilled } from '@ant-design/icons';
import { InputField } from '../../../../Components/Forms/InputField';
import { Messages } from '../../../../Components/Notifications/Messages';
import Buttons from '../../../../Components/Forms/Buttons';
import ProductForm from '../../../../Pages/BookingScreen/Forms/QuickAdd/QuickAdd.jsx';
import {
  GlobalAddCustomerDetails,
  getAddCustomerDetails,
  postAddCustomerDetails,
  triggerCustomerRefresh,
} from '../../../../Features/BookingScreen/Customer/addCustomer';
import {
  extractLastNumberOrderId,
  getSession,
  validateSafeInput,
} from '../../../../Services/Others';
import { getExtTabledata } from '../../../../Features/ExteraCharges/ExtraCharges';
import {
  globalExtraChargesType,
  ChangeTotalAmount,
  globalExtraTotalAmount,
} from '../../../../Features/ExteraCharges/ExtraCharges.js';
import WeightScaleComp from '../../../../Components/WeightScale/weightScale.jsx';
import {
  gettinghold,
  puttinghold,
  changeholddata,
} from '../../../../Features/BookingScreen/HoldOption/HoldOption.js';
import {
  changeOrderCardDetails,
  GlobalOrderCardDetails,
  getProductsearch,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import { AiOutlineDownCircle, AiOutlineUpCircle } from 'react-icons/ai';
import '../../../../Styles/BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.scss';
import {
  IoCloseSharp,
  IoPersonAddSharp,
  IoSearchOutline,
} from 'react-icons/io5';
import { GrCheckboxSelected } from 'react-icons/gr';
import { BiCustomize } from 'react-icons/bi';
import { DatePicProd } from '../../../../Components/Forms/DatePickerProduct.jsx';
import {
  GlobalPreOrderList,
  GlobalpreOrderOpen,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import Imageupload from '../../../../Components/Forms/Upload.jsx';
import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import { getCombolist } from '../../../../Features/ComboMaster/ComboMaster.js';
import {
  ChangeFullFreeProductList,
  changeFullOfferAppliedProducts,
  changeLoyaltyConsumedQuantities,
} from '../../../../Features/Offer/Offernew/BookingOffernew.js';
import { v4 as uuidv4 } from 'uuid';
import { ApplicationPreferences } from '../../../../Features/BrachLogin/BranchLogin.js';
import { useDateStore } from '../../../../Features/BookingScreen/BookingData/DateStore.js';
import { FaEdit, FaMapMarkedAlt, FaTrash } from 'react-icons/fa';
import { MdHome, MdLocationOn } from 'react-icons/md';
import { RadioGrpButton } from '../../../../Components/Forms/RadioGroup.jsx';

const FeaturesFunctionalities = (props) => {
  const { closeModal = () => { } } = props;
  const applyOffer = useApplyOfferto_CardDetail();
  const EditableContext = React.createContext(null);
  const EditableContext1 = React.createContext(null);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const dispatch = useDispatch();
  const formRef = useRef();
  const formWsRef = useRef();
  const formRefExtraCharges = useRef();
  const ExtraChargesType = useSelector(globalExtraChargesType);
  const GlobalExtraCharge = useSelector(globalExtraTotalAmount);
  const ReorderHoldDetails = useSelector(GlobalReorderHoldDetails);
  const BookingType = useSelector(GlobalBookingType);
  const BookingTypeBoth = useSelector(GlobalBookingTypeBoth);
  const [dataSource, setDataSource] = useState(
    ExtraChargesType.filter((item) => item.ActiveStatus == 'A')
  );
  const [dataSource1, setDataSource1] = useState(
    ExtraChargesType.filter((item) => item.ActiveStatus == 'A')
  );
  const [ImageUrl, setImageUrl] = useState(null);
  const preOrder = useSelector(GlobalpreOrderOpen);
  const PreOrderList = useSelector(GlobalPreOrderList);
  const withoutPreOrderList = useSelector(GlobalOrderCardDetails);
  const PreferenceDatas = useSelector(PreferenceData);
  console.log(PreferenceDatas, 'PreferenceDatas');
  const CartOrderDetails = preOrder ? PreOrderList : withoutPreOrderList;
  const [InitialOutStandingType, setInitialOutStandingType] = useState(null);
  const [amountType, setAmountType] = useState('C');

  const templateData = useSelector(getTemplateData);
  const prodCat = useSelector(GlobalProductCategorie);
  const ProdSubCat = useSelector(GlobalProductSubCategorie);

  const GlobalAddCustomerDetails1 = useSelector(GlobalAddCustomerDetails);
  const GlobEstBooking = useSelector(GlobalEstimateBooking);
  const GlobProdwisedata = useSelector(GlobalSelProdWiseEst);

  const [hold, setHold] = useState(props.modalOpen);
  const [WeightScale, setWeightScale] = useState(props.WeightScale);
  const [WeightScale2, setWeightScale2] = useState(true);

  const [CusDetails, setCusDetails] = useState(false);
  const [zipCodeData, setZipCodeData] = useState(false);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [totalAmount, setTotalAmount] = useState(0);
  const [Tabledata, setTabledata] = useState();
  const [extdata, setExtdata] = useState([]);
  const [extdata1, setExtdata1] = useState([]);
  const [SelectData, setSelectData] = useState([]);

  const [SelectData2, setSelectData2] = useState([]);
  const [oldUserId, setoldUserId] = useState(null);
  const [CalcProductRate, setCalcProductRate] = useState();
  const [CalcProductWeight, setCalcProductWeight] = useState();

  const [WSProductList, setWSProductList] = useState([]);
  const [ProductValue, setProductValue] = useState();
  const [WSProductDataSource, setWSProductDataSource] = useState([]);
  const [WSProductRate, setWSProductRate] = useState(0);
  const [WSProductWeight, setWSProductWeight] = useState(0);
  const [WSTotalPrice, setWSTotalPrice] = useState(0);
  const [WSSelectedStockDetail, setWSSelectedStockDetail] = useState([]);
  const [WSSelectedOnekgProd, setWSSelectedOnekgProd] = useState([]);
  const [CalcPriceWeightOpen, setCalcPriceWeightOpen] = useState(false);
  const [wsport, setwsport] = useState(null);

  const [isOpen, setIsOpen] = useState(false);
  const [Searchopen, setSearchopen] = useState(false);

  const [gender, setGender] = useState('M');
  const [isSearching, setIsSearching] = useState(false);
  const [suggestionClicked, setSuggestionClicked] = useState(false);
  const [selectSearchDefaultValue, setselectSearchDefaultValue] = useState('');
  const [TableName, setTableName] = useState([]);
  const [Checkbox1, setCheckbox1] = useState(true);
  const [selectedProduct, setselectedProduct] = useState();

  const [inputValue, setInputValue] = useState('');
  const [suggestions, setSuggestions] = useState(['prematix', 'pr']);
  const [searchResults, setSearchResults] = useState([]);
  const [selectedSearchValue, setselectedSearchValue] = useState('CustMobile');

  const [selectedValue, setSelectedValue] = useState(null);
  const [offerType, setofferType] = useState('P');
  const [OfferValue, setOfferValue] = useState(null);
  const [Maritalstatus, setMaritalstatus] = useState('N');
  const [allowDecimal, setAllowDecimal] = useState(false);
  const [DobDate, setDobDate] = useState();
  const [SpouseDobDate, setSpouseDobDate] = useState();
  const [anniversaryDate, setanniversaryDate] = useState();
  const [customerAddress, setCustomerAddress] = useState();
  const appPreferences = useSelector(ApplicationPreferences);
  const { selectedDate } = useDateStore();
  const salespagefields = appPreferences?.find(
    (pref) => pref?.PreferredCatName === 'Sales Page Fields'
  )?.PreferenceCatDetails;
  const AvailableDate = salespagefields?.find(
    (type) =>
      type?.PreferredSubCatName?.toLowerCase() === 'available date' &&
      type?.PreferredStatus === 'Y'
  );
  const commonModulePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Common Module'
  )?.PreferenceCatDetails;
  const sportsAppPreference = commonModulePreference?.find(
    (preference) =>
      preference?.PreferredSubCatName === 'SportsApp' &&
      preference?.PreferredStatus === 'Y'
  );
  const [addressPreview, setAddressPreview] = useState([]);
  const [addressesList, setAddressesList] = useState([]);
  const [addressTypes, setAddressTypes] = useState({});
  const [editingIndex, setEditingIndex] = useState(null);

  const yesNoOptions = [
    { value: 'A', label: 'Active' },
    { value: 'D', label: 'Deactive' },
  ];
  useEffect(() => {
    fetchdata();
    getPreference();
  }, []);
  useEffect(() => {
    getPreference();
  }, [PreferenceDatas]);

  useEffect(() => {
    hold ? dispatch(changeCombofocus(true)) : dispatch(changeCombofocus(false));
  }, [hold]);
  useEffect(() => {
    WeightScale
      ? dispatch(changeCombofocus(true))
      : dispatch(changeCombofocus(false));
  }, [WeightScale]);
  useEffect(() => {
    WeightScale2
      ? dispatch(changeCombofocus(true))
      : dispatch(changeCombofocus(false));
  }, [WeightScale2]);

  useEffect(() => {
    if (preOrder) {
      if (GlobalExtraCharge?.length > 0) {
        if (
          GlobalExtraCharge?.[0]?.ProdId === null ||
          (GlobalExtraCharge?.[0]?.ProdId === '' &&
            GlobalExtraCharge?.[0]?.InwardDtlId === '')
        ) {
          setCheckbox1(true);
        } else {
          setCheckbox1(false);
        }
      } else {
        setCheckbox1(true);
      }
    }
  }, [preOrder]);

  useEffect(() => {
    if (props?.mobileNo && String(props?.mobileNo)?.length === 10) {
      handleSelectSuggestion(String(props?.mobileNo));
    }
  }, [props?.mobileNo]);

  useEffect(() => {
    const { addcustomer, ExtraCharges, QuickAdd, reprint } = props;

    if (addcustomer || ExtraCharges || QuickAdd || reprint) {
      dispatch(changeCombofocus(true));
    } else {
      dispatch(changeCombofocus(false));
    }
  }, [props.addcustomer, props.ExtraCharges, props.QuickAdd, props.reprint]);

  useEffect(() => {
    formRef.current?.getFieldsValue()?.Zip === undefined &&
      setZipCodeData(false);
  }, [inputValue]);

  let CustIdForDynamicChange = ` ${' '}${suggestions?.[0]?.CustId?.match(/(.+)-\d+$/)?.[1]}-`;
  const statusFormatters = (index) => {
    const rows = [...TableName];
    const remove = rows?.filter(
      (e) => !(e.ProdName === index?.ProdName && e.UniqueId === index?.UniqueId)
    );

    setTableName(remove);
  };

  const fetchdata = async () => {
    let res = await dispatch(
      getAllCustomer({ CompId: CompId, AppId: AppId, branchId: BranchId })
    ).unwrap();

    if (res?.data?.statusCode == 1) {
      setSuggestions(res?.data?.data);
    }
  };

  const handleSelectSuggestion = (suggestion) => {
    checkExistingCustomer(
      suggestions.filter((a) => a[selectedSearchValue] === suggestion)?.[0]
        ?.CustMobile || suggestion
    );
    setInputValue(
      suggestions.filter((a) => a[selectedSearchValue] === suggestion)?.[0]
        ?.CustMobile || suggestion
    );
  };

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

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

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

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

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }

  const options = suggestions
    ? suggestions
      ?.filter((item) =>
        selectedSearchValue === 'CustName' ? item.CustName !== null : item
      )
      .map((item) => ({
        value: item?.CustMobile,
        label:
          selectedSearchValue === 'CustMobile'
            ? `${item?.CustMobile} - ${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`
            : selectedSearchValue === 'CustId'
              ? `${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}${item?.CustName ? ' - ' : ''} ${item?.CustName ? item?.CustName : ''} - ${item?.CustMobile}`
              : selectedSearchValue === 'CustName' &&
              item?.CustName !== null &&
              `${item?.CustName ? item?.CustName : ''} ${item?.CustName ? ' - ' : ''} ${item?.CustMobile} - ${'Id:' + item?.CustId?.match(/-(\d+)$/)?.[1]}`,
        CustMobile: item?.CustMobile,
        CustId: item?.CustId?.match(/-(\d+)$/)?.[1],
        CustName: item?.CustName,
      }))
    : GlobalAddCustomerDetails1?.map((item) => ({
      value: item.CustMobile,
      label: `${item?.CustName} ${item?.CustMobile}`,
      CustMobile: item?.CustMobile,
      CustId: item?.CustId,
      CustName: item?.CustName,
    }));
  const handleYesOrNoChange = (value) => {
    setSelectedValue(value);
    formRef.current?.setFieldsValue({ OfferActiveStatus: value });
  };
  const columnshold = [
    {
      title: 'Order.Id',
      key: 'productDetails',
      dataIndex: 'productDetails',
      align: 'center',
      width: '150px',
      onCell: (record) => {
        const productDetails = record?.productDetails;
        const Combodtl =
          record?.productDetails?.[0]?.comboDtl?.[0]?.ComboInwardDetails?.[0]
            ?.ComboDetails;

        return {
          onClick: () => {
            HoldPutfun(productDetails, record, Combodtl);
          },
        };
      },
      render: (productDetails, record) => (
        <a
          style={{ color: 'black' }}
          onClick={() => HoldPutfun(productDetails, record)}
        >
          {record?.OrderId &&
            extractLastNumberOrderId(record?.OrderId, record?.FYStatus)}
        </a>
      ),
    },
    {
      title: 'Order Type',
      key: 'productDetails',
      dataIndex: 'productDetails',
      align: 'center',
      width: '150px',
      onCell: (record) => {
        const productDetails = record?.productDetails;
        const Combodtl =
          record?.productDetails?.[0]?.comboDtl?.[0]?.ComboInwardDetails?.[0]
            ?.ComboDetails;

        return {
          onClick: () => {
            HoldPutfun(productDetails, record, Combodtl);
          },
        };
      },
      render: (productDetails, record) => (
        <a
          style={{ color: 'black' }}
          onClick={() => HoldPutfun(productDetails, record)}
        >
          {record?.OrderType == 'E' ? 'Estimate' : 'Sales'}
        </a>
      ),
    },
    ...(sportsAppPreference
      ? [
        {
          title: 'Subcategory',
          key: 'productDetails',
          dataIndex: 'productDetails',
          align: 'center',
          width: '150px',
          onCell: (record) => {
            const productDetails = record?.productDetails;
            const Combodtl =
              record?.productDetails?.[0]?.comboDtl?.[0]
                ?.ComboInwardDetails?.[0]?.ComboDetails;

            return {
              onClick: () => {
                HoldPutfun(productDetails, record, Combodtl);
              },
            };
          },
          render: (productDetails, record) => (
            <a
              style={{ color: 'black' }}
              onClick={() => HoldPutfun(productDetails, record)}
            >
              {record?.productDetails?.[0]?.ProdSubCatName}
            </a>
          ),
        },
      ]
      : []),
    {
      title: 'Orders',
      key: 'productDetails',
      dataIndex: 'productDetails',
      width: '150px',
      onCell: (record) => {
        const productDetails = record?.productDetails;
        return {
          onClick: () => {
            HoldPutfun(productDetails, record);
          },
        };
      },
      render: (productDetails, record) => (
        <a
          style={{ color: 'black' }}
          onClick={() => HoldPutfun(productDetails, record)}
        >
          {productDetails?.length > 0 &&
            productDetails
              ?.map(
                (item) =>
                  item.ProdName +
                  ('(' + item.Size + '' + ' ' + item.UomName) +
                  ')'
              )
              .join(',')}
        </a>
      ),
    },
    {
      title: 'Customer Name/Mobile.No/Cust.Id',
      key: 'sno',
      dataIndex: 'CustSuppName',
      width: '150px',
      onCell: (record) => {
        const productDetails = record?.productDetails;
        return {
          onClick: () => {
            HoldPutfun(productDetails, record);
          },
          style: { cursor: 'pointer' },
        };
      },
      render: (text, record) =>
        record?.CustSuppName || record?.CustSuppMobileNo || '-',
    },
    {
      title: 'Delete',
      key: 'sno',
      width: '150px',
      render: (record) => (
        <a className="BSC1Payment-HoldModel-delete">
          <TiDelete
            style={{ cursor: 'pointer' }}
            onClick={() => statusFormatter(record)}
          />
        </a>
      ),
    },
  ];
  const WSStockColumns = [
    {
      title: 'Stock Quantity',
      dataIndex: 'BalanceQty',
      key: 'BalanceQty',
      align: 'right',
      onCell: (record) => {
        return {
          onClick: () => {
            GetProductRate(record);
          },
        };
      },
      render: (text, row) => (
        <a style={{ color: 'black', width: '200px' }}>
          {row.BalanceQty ? row.BalanceQty : 'Stock Not Maintained'}
        </a>
      ),
    },
    {
      title: 'Amount',
      dataIndex: 'SellPrice',
      key: 'SellPrice',
      align: 'right',
      onCell: (record) => {
        return {
          onClick: () => {
            GetProductRate(record);
          },
        };
      },
    },
  ];
  useEffect(() => {
    setWeightScale(props.WeightScale);
  }, [props.WeightScale]);
  // useEffect(() => {
  //   if (!props.addcustomer) {
  //     formRef.current?.resetFields();
  //     setZipCodeData(false);
  //   }
  // }, [props.addcustomer]);
  const ExtTabledata = async () => {
    const data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    await dispatch(getExtTabledata(data)).unwrap();
  };
  useEffect(() => {
    setDataSource(
      ExtraChargesType.filter(
        (item) => item.ActiveStatus == 'A' && item?.PackageAvilable != 'Y'
      )
    );
    setDataSource1(
      ExtraChargesType.filter(
        (item) => item.ActiveStatus == 'A' && item?.PackageAvilable != 'Y'
      )
    );
  }, [ExtraChargesType]);

  useEffect(() => {
    if (props.ExtraCharges == true) {
      if (ExtraChargesType?.length === 0) {
        ExtTabledata();
      }
    }
  }, [props.ExtraCharges]);

  useEffect(() => {
    setTotalAmount(
      extdata.reduce((sum, item) => sum + item.QTY * item.Price, 0)
    );
  }, [extdata]);

  useEffect(() => {
    setselectedProduct();

    if (GlobalExtraCharge?.length === 0) {
      setTableName([]);
      setExtdata([]);
      setSelectData([]);
    }
  }, [Checkbox1]);
  useEffect(() => {
    if (GlobalExtraCharge?.length > 0) {
      if (
        GlobalExtraCharge?.[0]?.ProdId === null ||
        (GlobalExtraCharge?.[0]?.ProdId === '' &&
          GlobalExtraCharge?.[0]?.InwardDtlId === '')
      ) {
        let globalexdata = GlobalExtraCharge?.map((item) => {
          let mappedItem = {
            UniqueId: item?.ExtraChargeId,
            QTY: item?.OrderQty,
            Price: item?.OrderRate,
            ProdId: null,
            InwardDtlId: null,
            ExtraChargeType: item?.ExtraChargeType,
            TotalAmt: item?.TotalAmt,
            TaxAmt: item?.TaxAmt,
            ProdName: item?.ProdName,
            TaxId: item?.TaxId,
            TaxPercentage: item?.TaxPercentage,
            SinglePc: null,
          };

          // Add SalesId only if it exists
          if (item?.SalesId) {
            mappedItem['SalesId'] = item?.SalesId;
          }

          return mappedItem;
        });
        setExtdata(globalexdata);
        setSelectData(globalexdata?.map((item) => item.UniqueId));
        let mergedArray = mergearrays(dataSource, globalexdata);
        setDataSource(mergedArray);
      } else {
        let globalexdata = GlobalExtraCharge?.map((item) => {
          let mappedItem = {
            UniqueId: item?.ExtraChargeId,
            QTY: item?.OrderQty,
            Price: item?.OrderRate * item?.OrderQty,
            ProdId: item?.ProdId,
            InwardDtlId: item?.InwardDtlId,
            ProdName: item?.ProdName,
            ExtraChargeType: item?.ExtraChargeType,
            TotalAmt: item?.TotalAmt,
            TaxAmt: item?.TaxAmt,
            BookingTypeName: item?.BookingTypeName,
            BookingType: item?.BookingType,
            TaxId: item?.TaxId,
            TaxPercentage: item?.TaxPercentage,
            SinglePc: item?.SinglePc,
          };

          // Add SalesId only if it exists
          if (item?.SalesId) {
            mappedItem['SalesId'] = item?.SalesId;
          }

          return mappedItem;
        });

        setCheckbox1(false);
        setTableName(globalexdata);
        setSelectData([]);
      }
    } else {
      setTableName([]);
      setExtdata([]);
      setSelectData([]);
    }
  }, [GlobalExtraCharge]);
  function mergearrays(array1, array2) {
    let mergedArray = [];

    // Merge array1 into mergedArray
    mergedArray = array1.slice();

    // Merge array2 into mergedArray, ensuring unique objects based on UniqueId
    for (let item2 of array2) {
      let existingItemIndex = mergedArray.findIndex(
        (item) => item.UniqueId === item2.UniqueId
      );
      if (existingItemIndex !== -1) {
        // If item2 exists in mergedArray, update its properties
        mergedArray[existingItemIndex] = {
          ...mergedArray[existingItemIndex],
          ...item2,
        };
      } else {
        // If item2 doesn't exist in mergedArray, add it
        mergedArray.push(item2);
      }
    }
    return mergedArray;
  }
  useEffect(
    () => {
      if (WSProductWeight > 0 && WSProductRate > 0) {
        WSTotalCalculation();
      }
    },
    [WSProductWeight],
    [WSProductRate]
  );

  const addeddata = (record) => {
    if (SelectData.includes(record.UniqueId)) {
      if (totalAmount > 0) {
        setTotalAmount(totalAmount - record.Price * parseInt(record.QTY));
        const remove = extdata?.filter(
          (item) => item.UniqueId !== record.UniqueId
        );
        setExtdata(remove);
        setSelectData(SelectData?.filter((a) => a != record.UniqueId));
      }
    } else {
      setSelectData([...SelectData, record.UniqueId]);
      setTotalAmount(totalAmount + record.Price * parseInt(record.QTY));
      let data = {
        ExtraChargeType: record.ExtraChargeType,
        Price: record.Price,
        QTY: parseInt(record.QTY),
        UniqueId: record.UniqueId,
        TotalAmt: parseFloat(
          formatAmount(parseInt(record.Price) * parseInt(record.QTY))
        ),
        TaxAmt: formatAmount(
          ((record.Price * record.TaxPercentage) /
            (100 + record.TaxPercentage)) *
          record.QTY
        ),
        TaxId: record.TaxId,
        TaxPercentage: record.TaxPercentage,
      };
      setExtdata([data, ...extdata]);
    }
  };
  const formatAmount = (value) => {
    return allowDecimal
      ? parseFloat(value || 0).toFixed(2)
      : Math.round(value || 0);
  };
  const addeddata1 = (record) => {
    // Check if the UniqueId of the record is included in SelectData2
    if (SelectData2.includes(record.UniqueId)) {
      // If included, remove the record from extdata1 and update SelectData2
      const remove = extdata1?.filter(
        (item) => item.UniqueId !== record.UniqueId
      );
      setExtdata1(remove);
      setSelectData2(SelectData2?.filter((a) => a !== record.UniqueId));
    } else {
      // If not included, check for duplicates in extdata1 based on ExtraChargeType and UniqueId
      const isDuplicate = TableName?.some(
        (item) =>
          item.InwardDtlId +
          ' ' +
          item.BookingTypeName +
          ' ' +
          item.SinglePc ===
          selectedProduct && item.UniqueId === record.UniqueId
      );

      if (!isDuplicate) {
        // If not a duplicate, add the UniqueId to SelectData2 and construct data object
        setSelectData2([...SelectData2, record.UniqueId]);

        let data = {
          ExtraChargeType: record.ExtraChargeType,
          Price: record.Price,
          QTY: parseInt(record.QTY),
          UniqueId: record.UniqueId,
          TotalAmt: parseFloat(
            formatAmount(parseInt(record.Price) * parseInt(record.QTY))
          ),
          TaxAmt: formatAmount(
            ((record.Price * record.TaxPercentage) /
              (100 + record.TaxPercentage)) *
            record.QTY
          ),
          TaxId: record?.TaxId,
          TaxPercentage: record.TaxPercentage,
          SinglePc: record?.SinglePc,
        };

        // Add the constructed data object to extdata1
        setExtdata1([data, ...extdata1]);
      }
      // If it's a duplicate, you can handle it accordingly (e.g., show a message)
      else {
        setMessageType('error');
        setMessageData('Data Already Exists');
      }
    }
  };
  const ProfuctName = CartOrderDetails?.find(
    (e) =>
      e.InwardDtlId + ' ' + e.BookingTypeName + ' ' + e.SinglePc ==
      selectedProduct
  );

  const producttName = ProfuctName?.ProdName;

  const globalamount1 = () => {
    if (selectedProduct) {
      setSelectData2([]);
      setExtdata1([]);

      const newArray = extdata1?.map((obj) => ({
        ...obj,
        ProdName:
          ProfuctName?.ProdVariantName !== 'Variant 1'
            ? `${ProfuctName?.ProdName} (${ProfuctName.Size} ${ProfuctName.UomName}) (${ProfuctName.ProdVariantName}${BookingTypeBoth ? ` (${ProfuctName?.BookingTypeName})` : ''})`
            : `${ProfuctName?.ProdName} (${ProfuctName.Size} ${ProfuctName.UomName}) ${BookingTypeBoth ? ` (${ProfuctName?.BookingTypeName})` : ''}`,
        InwardDtlId: ProfuctName?.InwardDtlId,
        ProdId: ProfuctName?.ProdId,
        BookingTypeName: ProfuctName?.BookingTypeName,
        BookingType: ProfuctName?.BookingType,
        // booking type no came from global booking
        SinglePc: ProfuctName?.SinglePc,
      }));
      setTableName([...TableName, ...newArray]);
    }
  };
  const globalamount = async (data) => {
    setSelectData2([]);
    setTableName([]);
    props.ExtraChargesCancle();
    const modifiedData = data?.map(
      ({ UniqueId, ExtraChargeType, Price, QTY, ...rest }) => ({
        ...rest,
        ExtraChargeId: UniqueId,
        ExtraChargeType: ExtraChargeType,
        ProdId: null,
        InwardDtlId: '',
        OrderRate: Price,
        OrderQty: QTY,
        OrderType:
          GlobEstBooking === 'OvrAllEst' ? 'E' : preOrder ? 'PRE' : 'S',
        SinglePc: null,
        BookingTypeName: rest?.BookingTypeName,
        BookingType: rest?.BookingType,
      })
    );

    await dispatch(ChangeTotalAmount(modifiedData));
  };
  const globalamount2 = async (data) => {
    setTotalAmount(0);
    props.ExtraChargesCancle();
    setDataSource(
      ExtraChargesType.filter(
        (item) => item.ActiveStatus == 'A' && item?.PackageAvilable != 'Y'
      )
    );

    const modifiedData = data?.map(
      ({ UniqueId, ExtraChargeType, QTY, Price, ProdName, ...item }) => ({
        ...item,
        SinglePc: item?.SinglePc ? item?.SinglePc : 'N',
        ExtraChargeId: UniqueId,
        ExtraChargeType: ExtraChargeType,
        OrderQty: QTY,
        OrderRate: Price / QTY,
        ProdName: ProdName,
        OrderType:
          GlobEstBooking === 'OvrAllEst'
            ? 'E'
            : GlobEstBooking === 'ParEst'
              ? GlobProdwisedata?.includes(item?.InwardDtlId)
                ? 'E'
                : 'S'
              : preOrder
                ? 'PRE'
                : 'S',
        Size: item?.Size,
        UomName: item?.UomName,
        ProdVariantName: item?.ProdVariantName,
        BookingTypeName: item?.BookingTypeName,
        BookingType: item?.BookingType,
      })
    );
    await dispatch(ChangeTotalAmount(modifiedData));
  };

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

  const onChangeProduct = (e) => {
    formRefExtraCharges.current.setFieldsValue({
      Extracharges: e,
    });
    setselectedProduct(e);
  };

  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}
            type="number"
            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 EditableCell1 = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing1, setEditing1] = useState(false);
    const inputRef1 = useRef(null);
    const form1 = useContext(EditableContext1);

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

    const toggleEdit1 = () => {
      setEditing1(!editing1);
      form1.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };

    const save1 = async () => {
      try {
        const values = await form1.validateFields();
        toggleEdit1();
        handleSave1({
          ...record,
          ...values,
        });
      } catch (errInfo) { }
    };

    let childNode = children;

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

    return <td {...restProps}>{childNode}</td>;
  };
  const calculateTaxAmount = (record) => {
    return (
      ((record.Price * record.TaxPercentage) / (100 + record.TaxPercentage)) *
      record.QTY
    );
  };
  const WithoutTaxAmountTaxAmount = (record) => {
    return (
      record.Price * record.QTY -
      ((record.Price * record.TaxPercentage) / (100 + record.TaxPercentage)) *
      record.QTY
    );
  };
  const WithTaxAmountTaxAmount = (record) => {
    return record.Price * record.QTY;
  };
  const WithoutTaxAmountTaxAmount2 = (record) => {
    return record.Price - record.TaxAmt;
  };

  const defaultColumns = [
    {
      title: 'ExtraCharge Type',
      key: 'ExtraChargeType',
      dataIndex: 'ExtraChargeType',
      width: '200px',
    },
    {
      title: 'QTY',
      key: 'QTY',
      dataIndex: 'QTY',
      align: 'right',
      width: '100px',
      editable: Checkbox1 ? true : false,
    },
    {
      title: 'Price',
      key: 'Price',
      dataIndex: 'Price',
      align: 'right',
      width: '100px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {formatAmount(WithoutTaxAmountTaxAmount(record))}
        </a>
      ),
    },
    {
      title: 'Tax Amt',
      key: 'TotalTaxAmt',
      dataIndex: 'TotalTaxAmt',
      align: 'right',
      width: '100px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {formatAmount(calculateTaxAmount(record))}
        </a>
      ),
    },
    {
      title: 'Amt',
      key: 'Price',
      dataIndex: 'Price',
      align: 'right',
      width: '100px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {formatAmount(WithTaxAmountTaxAmount(record))}
        </a>
      ),
    },
    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      width: '80px',
      render: (text, record) => (
        <Space size="middle">
          <Checkbox
            checked={SelectData?.includes(record.UniqueId) ? true : false}
            onClick={() => addeddata(record)}
            disabled={
              Object.keys(ReorderHoldDetails).length !== 0 &&
                BookingType === 'Dine In' &&
                GlobalExtraCharge.some(
                  (item) => item.ExtraChargeId === record.UniqueId
                )
                ? true
                : false
            }
          />
        </Space>
      ),
    },
  ];
  const defaultColumns1 = [
    {
      title: 'ExtraCharge Type',
      key: 'ExtraChargeType',
      dataIndex: 'ExtraChargeType',
      width: '200px',
    },
    {
      title: 'QTY',
      key: 'QTY',
      dataIndex: 'QTY',
      align: 'right',
      width: '100px',
      // editable: Checkbox1 ? true : false,
    },
    {
      title: 'Price1',
      key: 'Price',
      dataIndex: 'Price',
      align: 'right',
      width: '100px',
      render: (text, record) => {
        return (
          <a style={{ color: 'black' }}>
            {formatAmount(WithoutTaxAmountTaxAmount(record))}
          </a>
        );
      },
    },

    {
      title: 'Tax Amt',
      key: 'TotalTaxAmt',
      dataIndex: 'TotalTaxAmt',
      align: 'right',
      width: '100px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {formatAmount(calculateTaxAmount(record))}
        </a>
      ),
    },
    {
      title: 'Amt',
      key: 'Price',
      dataIndex: 'Price',
      align: 'right',
      width: '100px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {formatAmount(WithTaxAmountTaxAmount(record))}
        </a>
      ),
    },
    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      width: '80px',
      render: (text, record) => (
        <Space size="middle">
          <Checkbox
            checked={SelectData2?.includes(record.UniqueId) ? true : false}
            onClick={() => addeddata1(record)}
          />
        </Space>
      ),
    },
  ];

  const handleSave = (row) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.UniqueId === item.UniqueId);
    const item = newData[index];
    if (SelectData?.includes(row.UniqueId)) {
      const isDuplicate = extdata?.some(
        (item) => item.UniqueId === row.UniqueId
      );

      const remove = extdata?.filter((item) => item.UniqueId !== row.UniqueId);

      let data = {
        ExtraChargeType: row.ExtraChargeType,
        Price: row.Price,
        QTY: parseInt(row.QTY),
        TaxAmt: formatAmount(
          ((row.Price * row.TaxPercentage) / (100 + row.TaxPercentage)) *
          row.QTY
        ),
        TotalAmt: row.Price * row.QTY,
        // ((row.Price * row.TaxPercentage) / (100 + row.TaxPercentage) *row.QTY ).toFixed(2),
        TaxId: row.TaxId,
        TaxPercentage: row.TaxPercentage,
        UniqueId: row.UniqueId,
      };
      setExtdata([...remove, data]);
    }
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    // let vv={...newData,
    //   TotalTaxAmt:(row.Price * row.TaxPercentage) / (100 + row.TaxPercentage) * parseInt(row.QTY)

    // }
    const newArray = newData.map((obj) => ({
      ...obj,
      // TotalTaxAmt: parseFloat((obj.Price * obj.TaxPercentage) / (100 + obj.TaxPercentage) * parseInt(obj.QTY)).toFixed(2)
    }));

    setDataSource(newArray);
  };
  const handleSave1 = (row) => {
    const newData = [...TableName];
    const index = newData.findIndex(
      (item) => row.UniqueId === item.UniqueId && row.ProdName === item.ProdName
    );
    const item = newData[index];
    const tax = dataSource?.find((e) => e.UniqueId == item.UniqueId);
    let Taxx = tax?.TaxPercentage;
    let Price2 = tax?.Price;

    const hasUniqueId = TableName.some(
      (item) => item.UniqueId === row.UniqueId
    );
    if (hasUniqueId) {
      let updateQty = [...TableName];

      updateQty[index] = {
        ProdName: row.ProdName,
        ExtraChargeType: row.ExtraChargeType,
        Price: Price2 * row.QTY,
        QTY: parseInt(row.QTY),
        ProdId: row.ProdId,
        InwardDtlId: row.InwardDtlId,
        UniqueId: row.UniqueId,
        //((record.Price * record.TaxPercentage) / (100 + record.TaxPercentage)) *
        TaxAmt: formatAmount(
          ((Price2 * Taxx) / (100 + Taxx)) * parseInt(row.QTY)
        ),
        TotalAmt: formatAmount(parseInt(Price2) * parseInt(row.QTY)),
        BookingTypeName: row.BookingTypeName,
      };
      setTableName(updateQty);
    }
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const components1 = {
    body: {
      row: EditableRow1,
      cell: EditableCell1,
    },
  };
  const ExtraChargescolumns = [
    {
      title: 'Sl.No',
      key: 'sno',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{index + 1}</a>
      ),
      align: 'center',
      width: '150px',
    },
    {
      title: 'Product Name',
      dataIndex: 'ProdName',
      key: 'ProdName',
      width: '150px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {record?.ProdName + '(' + record?.BookingTypeName + ')'}
        </a>
      ),
    },
    {
      title: 'EXTRACHARGE TYPE',
      dataIndex: 'ExtraChargeType',
      key: 'ExtraChargeType',
      align: 'right',
      width: '150px',
    },
    {
      title: 'Price',
      dataIndex: 'Price',
      key: 'Price',
      align: 'right',
      width: '150px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {formatAmount(WithoutTaxAmountTaxAmount2(record))}
        </a>
      ),
    },
    {
      title: 'QTY',
      dataIndex: 'QTY',
      key: 'QTY',
      align: 'center',
      width: '200px',
      editable: true,
    },
    {
      title: ' Tax AMT',
      dataIndex: 'TaxAmt',
      key: 'ProdId',
      align: 'right',
      width: '150px',
      render: (text) => <span>{safeRound(text)}</span>,
    },
    {
      title: 'AMT',
      dataIndex: 'TotalAmt',
      key: 'ProdId',
      align: 'right',
      width: '150px',
      render: (amt) => <span>{safeRound(amt)}</span>,
    },
    {
      title: 'Action',
      dataIndex: 'Action',
      key: 'Action',
      align: 'center',
      render: (_, record, index) => (
        <Space size="middle">
          <a>
            {Object.keys(ReorderHoldDetails).length !== 0 &&
              BookingType === 'Dine In' &&
              GlobalExtraCharge?.some(
                (item) =>
                  item.ExtraChargeId === record.UniqueId &&
                  item.InwardDtlId === record.InwardDtlId
              ) ? (
              <DeleteFilled
                style={{
                  color: '#FF4D4F',
                  opacity: '0.4',
                }}
              />
            ) : (
              <DeleteFilled
                style={{
                  color: '#FF4D4F',
                }}
                onClick={() => statusFormatters(record, index)}
              />
            )}
          </a>
        </Space>
      ),
    },
  ];
  const columns = defaultColumns?.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  const columns1 = ExtraChargescolumns?.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave1,
      }),
    };
  });

  const handleToggle = () => {
    setIsOpen(!isOpen);
  };

  useEffect(() => {
    setHold(props.modalOpen);
  }, [props.modalOpen]);

  useEffect(() => {
    if (hold == true) {
      holding();
      dispatch(changeCustomerDelete('Deleted'));
    }
  }, [hold]);

  useEffect(() => {
    if (customerAddress && customerAddress[0]?.CustomerAddressDtl) {
      const addressList = customerAddress[0].CustomerAddressDtl.map((addr) => ({
        ActiveStatus: addr.ActiveStatus,
        Address1: addr.Address1 || '',
        Address2: addr.Address2 || '',
        Zip: addr.Zip || '',
        AddId: addr.AddId || '',
        City: addr.City || '',
        Dist: addr.Dist || '',
        State: addr.State || '',
        Latitude: addr.Latitude || '',
        Longitude: addr.Longitude || '',
        AddressType: addr.AddressType || '',
      }));

      console.log(addressList, 'ddddddddddddd');
      const prefilled = {};
      addressList.forEach((addr, idx) => {
        switch (addr.AddressType) {
          case 'Both Address':
            prefilled[idx] = [
              'Delivery Address',
              'Billing Address',
              'Both Address',
            ];
            break;
          case 'Delivery Address':
            prefilled[idx] = ['Delivery Address'];
            break;
          case 'Billing Address':
            prefilled[idx] = ['Billing Address'];
            break;
          default:
            prefilled[idx] = [];
            break;
        }
      });
      setAddressTypes(prefilled);
      setAddressesList(addressList);
      setAddressPreview(addressList);
      // setZipCodeData(true);
    }
  }, [customerAddress]);

  const pinCodeChange = (e) => {
    const value = e.target.value;
    if (value.length === 6) {
      getPincodeValues(value);
    } else {
      setZipCodeData(false);
    }
  };

  const getPincodeValues = async (pinCode) => {
    try {
      const res = await fetch(
        `https://api.postalpincode.in/pincode/${pinCode}`
      );
      const response = await res.json();

      if (response[0]?.Status === 'Success') {
        const postOffice = response[0].PostOffice?.[0];
        setZipCodeData(true);
        formRef.current?.setFieldsValue({
          City: postOffice?.Block || postOffice?.Name || '',
          Dist: postOffice?.District || '',
          State: postOffice?.State || '',
        });
      } else {
        setZipCodeData(false);
        formRef.current?.setFieldsValue({
          City: '',
          Dist: '',
          State: '',
        });
      }
    } catch (error) {
      console.error('Error fetching pincode info:', error);
      setZipCodeData(false);
    }
  };

  // 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'],
  //     });
  //   } else {
  //     setZipCodeData(false);
  //   }
  // };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const customerData = async (e) => {
    let data = {
      MobileNo: e,
      CompId: getSession('CompId'),
      BranchId: getSession('BranchId'),
      AppId: getSession('AppId'),
    };

    let response = await dispatch(getAddCustomerDetails(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setoldUserId(response?.data?.data?.[0]?.UserId);
      setCustomerAddress(response?.data?.data);
      if (response?.data?.data?.[0]?.Zip) {
        getPincodeValues(response?.data?.data?.[0].Zip);
      }
      if (response?.data?.data?.[0]?.OfferActiveStatus) {
        setSelectedValue(response?.data?.data?.[0]?.OfferActiveStatus);
      }
      if (response?.data?.data?.[0]?.OfferType) {
        setofferType(response?.data?.data?.[0]?.OfferType);
      }
      if (response?.data?.data?.[0]?.MarriedStatus) {
        setMaritalstatus(response?.data?.data?.[0]?.MarriedStatus);
      }
      if (response?.data?.data?.[0]?.SpouseDOB) {
        setSpouseDobDate(response?.data?.data?.[0]?.SpouseDOB);
      }
      if (response?.data?.data?.[0]?.AnniversaryDate) {
        setanniversaryDate(response?.data?.data?.[0]?.AnniversaryDate);
      }
      if (response?.data?.data?.[0]?.CustDOB) {
        setDobDate(response?.data?.data?.[0]?.CustDOB);
      }
      if (
        response?.data?.data?.[0]?.OfferValue == 0 ||
        response?.data?.data?.[0]?.OfferValue
      ) {
        setOfferValue(
          response?.data?.data?.[0]?.OfferValue
            ? response?.data?.data?.[0]?.OfferValue
            : 0
        );
      }
      formRef.current?.setFieldsValue(response?.data?.data?.[0]);

      if (response?.data?.data?.[0]?.InitialOutStanding) {
        setInitialOutStandingType(
          response?.data?.data?.[0]?.InitialOutStanding
        );
      }
    } else if (response?.data?.statusCode === 0) {
      setoldUserId(null);
      !Searchopen && formRef.current?.resetFields();
      !Searchopen && formRef.current?.setFieldsValue({ CustMobile: e });
      Searchopen && setCusDetails(false);
    }
  };

  const handleSubmit = async (value) => {
    let PostData = value;
    PostData['CompId'] = getSession('CompId');
    PostData['BranchId'] = getSession('BranchId');
    PostData['AppId'] = getSession('AppId');
    PostData['CreatedBy'] = getSession('UserId');
    // PostData['Document'] = ImageUrl ? ImageUrl : null;
    PostData['CustomerProfile'] = ImageUrl ? ImageUrl : null;
    PostData['InitialOutStanding'] = parseInt(value?.OutStandingAmount);
    if (oldUserId) {
      PostData['UserId'] = oldUserId;
    }
    if (offerType) {
      PostData['OfferType'] = offerType;
    }
    if (Maritalstatus == 'N') {
      PostData['MarriedStatus'] = 'N';
      PostData['CustDOB'] = DobDate;
    }
    if (Maritalstatus == 'Y') {
      PostData['MarriedStatus'] = 'Y';
      PostData['CustDOB'] = DobDate;
      PostData['SpouseDOB'] = SpouseDobDate;
      PostData['AnniversaryDate'] = anniversaryDate;
    }
    const addedAddresses = addressesList || [];
    const validAddresses = addedAddresses?.filter(
      (addr) => addr?.Address1 && addr?.Zip
    );

    PostData['CustomerAddressDtl'] = validAddresses;

    let response = await dispatch(postAddCustomerDetails(PostData)).unwrap();

    if (response?.data?.statusCode == 1) {
      fetchdata();
      dispatch(changeSelectedOption(null));
      dispatch(
        changeCustomerID(
          response?.data?.CustomerDetails?.[
          response?.data?.CustomerDetails.length - 1
          ]
        )
      );
      dispatch(
        changeSelectedCustId(response?.data?.CustomerDetails?.[0]?.CustId)
      );
      setMessageType('success');
      setMessageData('Customer Added Successfully');
      setInputValue('');
      setoldUserId(null);
      dispatch(triggerCustomerRefresh());
      formRef.current?.resetFields();
      props.handleAddCustomerCancel();
    } else {
      setMessageType('error');
      setMessageData(response?.data?.response);
    }
    setIsOpen(false);
    setSearchopen(false);
    setCusDetails(false);
    setselectedSearchValue('CustMobile');
  };

  const checkExistingCustomer = (value) => {
    if (!isNaN(value)) {
      if (value?.length == 10) {
        customerData(value);
        setCusDetails(true);
      } else {
        setCusDetails(false);
      }
    } else {
      if (value?.length == 50) {
        customerData(value);
        setCusDetails(true);
      } else {
        setCusDetails(false);
      }
    }
  };

  const holding = async () => {
    const data = { CompId: CompId, BranchId: BranchId, AppId: AppId };
    let response = await dispatch(gettinghold(data)).unwrap();
    if (response?.data?.statusCode == 1) {
      let modifiedData = response?.data?.data?.map((item) => {
        return {
          ...item,
          productDetails: item.productDetails.map((product) => {
            // Clone the product to avoid modifying the original object
            let newProduct = { ...product };

            if (product.Type === 'P') {
              if (product.SinglePc === 'Y') {
                newProduct.UomName = 'PCS';
                newProduct.MRP = newProduct.OrderRate;
              }
            } else {
              newProduct.ProdName = newProduct.ProdName;
              newProduct.Size = 1;
              newProduct.UomName = 'Combo';
              newProduct.MRP = newProduct.OrderRate;
            }

            return newProduct; // Return the modified product
          }),
        };
      });

      setTabledata(modifiedData);
    }
  };

  const statusFormatter = async (row) => {
    let orderListIds = [];
    orderListIds.push(row.OrderId);

    let putData = { OrderId: orderListIds };
    let response = await dispatch(puttinghold(putData)).unwrap();

    const extractedData = row?.productDetails?.map((prod) => ({
      ProdId: prod.ProdId,
      InwardDtlId: prod.InwardDtlId,
      SinglePc: prod.SinglePc,
      Qty: prod.OrderQty,
      Date: prod?.BookingDate,
    }));
    let BlockPostdata = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      Status: 'UnBlock',
      CreatedBy: UserId,
      ProductList: extractedData,
    };
    await dispatch(PostBlockSlots(BlockPostdata)).unwrap();

    if (response?.data?.statusCode == 1) {
      setMessageType('success');
      setMessageData(response?.data?.response);
      let holdingData = await dispatch(
        gettinghold({ CompId: CompId, BranchId: BranchId, AppId: AppId })
      ).unwrap();
      if (holdingData?.data?.statusCode === 1) {
        setTabledata(holdingData?.data?.data);
        dispatch(changeholddata(holdingData?.data?.data));
      } else {
        // props.handleHoldCancel();
        props?.closeModal();
        setHold(false);
        const dataValue = { CompId: CompId, BranchId: BranchId, AppId: AppId };
        let responseValue = await dispatch(gettinghold(dataValue)).unwrap();
        if (responseValue?.data?.statusCode == 1) {
          dispatch(changeholddata(responseValue?.data?.data));
          getstockbadge();
          Combocarddata();
        } else {
          dispatch(changeholddata([]));
        }
      }
      getstockbadge();
      Combocarddata();
    }
  };
  const HoldPutfun = async (a, b) => {
    const updated = a?.map((item) => ({
      ...item,
      Offer: item?.OfferAmt,
      localId: uuidv4(),
      OfferMode: item?.OfferMode ? item?.OfferMode?.trim() : null,
      VariantAvailableFrom: item?.AvailableFrom || null,
      VariantAvailableTo: item?.AvailableTo || null,
      // TotalAmt: formatAmount((item.TotalAmt - item.OfferValue)),
    }));
    b?.RefDetails?.[0]?.FreeProdList &&
      dispatch(ChangeFullFreeProductList(b?.RefDetails[0]?.FreeProdList));
    b?.RefDetails?.[0]?.OfferAppliedProductList &&
      dispatch(
        changeFullOfferAppliedProducts(
          b?.RefDetails[0]?.OfferAppliedProductList
        )
      );

    const loyaltyFreeProductOfferApplied =
      b?.RefDetails?.[0]?.OfferAppliedProductList?.filter(
        (off) =>
          off?.FreeProductsList?.OfferMode === 'L' &&
          off?.TableUniqueName === 'FreeProduct'
      );

    let res = await dispatch(
      getCustomerForHold({
        CompId: CompId,
        AppId: AppId,
        branchId: BranchId,
        OrderId: b?.OrderId,
      })
    ).unwrap();
    if (res?.data?.statusCode == 1) {
      let custdetail = res?.data?.data?.find(
        (item) => item.CustId === b.CustSuppId
      );
      if (custdetail !== undefined) {
        let data = {
          CustId: custdetail?.CustId,
          CustName: custdetail?.CustName,
          label: custdetail?.CustName
            ? custdetail?.CustName
            : custdetail?.CustMobile,
          value: custdetail?.CustMobile,
          LoyaltyPointsDetail: custdetail?.LoyaltyPointsDetail,
          TotalLoyaltyPoints: custdetail?.TotalLoyaltyPoints,
        };
        await dispatch(changeSelectedOption(data));
        await dispatch(ChangeSelectedCustDisable(true));
        if (loyaltyFreeProductOfferApplied?.length > 0) {
          const loyaltyProdQuantities = {};

          loyaltyFreeProductOfferApplied.forEach((off) => {
            const freeProdDtls = off?.FreeProductsList;
            const freeProdOfferId =
              freeProdDtls?.ProdVariantDetails?.[0]?.StockDetails?.[0]
                ?.ProdOfferId;

            const key = [
              freeProdDtls?.OfferId,
              freeProdDtls?.FreeProdId,
              freeProdDtls?.FreeProdVariantName,
              freeProdOfferId,
            ].join('|');

            loyaltyProdQuantities[key] = freeProdDtls?.FreeQty || 0;
          });
          if (Object.keys(loyaltyProdQuantities).length > 0) {
            dispatch(changeLoyaltyConsumedQuantities(loyaltyProdQuantities));
          }

          console.log(loyaltyProdQuantities, 'loyaltyProdQuantities');
        }
      }
    }

    let temp = a
      ?.filter((item) => item.OrderType === 'E')
      .map((item) => item.InwardDtlId + ' ' + item.BookingTypeName);
    await dispatch(changeSelProdWiseEst(temp));
    if (b.OrderType == 'E') {
      await dispatch(changeEstimateBooking('OvrAllEst'));
      await dispatch(ChangeOverAllDiscEstimate(parseFloat(b.OverallDisc)));
      await dispatch(changeOrderCardDetails(updated));
    } else {
      await dispatch(changeEstimateBooking('Sales'));
      await dispatch(ChangeOverAllDiscSales(parseFloat(b.OverallDisc)));
      const salesOffer = templateData?.BookingNavbar?.[1]?.some(
        (item) => item?.OptionName === 'Offer'
      );
      const preferenceOffer =
        PreferenceDatas?.[0]?.['SettingDtlDetails']?.find(
          (item) => item.SettingIdName === 'Offer'
        )?.SettingValue === 'Y';
      // if (salesOffer && preferenceOffer) {
      //   await applyOffer(a, b.OrderOfferDetails);
      // }
      // else
      // {
      await dispatch(changeOrderCardDetails(updated));
      // }
    }
    await dispatch(changeOrderType('Hold'));
    await dispatch(changeHoldOrderDtl(true));
    await dispatch(changeReorderHoldDetails(b));
    await dispatch(changeReorderProductDetails(b?.productDetails));
    await dispatch(changeSelectedCustId(b?.CustSuppId));
    await dispatch(ChangeTotalAmount(b?.ExtraChargeDetails));
    setHold(false);
    // props.handleHoldCancel();
    props?.closeModal();
  };

  const removeAll = async () => {
    let data = [];
    Tabledata?.map((item) => {
      data?.push(item.OrderId);
    });
    let putData = { OrderId: data };
    clearall(putData);
  };

  const clearall = async (data) => {
    let response = await dispatch(puttinghold(data)).unwrap();

    const allProducts = Tabledata.flatMap((row) =>
      row?.productDetails?.map((prod) => ({
        ProdId: prod.ProdId,
        InwardDtlId: prod.InwardDtlId,
        SinglePc: prod.SinglePc,
        Qty: prod.OrderQty,
        Date: row?.SalesDate,
      }))
    );

    const BlockPostdata = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      Status: 'UnBlock',
      CreatedBy: UserId,
      ProductList: allProducts,
    };
    await dispatch(PostBlockSlots(BlockPostdata)).unwrap();

    if (response?.data?.statusCode == 1) {
      setMessageType('success');
      setMessageData(response?.data?.response);

      // props.handleHoldCancel();
      props?.closeModal();
      setHold(false);
      const dataValue = { CompId: CompId, BranchId: BranchId, AppId: AppId };
      let responseValue = await dispatch(gettinghold(dataValue)).unwrap();
      if (responseValue?.data?.statusCode == 1) {
        dispatch(changeholddata(responseValue?.data?.data));
        getstockbadge();
        Combocarddata();
      } else {
        dispatch(changeholddata([]));
        getstockbadge();
        Combocarddata();
      }
      dispatch(triggerCustomerRefresh());
      dispatch(changeSelectedOption(null));
    }
  };
  const setWsport = async (e) => {
    setwsport(e);
  };

  const myfun = async (e) => {
    setWSProductWeight(e);
    formWsRef.current?.setFieldsValue({ WSProductWeight: e });
  };
  const WSProductSelect = (data) => {
    formWsRef.current.resetFields(['CalcProductRate']);
    setCalcProductWeight();
    setCalcProductRate();
    formWsRef.current.resetFields(['CalcProductWeight', 'CalcProductRate']);
    setProductValue(data);
    let ProdNamedata = WSProductList?.find((item) => item.ProdName === data);
    let OneKgProd = ProdNamedata?.ProductDetail?.find(
      (item) =>
        (item?.UomName?.toLowerCase() === 'KGS'?.toLowerCase() ||
          item?.UomName?.toLowerCase() === 'KG'?.toLowerCase()) &&
        item?.Size === 1
    );
    setWSSelectedOnekgProd(OneKgProd);
    setWSProductDataSource(OneKgProd?.ProdVariantDetails?.[0]?.StockDetails);
    if (OneKgProd?.ProdVariantDetails?.[0]?.StockDetails?.length === 1) {
      GetProductRate(OneKgProd?.ProdVariantDetails?.[0]?.StockDetails?.[0]);
    }
  };
  const WSProductChange = async (data) => {
    formWsRef.current.resetFields([
      'WSProductWeight',
      'WSProductRate',
      'WSTotalPrice',
    ]);
    setWSProductRate(0);
    setWSProductWeight(0);
    setWSTotalPrice(0);
    setWSProductDataSource([]);
    setProductValue(data);
    if (data?.length > 2) {
      let ProductList = await dispatch(
        getProductsearch({
          CompId: CompId,
          BranchId: BranchId,
          AppId: AppId,
          ProdName: data,
        })
      ).unwrap();
      if (ProductList?.data?.statusCode == 1) {
        setWSProductList(ProductList?.data?.data);
      }
    }
  };
  const GetProductRate = (data) => {
    setWSSelectedStockDetail(data);
    setWSProductRate(data?.SellPrice);
    formWsRef.current?.setFieldsValue({ WSProductRate: data?.SellPrice });
  };

  const WSTotalCalculation = () => {
    let pricepergram = WSProductRate / 1000;
    let total = formatAmount(parseFloat(WSProductWeight) * 1000 * pricepergram);

    setWSTotalPrice(total);
    formWsRef.current?.setFieldsValue({ WSTotalPrice: total });
  };
  const onFinish = async () => {
    let data = {
      Type: WSProductList?.[0]?.Type,
      OverallQuantity: WSProductList?.[0]?.OverAllQty,
      ActiveStatus: WSSelectedOnekgProd?.ActiveStatus,
      AvailableFrom: WSSelectedOnekgProd?.AvailableFrom,
      AvailableTo: WSSelectedOnekgProd?.AvailableTo,
      Cess: WSSelectedOnekgProd?.Cess,
      ExpDate: WSSelectedStockDetail?.ExpDate,
      HSNCode: WSSelectedOnekgProd?.HSNCode,
      ManufDate: WSSelectedStockDetail?.ManufDate,
      OpeningQty: WSSelectedOnekgProd?.OpeningQty,
      ProdType: WSProductList?.[0]?.ProdType,
      PartNumber: WSSelectedOnekgProd?.PartNumber,
      ProdId: WSSelectedOnekgProd?.ProdId,
      ProdLogo: WSSelectedOnekgProd?.ProdLogo,
      ProdName: WSSelectedOnekgProd?.ProdName,
      QRCode: WSSelectedOnekgProd?.QRCode,
      QtyBasedPrice: WSSelectedOnekgProd?.QtyBasedPrice,
      Rack: WSSelectedOnekgProd?.Rack,
      Size: parseFloat(WSProductWeight).toFixed(3),
      StockAvailable: WSSelectedOnekgProd?.StockAvailable,
      TaxId: WSSelectedOnekgProd?.TaxId,
      TaxPercentage: WSSelectedOnekgProd?.TaxPercentage,
      TaxName: WSSelectedOnekgProd?.TaxIdName,
      UniqueId: WSSelectedOnekgProd?.UniqueId,
      UomName: WSSelectedOnekgProd?.UomName,
      BalanceQty: WSSelectedStockDetail?.BalanceQty,
      BatchRef: WSSelectedStockDetail?.BatchRef,
      InwardDate: WSSelectedStockDetail?.InwardDate,
      InwardDtlId: WSSelectedStockDetail?.InwardDtlId,
      InwardId: WSSelectedStockDetail?.InwardId,
      MRP: WSSelectedStockDetail?.MRP,
      Offer: WSSelectedStockDetail?.OfferPrice,
      SellPrice: WSSelectedStockDetail?.SellPrice,
      ProdVariantName: 'Variant1',
      OrderRate: Math.round(WSTotalPrice),
      SuppId: WSSelectedStockDetail?.SuppId,
      SuppName: WSSelectedStockDetail?.SuppName,
      OrderQty: WSProductWeight,
    };

    if (WSTotalPrice > 0) {
      await dispatch(ChangeWSProduct(data));
      WSModalPortclose();
    } else {
      WSModalPortclose();
      setMessageType('error');
      setMessageData('Total is not calculated');
    }
  };
  const WSModalPortclose = () => {
    setWeightScale2(false);

    setWSProductWeight(0);
    formWsRef.current?.resetFields();

    setTimeout(() => {
      WSModalClose();
      // setwsport(null)
    }, 20);
  };
  const WSModalClose = () => {
    setWeightScale2(true);

    setWSProductList([]);
    setProductValue();
    setWSProductDataSource([]);
    setWSProductRate(0);
    setWSProductWeight(0);
    setWSTotalPrice(0);
    setWSSelectedStockDetail([]);
    setWSSelectedOnekgProd([]);
    setCalcProductWeight();
    setCalcProductRate();
    formWsRef.current?.resetFields();
    setWeightScale(false);
    if (props.handleWeightScaleCancel) {
      props.handleWeightScaleCancel();
    }
  };

  const CalculateWeight = async (e) => {
    if (WSSelectedOnekgProd && ProductValue) {
      setCalcProductRate(e?.target?.value);
      let tempCalcProductWeight = (e.target.value / WSProductRate).toFixed(3);

      setCalcProductWeight(parseFloat(tempCalcProductWeight));
      formWsRef.current?.setFieldsValue({
        CalcProductWeight: tempCalcProductWeight,
      });
    }
  };
  const CalculateWeightOpen = () => {
    setCalcPriceWeightOpen(!CalcPriceWeightOpen);
    setCalcProductWeight();
    setCalcProductRate();
    formWsRef.current.resetFields(['CalcProductWeight', 'CalcProductRate']);
  };
  const HandleProductName = (_, value) => {
    return new Promise((resolve, reject) => {
      if (WSSelectedOnekgProd && ProductValue) {
        resolve();
      } else {
        reject('Please Select Product');
      }
    });
  };

  const HandleCloseModal = () => {
    props.handleAddCustomerCancel();
    setInputValue('');
    setCusDetails(false);
    setselectedSearchValue('CustMobile');
    setSearchopen(false);
    setIsOpen(false);
  };

  const getstockbadge = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ...(AvailableDate && selectedDate
        ? {
          fromDate: selectedDate?.[0],
          toDate: selectedDate?.[1],
        }
        : {}),
    };
    await dispatch(getSelectedFavItems(data)).unwrap();

    let data1 = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ProdSubCat: ProdSubCat,
      ...(AvailableDate && selectedDate
        ? {
          fromDate: selectedDate?.[0],
          toDate: selectedDate?.[1],
        }
        : {}),
    };

    let data2 = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      prodCat: prodCat,
      ...(AvailableDate && selectedDate
        ? {
          fromDate: selectedDate?.[0],
          toDate: selectedDate?.[1],
        }
        : {}),
    };

    if (
      templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      ) &&
      ProdSubCat
    ) {
      await dispatch(getLayoutproductCard(data1)).unwrap();
    } else if (
      !templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      )
    ) {
      await dispatch(getCardDataWithoutSubmodule(data2)).unwrap();
    } else {
      await dispatch(getCardDataWithoutSub(data2)).unwrap();
    }
  };

  const Combocarddata = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ActiveStatus: 'A',
    };

    let response = await dispatch(getCombolist(data)).unwrap();
    let datas = response?.data?.data;
    await dispatch(ChangeComboCarddata(datas));
  };

  const HandleSearch = () => {
    setSearchopen(!Searchopen);
    setselectedSearchValue('CustMobile');
    setInputValue('');
    setCusDetails(false);
    setIsOpen(false);
    setselectSearchDefaultValue();
    formRef.current?.resetFields();
    Searchopen == true && setCusDetails(false);
  };

  const handleRadioChange = (event) => {
    setselectedSearchValue(event.target.value);
    event.target.value === 'CustName' ? setInputValue('') : setInputValue('');
    setIsOpen(false);
    setCusDetails(false);
    event.target.value === 'CustId' && setInputValue(CustIdForDynamicChange);
    setselectSearchDefaultValue();
    formRef.current?.resetFields();
  };
  const validateEmail = (_, value) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!value || emailRegex.test(value)) {
      return Promise.resolve();
    }
    return Promise.reject('Invalid email address');
  };
  const ClearMobileInput = () => {
    setInputValue('');
    setIsOpen(false);
    setCusDetails(false);
    formRef.current?.resetFields();
  };
  const handleCustomerSelectChange = (value, option) => {
    handleSelectSuggestion(value);
    setZipCodeData(false);
    setIsOpen(false);
    setselectSearchDefaultValue(
      option[selectedSearchValue] !== null
        ? option[selectedSearchValue]
        : option?.CustMobile
    );
  };
  const handleSearchInputChange = (inputValue) => {
    handleSelectSuggestion(inputValue);
  };
  const Onchangeoffertype = (a) => {
    setofferType(a);
    // dispatch(changeSetup_OfferType(a))
  };

  const Handleoffervalue = (e) => {
    formRef.current?.setFieldsValue({ OfferValue: e?.target?.value });
    setOfferValue(e?.target?.value);
    // dispatch(changeSetup_OfferValue(e?.target?.value))
  };
  const onchangeStatus = (e) => {
    setMaritalstatus(e?.target?.value);
  };

  // const dobchange=(e)
  const dobchange = async (date, dateString) => {
    if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      // formRef.current?.setFieldsValue({ ManufDate: Date1 })
      await setDobDate(Date1);
    }
  };
  const spousedobchange = async (date, dateString) => {
    if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      // formRef.current?.setFieldsValue({ ManufDate: Date1 })
      await setSpouseDobDate(Date1);
    }
  };
  const anniversaryDatechange = async (date, dateString) => {
    if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      // formRef.current?.setFieldsValue({ ManufDate: Date1 })
      await setanniversaryDate(Date1);
    }
  };

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

  const deliveryOptions = [
    'Delivery Address',
    'Billing Address',
    'Both Address',
  ];

  const handleAddOrUpdateAddress = () => {
    const currentFormValues = formRef.current?.getFieldsValue() || {};

    if (!currentFormValues?.Address1 || !currentFormValues?.Zip) {
      setMessageType('error');
      setMessageData('Please enter Address Line1 and Zipcode before adding');
      return;
    }
    const selectedAddressType =
      editingIndex !== null
        ? addressTypes[editingIndex] || []
        : addressTypes[Object.keys(addressTypes).length - 1] || [];

    let addressType = '';
    if (selectedAddressType.includes('Both Address')) {
      addressType = 'Both Address';
    } else if (
      selectedAddressType.includes('Delivery Address') &&
      selectedAddressType.includes('Billing Address')
    ) {
      addressType = 'Both Address';
    } else if (selectedAddressType.includes('Delivery Address')) {
      addressType = 'Delivery Address';
    } else if (selectedAddressType.includes('Billing Address')) {
      addressType = 'Billing Address';
    }
    const newAddress = {
      AddressType: addressType,
      Address1: currentFormValues?.Address1,
      Address2: currentFormValues?.Address2 || '',
      Zip: currentFormValues?.Zip,
      City: currentFormValues?.City || '',
      Dist: currentFormValues?.Dist || '',
      State: currentFormValues?.State || '',
      Latitude: currentFormValues?.Latitude || '',
      Longitude: currentFormValues?.Longitude || '',
    };

    if (editingIndex !== null) {
      // 🛠️ Update existing address
      setAddressesList((prev) => {
        const updated = [...prev];
        updated[editingIndex] = newAddress;
        setAddressPreview(updated);
        return updated;
      });

      setEditingIndex(null);
      setMessageType('success');
      setMessageData('Address updated successfully!');
    } else {
      // ➕ Add new address
      setAddressesList((prev) => {
        const updated = [...prev, newAddress];
        setAddressPreview(updated);
        return updated;
      });

      setMessageType('success');
      setMessageData('Address added successfully!');
    }

    // 🧹 Clear form
    formRef.current?.setFieldsValue({
      Address1: '',
      AddressType: '',
      Address2: '',
      Zip: '',
      City: '',
      Dist: '',
      State: '',
      Latitude: '',
      Longitude: '',
    });

    setZipCodeData(false);
  };

  const handleAddressTypeChange = (index, type, checked) => {
    setAddressTypes((prev) => {
      const updated = { ...prev };
      let currentTypes = [...(updated[index] || [])];

      if (type === 'Both Address') {
        if (checked) {
          currentTypes = [
            'Delivery Address',
            'Billing Address',
            'Both Address',
          ];
          // Clear other addresses when Both Address is selected
          Object.keys(updated).forEach((i) => {
            if (parseInt(i) !== index) {
              updated[i] = [];
            }
          });
        } else {
          currentTypes = [];
        }
      } else {
        if (checked) {
          if (!currentTypes.includes(type)) {
            currentTypes.push(type);
          }
          // If both Delivery and Billing are selected, add Both Address
          if (
            currentTypes.includes('Delivery Address') &&
            currentTypes.includes('Billing Address')
          ) {
            currentTypes.push('Both Address');
          }
          // Clear same type from other addresses
          Object.keys(updated).forEach((i) => {
            if (parseInt(i) !== index) {
              updated[i] = (updated[i] || []).filter(
                (opt) => opt !== type && opt !== 'Both Address'
              );
            }
          });
        } else {
          currentTypes = currentTypes.filter(
            (t) => t !== type && t !== 'Both Address'
          );
        }
      }

      updated[index] = currentTypes;

      // Update addresses list
      setAddressesList((prev) => {
        const newList = prev.map((addr, i) => {
          const opts = updated[i] || [];
          let addressType = '';

          if (opts.includes('Both Address')) addressType = 'Both Address';
          else if (opts.includes('Delivery Address'))
            addressType = 'Delivery Address';
          else if (opts.includes('Billing Address'))
            addressType = 'Billing Address';

          return { ...addr, AddressType: addressType };
        });

        setAddressPreview(newList);
        return newList;
      });

      return updated;
    });
  };

  const handleEditAddress = (index) => {
    const addrToEdit = addressPreview[index];

    formRef.current.setFieldsValue({
      AddId: addrToEdit.AddId,
      AddressType: addrToEdit.AddressType,
      Address1: addrToEdit.Address1,
      Address2: addrToEdit.Address2,
      Zip: addrToEdit.Zip,
      City: addrToEdit.City,
      Dist: addrToEdit.Dist,
      State: addrToEdit.State,
      Latitude: addrToEdit.Latitude,
      Longitude: addrToEdit.Longitude,
    });
    if (addrToEdit.Zip) {
      setZipCodeData(true);
    }

    setEditingIndex(index);

    // Scroll to and focus Address1 input
    setTimeout(() => {
      const addressForm = document.querySelector('.subinputForm');
      const address1Input = document.querySelector('input[id*="Address1"]');

      if (addressForm) {
        addressForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }

      if (address1Input) {
        address1Input.focus();
      }
    }, 100);
  };

  // const handleRemoveAddress = (index) => {
  //   setAddressPreview((prev) => prev.filter((_, i) => i !== index));
  //   setAddressesList((prev) => prev.filter((_, i) => i !== index));

  //   setNewAddress((prev) => prev.filter((_, i) => i !== index));
  //   setAddressTypes((prev) => {
  //     const updated = { ...prev };
  //     delete updated[index];
  //     return updated;
  //   });
  // };

  const handleRemoveAddress = (index) => {
    setAddressPreview((prev) =>
      prev.map((item, i) =>
        i === index ? { ...item, ActiveStatus: 'D' } : item
      )
    );
    setAddressesList((prev) =>
      prev.map((item, i) =>
        i === index ? { ...item, ActiveStatus: 'D' } : item
      )
    );
    setNewAddress((prev) =>
      prev.map((item, i) =>
        i === index ? { ...item, ActiveStatus: 'D' } : item
      )
    );
  };

  return (
    <div>
      <div className="BSBilling7-icon-flex">
        <DefaultModal
          title={
            <div className="Holdmodel-title">
              <FormHeader title={'Holding Orders'} />
            </div>
          }
          open={hold}
          width={900}
          footer={null}
          children={
            <div>
              <Button
                className="BSC1Payment-HoldModel-cancleall"
                type="primary"
                danger
                onClick={(e) => {
                  e?.stopPropagation();
                  removeAll();
                }}
              // onClick={() => statusFormatter(record,index)}
              >
                Clear All
              </Button>

              <div className="BSC1Payment-Tablediv">
                <Tables
                  columns={columnshold}
                  data={Tabledata}
                  dataSource={Tabledata}
                />
              </div>
            </div>
          }
          handleCancel={props.handleHoldCancel}
        />
      </div>

      <div className="BSBilling7-icon-flex">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <DefaultModal
          width={650}
          className={'AddCustomerModal'}
          title={
            <div className="Holdmodel-title">
              <FormHeader
                title={Searchopen ? 'Search Customer' : 'Add Customer'}
              />
              {Searchopen && (
                <div
                  style={{
                    display: 'flex',
                    columnGap: '0.7rem',
                    flexWrap: 'wrap',
                  }}
                >
                  <label
                    htmlFor="CustMobile"
                    className="search-addcustomer-inputlabel"
                    style={{
                      backgroundColor:
                        selectedSearchValue === 'CustMobile' && '#1292EE',
                      color: selectedSearchValue === 'CustMobile' && '#fff',
                    }}
                  >
                    <input
                      onChange={handleRadioChange}
                      type="radio"
                      value={'CustMobile'}
                      name="search"
                      id="CustMobile"
                      checked={selectedSearchValue === 'CustMobile'}
                    />
                    Mobile
                  </label>
                  <label
                    htmlFor="CustName"
                    className="search-addcustomer-inputlabel"
                    style={{
                      backgroundColor:
                        selectedSearchValue === 'CustName' && '#1292EE',
                      color: selectedSearchValue === 'CustName' && '#fff',
                    }}
                  >
                    <input
                      onChange={handleRadioChange}
                      type="radio"
                      value={'CustName'}
                      name="search"
                      id="CustName"
                      checked={selectedSearchValue === 'CustName'}
                    />
                    Name
                  </label>
                  <label
                    htmlFor="CustId"
                    className="search-addcustomer-inputlabel"
                    style={{
                      backgroundColor:
                        selectedSearchValue === 'CustId' && '#1292EE',
                      color: selectedSearchValue === 'CustId' && '#fff',
                    }}
                  >
                    <input
                      onChange={handleRadioChange}
                      type="radio"
                      value={'CustId'}
                      name="search"
                      id="CustId"
                      checked={selectedSearchValue === 'CustId'}
                    />
                    Cust Id
                  </label>
                </div>
              )}
            </div>
          }
          open={props.addcustomer}
          // width={900}
          footer={null}
          children={
            <Form ref={formRef} onFinish={handleSubmit} initialValues={''}>
              <div style={{ height: '45vh', overflow: 'auto' }}>
                <div className="CustMob-Name">
                  {!isSearching && (
                    <Form.Item
                      name="CustMobile"
                      rules={[
                        {
                          pattern:
                            selectedSearchValue == 'CustMobile' && /^\d{10}$/,
                          message:
                            selectedSearchValue == 'CustMobile' &&
                            'Please Enter a Valid 10-digit Mobile Number',
                        },
                        {
                          required: true,
                          message:
                            selectedSearchValue == 'CustMobile'
                              ? 'Please Enter Valid Mobile Number'
                              : selectedSearchValue == 'CustName'
                                ? 'Please Enter Valid Name'
                                : selectedSearchValue == 'CustId' &&
                                'Please EnterCustomer Id',
                        },
                      ]}
                    >
                      {Searchopen && (
                        <Select
                          showSearch
                          value={selectSearchDefaultValue}
                          type={
                            !Searchopen
                              ? 'number'
                              : selectedSearchValue === 'CustMobile'
                                ? 'number'
                                : 'text'
                          }
                          style={{ width: 250 }}
                          placeholder="Search to Select"
                          name="CustMobile"
                          optionFilterProp={selectedSearchValue}
                          filterOption={(input, option) =>
                            (option[selectedSearchValue] ?? '')
                              ?.toLowerCase()
                              ?.includes(input?.toLowerCase())
                          }
                          filterSort={(optionA, optionB) =>
                            (optionA[selectedSearchValue] ?? '')
                              ?.toLowerCase()
                              ?.localeCompare(
                                (
                                  optionB[selectedSearchValue] ?? ''
                                )?.toLowerCase()
                              )
                          }
                          options={options}
                          onSelect={(value, option) =>
                            setselectSearchDefaultValue(
                              ` ${option[selectedSearchValue] !== null ? option[selectedSearchValue] : option?.CustMobile}`
                            )
                          }
                          onChange={(value, option) =>
                            handleCustomerSelectChange(value, option)
                          }
                          onSearch={(inputValue) =>
                            handleSearchInputChange(inputValue)
                          }
                          onInputKeyDown={(e) => {
                            // Prevent minus sign and non-numeric characters for CustMobile and CustId
                            if (
                              (selectedSearchValue === 'CustMobile' ||
                                selectedSearchValue === 'CustId') &&
                              (e.key === '-' || e.key === 'e')
                            ) {
                              e.preventDefault();
                            }

                            // Ensure max length is respected
                            if (
                              (selectedSearchValue === 'CustMobile' &&
                                e.target.value.length >= 10 &&
                                e.key !== 'Backspace') ||
                              (selectedSearchValue === 'CustId' &&
                                e.target.value.length >= 9 &&
                                e.key !== 'Backspace')
                            ) {
                              e.preventDefault();
                            }

                            // Prevent numbers in name field
                            if (
                              selectedSearchValue === 'CustName' &&
                              !/^[A-Za-z]+$/.test(e.key) &&
                              e.key !== 'Backspace'
                            ) {
                              e.preventDefault();
                            }
                          }}
                          onWheel={(e) => e.preventDefault()} // Prevent scrolling from changing input value
                        />
                      )}
                      {!Searchopen && (
                        <InputField
                          label={
                            <label class="required">
                              {Searchopen
                                ? selectedSearchValue == 'CustMobile'
                                  ? 'Enter Mobile'
                                  : selectedSearchValue == 'CustName'
                                    ? 'Enter Name'
                                    : selectedSearchValue == 'CustId' &&
                                    'Enter Customer Id'
                                : ' Mobile Number'}
                            </label>
                          }
                          id="fruitInput"
                          options={options}
                          value={inputValue}
                          type={
                            !Searchopen
                              ? 'number'
                              : selectedSearchValue === 'CustMobile'
                                ? 'number'
                                : 'text'
                          }
                          list="fruits"
                          maxLength={
                            !Searchopen || selectedSearchValue === 'CustMobile'
                              ? 10
                              : undefined
                          }
                          autocomplete="off"
                          isOnChange={
                            selectedSearchValue === 'CustMobile'
                              ? inputValue?.length > 1
                                ? true
                                : inputValue && true
                              : true
                          }
                          onChange={(e) =>
                            handleSelectSuggestion(e?.target?.value)
                          }
                          onInput={(e) => {
                            let value = e?.target.value;

                            if (!suggestionClicked) {
                              // Allow only digits
                              value = value?.replace(/\D/g, '');

                              // Restrict starting digits to 6, 7, 8, 9
                              if (
                                value?.length === 1 &&
                                !/^[6-9]$/.test(value)
                              ) {
                                value = '';
                                setMessageData('Incorrect Number');
                                setMessageType('error');
                              }

                              // Restrict to max 10 digits
                              if (value?.length > 10) {
                                value = value?.slice(0, 10);
                              }

                              // Update the input field value
                              e.target.value = value;
                            }
                            setSuggestionClicked(false);
                          }}
                          suffix={
                            inputValue?.length >= 1 ? (
                              <IoCloseSharp onClick={ClearMobileInput} />
                            ) : (
                              <div></div>
                            )
                          }
                        />
                      )}

                      {!Searchopen && (
                        <datalist id="fruits">
                          {suggestions
                            ?.filter(
                              (suggestion) => suggestion[selectedSearchValue]
                            )
                            ?.map((suggestion, index) => (
                              <option
                                className="custom-suggestion-item"
                                key={index}
                                name={suggestion.MobileNo}
                                onMouseDown={() => {
                                  setSuggestionClicked(true);
                                  setInputValue(
                                    suggestion[selectedSearchValue]
                                  );
                                }}
                                value={suggestion[selectedSearchValue]}
                              >
                                <span>
                                  {selectedSearchValue == 'CustName'
                                    ? suggestion?.CustMobile
                                    : suggestion?.CustName}
                                  {selectedSearchValue === 'CustId' && (
                                    <>
                                      &nbsp; CustId:
                                      {
                                        suggestion?.CustId?.match(
                                          /-(\d+)$/
                                        )?.[1]
                                      }
                                    </>
                                  )}
                                </span>
                              </option>
                            ))}
                        </datalist>
                      )}

                      {searchResults.length > 0 && (
                        <div>
                          <p>Search Results:</p>
                          <ul>
                            {searchResults.map((result, index) => (
                              <li key={index}>{result}</li>
                            ))}
                          </ul>
                        </div>
                      )}

                      <div></div>
                    </Form.Item>
                  )}
                  <div className="search-and-addcust">
                    {Searchopen ? (
                      <div style={{ alignItems: 'center' }}>
                        <div
                          className="tooltip"
                          placement="bottom"
                          title={'Add Customer'}
                        >
                          <span className="tooltiptext">Add Customer</span>
                          <IoPersonAddSharp
                            style={{
                              color: 'rgb(18, 146, 238)',
                              fontSize: '20px',
                              cursor: 'pointer',
                            }}
                            onClick={HandleSearch}
                          />
                        </div>
                      </div>
                    ) : (
                      <div style={{ alignItems: 'center' }}>
                        <div className="tooltip" placement="bottom">
                          <span className="tooltiptext">Search Customer</span>
                          <IoSearchOutline
                            style={{
                              color: 'rgb(18, 146, 238)',
                              fontSize: '26px',
                              cursor: 'pointer',
                            }}
                            onClick={HandleSearch}
                          />
                        </div>
                      </div>
                    )}
                  </div>
                  <div
                    className={
                      CusDetails ? 'BSC1-CusDetails' : 'BSC1-CusDetails1'
                    }
                  >
                    <div className="BSC1-Basicdetails">
                      <Form.Item
                        name="CustName"
                        rules={[
                          {
                            pattern: /^(?!\s*$).+/,
                            message: 'Please Enter Customer Name',
                          },
                          {
                            validator: async (_, value) => {
                              await validateSafeInput(value); // To block HTML tags & SQL keywords
                              return Promise.resolve();
                            },
                          },
                        ]}
                      >
                        <InputField
                          label={<label>Customer Name</label>}
                          autocomplete="off"
                          isOnChange={
                            formRef.current?.getFieldsValue()?.CustName ||
                              inputValue
                              ? true
                              : false
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        name="CustShortName"
                        rules={[
                          {
                            pattern: /^(?!\s*$).+/,
                            message: 'Please Enter Customer Short Name',
                          },
                          {
                            validator: async (_, value) => {
                              await validateSafeInput(value); // To block HTML tags & SQL keywords
                              return Promise.resolve();
                            },
                          },
                        ]}
                      >
                        <InputField
                          label={<label>Customer Short Name </label>}
                          autocomplete="off"
                          isOnChange={
                            formRef.current?.getFieldsValue()?.CustShortName
                              ? true
                              : false
                          }
                        />
                      </Form.Item>
                      <Form.Item name={'Gender'}>
                        <RadioGrpButton
                          Header={'Gender'}
                          content={[
                            { label: 'Male', value: 'M' },
                            { label: 'Female', value: 'F' },
                          ]}
                          // value={formRef.current?.getFieldsValue()?.Gender}
                          defaultSelect={gender}
                          onSelectFuntion={(e) => {
                            setGender(e);
                            formRef.current.setFieldsValue({ Gender: e });
                          }}
                        />
                      </Form.Item>
                      <Form.Item name={'AadhaarNo'}>
                        <InputField
                          label={'Aadhaar No'}
                          maxLength={12}
                          autocomplete="off"
                          isOnChange={
                            formRef.current?.getFieldsValue()?.AadhaarNo
                              ? true
                              : false
                          }
                          inputMode="numeric"
                          onInput={(e) => {
                            e.target.value = e.target.value.replace(/\D/g, '');
                          }}
                        />
                      </Form.Item>
                      <div className="upload_btn emp-master-form__upload">
                        <p>Upload Profile</p>
                        <Form.Item
                          name="CustomerProfile"
                        // getValueFromEvent={(e) =>
                        //   formType === 'edit' ? editstate?.EmpPhotoLink : e
                        // }
                        >
                          <Imageupload
                            singleImage={true}
                            updateImageUrl={updateImageUrl}
                            ImageLink={(() => {
                              const link =
                                formRef.current?.getFieldsValue()
                                  ?.CustomerProfile || ImageUrl;
                              // Always return a string
                              return typeof link === 'string' ? link : '';
                            })()}
                          />
                        </Form.Item>
                      </div>
                    </div>
                  </div>
                  {/* <p
                    onClick={handleToggle}
                    style={{
                      fontSize: '13px',
                      cursor: 'pointer',
                      padding: '1rem 0.3rem',
                      display: 'flex',
                      // alignItems: "center",
                      flexDirection: 'row',
                      columnGap: '0.3rem',
                    }}
                  >
                    {' '}
                    {isOpen ? 'More info close' : 'More info open'}{' '}
                    <AiOutlineDownCircle />
                  </p> */}
                  <p
                    style={{
                      fontSize: '13px',
                      cursor: 'pointer',
                      padding: '1rem 0.3rem',
                      display: 'flex',
                      // alignItems: "center",
                      flexDirection: 'row',
                      columnGap: '0.3rem',
                      color: 'rgb(18, 146, 238)',
                    }}
                  >
                    {' '}
                    {isOpen ? (
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          gap: '4px',
                        }}
                        onClick={handleToggle}
                      >
                        More info close{' '}
                        <AiOutlineUpCircle style={{ marginTop: '4px' }} />
                      </div>
                    ) : (
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          gap: '4px',
                        }}
                        onClick={handleToggle}
                      >
                        More info open{' '}
                        <AiOutlineDownCircle style={{ marginTop: '4px' }} />
                      </div>
                    )}{' '}
                  </p>
                  {
                    <div
                      style={{ display: !isOpen && 'none' }}
                      className="BSC1-AdressInputs"
                    >
                      <Form.Item
                        name="CustEmail"
                        rules={[
                          {
                            // required: true,
                            message: 'Please enter Customer Email',
                          },
                          {
                            validator: validateEmail,
                          },
                        ]}
                      >
                        <InputField
                          label="Email Id"
                          autocomplete="off"
                          isOnChange={
                            formRef.current?.getFieldsValue()?.CustEmail
                              ? true
                              : false
                          }
                        />
                      </Form.Item>

                      <Form.Item
                        name="CustGSTIN"
                        rules={[
                          {
                            pattern:
                              /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Za-z]{1}[Z]{1}[0-9A-Za-z]{1}$/,
                            message: 'Enter a valid GSTIN',
                          },
                        ]}
                      >
                        <InputField
                          style={{ textTransform: 'uppercase' }}
                          autoComplete="off"
                          label="GST No"
                          autocapitalize="on"
                          isOnChange={
                            formRef.current?.getFieldsValue()?.CustGSTIN
                              ? true
                              : false
                          }
                        />
                      </Form.Item>

                      {isOpen && (
                        <>
                          <div className="formAddressDiv">
                            <p> Address Details</p>
                          </div>

                          <div className="customer-address-details-list">
                            {addressPreview.length > 0 ? (
                              addressPreview
                                ?.filter((addr) => addr.ActiveStatus !== 'D')
                                ?.map((addr, idx) => (
                                  <div key={idx} className="address-card">
                                    <div className="address-header">
                                      <div className="header-left">
                                        <h4>Address {idx + 1}</h4>
                                        {/* <h4>Address</h4> */}
                                      </div>
                                    </div>

                                    <div className="address-type-section">
                                      <div
                                        style={{
                                          display: 'flex',
                                          alignItems: 'center',
                                          flexWrap: 'wrap',
                                        }}
                                      >
                                        <Checkbox
                                          checked={(
                                            addressTypes[idx] || []
                                          ).includes('Delivery Address')}
                                          onChange={(e) =>
                                            handleAddressTypeChange(
                                              idx,
                                              'Delivery Address',
                                              e.target.checked
                                            )
                                          }
                                        >
                                          Delivery Address
                                        </Checkbox>
                                        <Checkbox
                                          checked={(
                                            addressTypes[idx] || []
                                          ).includes('Billing Address')}
                                          onChange={(e) =>
                                            handleAddressTypeChange(
                                              idx,
                                              'Billing Address',
                                              e.target.checked
                                            )
                                          }
                                        >
                                          Billing Address
                                        </Checkbox>
                                        <Checkbox
                                          checked={(
                                            addressTypes[idx] || []
                                          ).includes('Both Address')}
                                          onChange={(e) =>
                                            handleAddressTypeChange(
                                              idx,
                                              'Both Address',
                                              e.target.checked
                                            )
                                          }
                                        >
                                          Both Address
                                        </Checkbox>
                                      </div>
                                    </div>

                                    <div className="address-details-grid">
                                      <div className="address-detail-item address1">
                                        <div className="value">
                                          {addr?.Address1 || ''}
                                        </div>
                                      </div>

                                      <div className="address-detail-item address2">
                                        <div className="value">
                                          {addr?.Address2 || ''}
                                        </div>
                                      </div>

                                      <div className="address-detail-item zip">
                                        <div className="value">
                                          {addr?.Zip || ''}
                                        </div>
                                      </div>

                                      <div className="address-detail-item city">
                                        <div className="value">
                                          {addr?.City || ''}
                                        </div>
                                      </div>

                                      <div className="address-detail-item district">
                                        <div className="value">
                                          {addr?.Dist || ''}
                                        </div>
                                      </div>

                                      <div className="address-detail-item state">
                                        <div className="value">
                                          {addr?.State || ''}
                                        </div>
                                      </div>

                                      {addr?.Latitude && (
                                        <div className="address-detail-item coordinates">
                                          <div className="value coordinates">
                                            <MdLocationOn />{' '}
                                            {addr?.Latitude || ''},{' '}
                                            {addr?.Longitude || ''}
                                          </div>
                                        </div>
                                      )}
                                    </div>
                                    <div className="header-actions">
                                      <button
                                        type="button"
                                        onClick={() => handleEditAddress(idx)}
                                        className="edit-btn"
                                      >
                                        <FaEdit /> Edit
                                      </button>

                                      <Popconfirm
                                        title="Remove Address"
                                        description="Are you sure you want to remove this address?"
                                        onConfirm={() => handleRemoveAddress(idx)}
                                        okText="Yes, Remove"
                                        cancelText="Cancel"
                                        okType="danger"
                                      >
                                        <button
                                          className="remove-btn"
                                          type="button"
                                        >
                                          <FaTrash /> Remove
                                        </button>
                                      </Popconfirm>
                                    </div>
                                  </div>
                                ))
                            ) : (
                              <div className="empty-state">
                                <MdHome />
                                <h3>No addresses added yet</h3>
                                <p>
                                  Add your first address using the form below
                                </p>
                              </div>
                            )}
                          </div>
                          {/* Single Address Input Form */}
                          <div
                            className="subinputForm"
                            style={{
                              border: '1px solid #ddd',
                              borderRadius: '8px',
                              padding: '16px',
                              marginBottom: '16px',
                            }}
                          >
                            <h4
                              style={{ marginBottom: '12px', color: '#1677ff' }}
                            >
                              Address Form
                            </h4>
                            <div
                              style={{
                                display: 'flex',
                                flexWrap: 'wrap',
                                gap: '16px',
                                alignItems: 'flex-start',
                              }}
                            >
                              {/* Address1 */}
                              <Form.Item
                                name="Address1"
                                rules={[
                                  // { required: true, pattern: /^(?!\s*$).+/, message: "Please Enter Address1" },
                                  {
                                    validator: async (_, value) => {
                                      await validateSafeInput(value);
                                      return Promise.resolve();
                                    },
                                  },
                                ]}
                              >
                                <InputField
                                  field="Address1"
                                  autoComplete="off"
                                  label={
                                    <label className="required">
                                      Address Line1
                                    </label>
                                  }
                                  fieldState={true}
                                  fieldApi={true}
                                  isOnChange={true}
                                />
                              </Form.Item>

                              {/* Address2 */}
                              <Form.Item
                                name="Address2"
                                rules={[
                                  {
                                    pattern: /^(?!\s*$).+/,
                                    message: 'Please Enter Address2',
                                  },
                                  {
                                    validator: async (_, value) => {
                                      await validateSafeInput(value);
                                      return Promise.resolve();
                                    },
                                  },
                                ]}
                              >
                                <InputField
                                  field="Address2"
                                  autoComplete="off"
                                  label="Address Line2"
                                  fieldState={true}
                                  fieldApi={true}
                                  isOnChange={true}
                                />
                              </Form.Item>

                              {/* Zip */}
                              <Form.Item
                                name="Zip"
                                rules={[
                                  // { required: true, pattern: /^(?!\s*$).+/, message: "Please Enter Zipcode" },
                                  {
                                    validator: async (_, value) => {
                                      await validateSafeInput(value);
                                      return Promise.resolve();
                                    },
                                  },
                                ]}
                              >
                                <InputField
                                  field="Zip"
                                  autoComplete="off"
                                  label={
                                    <label className="required">Zipcode</label>
                                  }
                                  maxLength={6}
                                  fieldState={true}
                                  fieldApi={true}
                                  isOnChange={true}
                                  onChange={(e) => pinCodeChange(e, 0)}
                                />
                              </Form.Item>

                              {zipCodeData && (
                                <>
                                  <Form.Item
                                    name="City"
                                    rules={[
                                      // { required: true },
                                      {
                                        validator: async (_, value) => {
                                          await validateSafeInput(value);
                                          return Promise.resolve();
                                        },
                                      },
                                    ]}
                                  >
                                    <InputField
                                      field="City"
                                      disabled
                                      label="City"
                                      fieldState={true}
                                      fieldApi={true}
                                      isOnChange={true}
                                    />
                                  </Form.Item>

                                  <Form.Item
                                    name="Dist"
                                    rules={[
                                      // { required: true },
                                      {
                                        validator: async (_, value) => {
                                          await validateSafeInput(value);
                                          return Promise.resolve();
                                        },
                                      },
                                    ]}
                                  >
                                    <InputField
                                      field="Dist"
                                      disabled
                                      label="District"
                                      fieldState={true}
                                      fieldApi={true}
                                      isOnChange={true}
                                    />
                                  </Form.Item>

                                  <Form.Item
                                    name="State"
                                  // rules={[{ required: true }]}
                                  >
                                    <InputField
                                      field="State"
                                      disabled
                                      label="State"
                                      fieldState={true}
                                      fieldApi={true}
                                      isOnChange={true}
                                    />
                                  </Form.Item>
                                </>
                              )}

                              {/* Add Address Button */}
                              <button
                                type="button"
                                onClick={handleAddOrUpdateAddress}
                                style={{
                                  backgroundColor: '#1677ff',
                                  color: '#fff',
                                  padding: '6px 12px',
                                  border: 'none',
                                  borderRadius: '6px',
                                  cursor: 'pointer',
                                  marginTop: '8px',
                                  fontWeight: '500',
                                }}
                              >
                                {editingIndex !== null
                                  ? 'Update Address'
                                  : 'Add Address'}
                              </button>
                            </div>
                          </div>
                        </>
                      )}

                      <div className="customerOffer">
                        <div
                          style={
                            offerType == 'P'
                              ? {
                                opacity: '1',
                                boxShadow:
                                  'rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px',
                                margin: '3px',
                                padding: '5px',
                                backgroundColor: '#fff',
                              }
                              : { opacity: '0.6', boxShadow: 'none' }
                          }
                          onClick={() => {
                            Onchangeoffertype('P');
                          }}
                        >
                          <GrCheckboxSelected />
                          <p style={{ fontSize: '13px', textWrap: 'nowrap' }}>
                            Percentage
                          </p>
                        </div>
                        <div
                          style={
                            offerType == 'F'
                              ? {
                                opacity: '1',
                                boxShadow:
                                  'rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px',
                                margin: '3px',
                                padding: '5px',
                                backgroundColor: '#fff',
                              }
                              : { opacity: '0.6', boxShadow: 'none' }
                          }
                          onClick={() => {
                            Onchangeoffertype('F');
                          }}
                        >
                          <BiCustomize />
                          <p style={{ fontSize: '13px', textWrap: 'nowrap' }}>
                            Fixed
                          </p>
                        </div>
                      </div>

                      <div>
                        <Form.Item
                          name="OfferValue"
                          rules={[
                            {
                              validator: async (_, value) => {
                                // Check for unsafe input first
                                await validateSafeInput(value); // Blocks HTML tags & SQL keywords

                                // Allow empty values (assumes optional field)
                                if (value === undefined || value === '') {
                                  return Promise.resolve();
                                }

                                // Ensure it's a number
                                if (isNaN(value)) {
                                  return Promise.reject(
                                    new Error('Offer Value must be a number')
                                  );
                                }

                                // If offer type is percentage, check range
                                if (offerType === 'P' && value >= 100) {
                                  return Promise.reject(
                                    new Error(
                                      'Offer Value must be less than 100'
                                    )
                                  );
                                }

                                return Promise.resolve();
                              },
                            },
                          ]}
                        >
                          <InputField
                            label={<label>Offer Value</label>}
                            autocomplete="off"
                            isOnChange={
                              OfferValue || OfferValue == 0 ? true : false
                            }
                            onChange={Handleoffervalue}
                            inputMode="decimal"
                            onInput={(e) => {
                              const cleanedValue = e.target.value.replace(
                                /[^0-9.]/g,
                                ''
                              );
                              const parts = cleanedValue.split('.');
                              e.target.value =
                                parts.length > 2
                                  ? `${parts[0]}.${parts.slice(1).join('')}`
                                  : cleanedValue;
                            }}
                          />
                        </Form.Item>
                      </div>

                      <div>
                        <Form.Item name="OfferActiveStatus">
                          <DropDowns
                            defaultValue={selectedValue}
                            options={yesNoOptions?.map((option) => ({
                              value: option?.value,
                              label: option?.label,
                            }))}
                            label={<label>Active / Deactive</label>}
                            className="field-DropDown"
                            onChangeFunction={(e) => handleYesOrNoChange(e)}
                            valueData={selectedValue}
                          />
                        </Form.Item>
                      </div>
                      {/* sree  */}
                      <Form.Item name="CreditDays">
                        <InputField
                          label="Credit Days"
                          autocomplete="off"
                          disabled={
                            InitialOutStandingType === 'Y' ? true : false
                          }
                          isOnChange={
                            formRef.current?.getFieldsValue()?.CustEmail ||
                              inputValue
                              ? true
                              : false
                          }
                          inputMode="decimal"
                          onInput={(e) => {
                            const cleanedValue = e.target.value.replace(
                              /[^0-9.]/g,
                              ''
                            );
                            const parts = cleanedValue.split('.');
                            e.target.value =
                              parts.length > 2
                                ? `${parts[0]}.${parts.slice(1).join('')}`
                                : cleanedValue;
                          }}
                        />
                      </Form.Item>
                      <Form.Item name="CreditLimit">
                        <InputField
                          name="CreditLimit"
                          label="Credit Limits"
                          disabled={
                            InitialOutStandingType === 'Y' ? true : false
                          }
                          autocomplete="off"
                          isOnChange={
                            formRef.current?.getFieldsValue()?.CreditLimit ||
                              inputValue
                              ? true
                              : false
                          }
                          inputMode="decimal"
                          onInput={(e) => {
                            const cleanedValue = e.target.value.replace(
                              /[^0-9.]/g,
                              ''
                            );
                            const parts = cleanedValue.split('.');
                            e.target.value =
                              parts.length > 2
                                ? `${parts[0]}.${parts.slice(1).join('')}`
                                : cleanedValue;
                          }}
                        />
                      </Form.Item>

                      <Form.Item name="AmountType" label="Type of Amount">
                        <Switch
                          size="small"
                          checked={amountType === 'D'}
                          onChange={(checked) => {
                            const newValue = checked ? 'D' : 'C';
                            formRef.current?.setFieldsValue({
                              AmountType: newValue,
                            });
                            setAmountType(newValue);
                          }}
                          checkedChildren="Advance"
                          unCheckedChildren="Balance"
                        />
                      </Form.Item>

                      {/* Then add the input field */}
                      <Form.Item name="OutStandingAmount">
                        <InputField
                          field="OutStandingAmount"
                          name="OutStandingAmount"
                          label={
                            formRef.current?.getFieldValue('AmountType') === 'D'
                              ? 'Out Standing Advance'
                              : 'Out Standing Balances'
                          }
                          disabled={InitialOutStandingType === 'Y'}
                          inputMode="numeric"
                          autoComplete="off"
                          fieldState={true}
                          fieldApi={true}
                          id="error2"
                          isOnChange={true}
                          value={formRef.current?.getFieldValue(
                            'OutStandingAmount'
                          )}
                          onChange={(e) => {
                            let value = e.target.value.replace(/[^0-9.]/g, '');
                            // Handle decimal points
                            const parts = value.split('.');
                            if (parts.length > 2) {
                              value = `${parts[0]}.${parts.slice(1).join('')}`;
                            }
                            // Limit to 2 decimal places
                            if (parts.length === 2 && parts[1].length > 2) {
                              value = `${parts[0]}.${parts[1].slice(0, 2)}`;
                            }
                            formRef.current?.setFieldsValue({
                              OutStandingAmount: value,
                            });
                          }}
                          onKeyDown={(e) => {
                            // Allow backspace, delete, arrow keys, tab
                            if (
                              [
                                'Backspace',
                                'Delete',
                                'ArrowLeft',
                                'ArrowRight',
                                'Tab',
                              ].includes(e.key)
                            ) {
                              return;
                            }
                            // Allow numbers and a single decimal point
                            if (!/[\d.]/.test(e.key)) {
                              e.preventDefault();
                              return;
                            }
                            // Prevent multiple decimal points
                            if (e.key === '.' && e.target.value.includes('.')) {
                              e.preventDefault();
                            }
                          }}
                        />
                      </Form.Item>

                      {/* <div className="upload_btn">
                        <p>Upload Document</p>
                        <Form.Item name="Document" valuePropName="ImageLink">
                          <Imageupload
                            singleImage={true}
                            updateImageUrl={updateImageUrl}
                            ImageLink={
                              formRef.current?.getFieldsValue()?.UserImage ||
                              ImageUrl
                            }
                          />
                        </Form.Item>
                      </div> */}
                      <div
                        style={{
                          display: 'flex',
                          paddingLeft: '10px',
                          flexDirection: 'column',
                          rowGap: '0.5rem',
                        }}
                      >
                        <label style={{ fontWeight: '600' }}>
                          Marital Status{' '}
                        </label>
                        <Radio.Group
                          onChange={onchangeStatus}
                          value={Maritalstatus}
                        >
                          <Radio value={'N'}>Single</Radio>
                          <Radio value={'Y'}>Married </Radio>
                        </Radio.Group>
                      </div>
                      <div>
                        <div
                          style={{
                            display: 'flex',
                            alignitems: 'center',
                            padding: '0px 10px',
                            columnGap: '2rem',
                          }}
                        >
                          <div>
                            <label style={{ fontWeight: '600' }}>
                              Date of Birth
                            </label>
                            <br />
                            <br />
                            <DatePicProd
                              canSelectPast={true}
                              onChange={dobchange}
                              valueData={DobDate}
                            />
                          </div>
                          {Maritalstatus == 'Y' && (
                            <div
                              style={{
                                display: 'flex',
                                alignitems: 'center',
                                columnGap: '2rem',
                              }}
                            >
                              <div>
                                <label style={{ fontWeight: '600' }}>
                                  {' '}
                                  Spouse DOB
                                </label>
                                <br />
                                <br />
                                <DatePicProd
                                  canSelectPast={true}
                                  onChange={spousedobchange}
                                  valueData={SpouseDobDate}
                                />
                              </div>
                              <div>
                                <label style={{ fontWeight: '600' }}>
                                  Anniversary Date
                                </label>
                                <br />
                                <br />
                                <DatePicProd
                                  canSelectPast={true}
                                  onChange={anniversaryDatechange}
                                  valueData={anniversaryDate}
                                />
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  }
                </div>
              </div>

              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Buttons
                  buttonText="SUBMIT"
                  color="901D77"
                  icon={<ArrowRightOutlined />}
                />
              </div>
            </Form>
          }
          handleCancel={
            // props.handleAddCustomerCancel

            HandleCloseModal
          }
        />
      </div>
      {/* <div>
        <DefaultModal
          title={
            <div className="Holdmodel-title">
              <FormHeader title={'Reprint'} />
            </div>
          }
          open={props.reprint}
          width={1000}
          footer={null}
          children={<BSReprint />}
          handleCancel={props.handleReprintCancel}
        />
      </div> */}
      <div>
        <DefaultModal
          open={props.QuickAdd}
          width={800}
          footer={false}
          children={
            // cardData Mohan 18-4-2025
            <ProductForm
              formType="add"
              handleCancelData={props.handleQuickAddCancel}
              ProductSearch={props.ProductSearch}
              ProductSearchType={props.ProductSearchType}
              cardData={props.cardData}
            />
          }
          handleCancel={props.handleQuickAddCancel}
        />
      </div>
      <div>
        <DefaultModal
          open={props.ExtraCharges}
          width={900}
          footer={false}
          children={
            <>
              <h1 class="formHeader">Extra Charges</h1>

              <div style={{ display: 'flex' }}>
                <Checkbox
                  checked={Checkbox1 ? true : false}
                  onClick={() => {
                    setCheckbox1(!Checkbox1);
                  }}
                ></Checkbox>{' '}
                &nbsp;&nbsp;<p>Overall orders </p> {'  '}
                &nbsp;&nbsp;
                <Checkbox
                  checked={!Checkbox1 ? true : false}
                  onClick={() => {
                    setCheckbox1(!Checkbox1);
                  }}
                ></Checkbox>{' '}
                {/* {!Checkbox1 ? ( */}
                &nbsp;&nbsp; <p> Individual orders</p>
              </div>
              <br />
              <Form ref={formRefExtraCharges} onFinish={globalamount1}>
                {!Checkbox1 && (
                  <Form.Item
                    name="Extracharges"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Dropdown',
                      },
                    ]}
                  >
                    <div style={{ display: 'flex' }}>
                      <DropDowns
                        defaultValue={selectedProduct}
                        options={CartOrderDetails?.map((option) => ({
                          value:
                            option?.InwardDtlId +
                            ' ' +
                            option?.BookingTypeName +
                            ' ' +
                            option?.SinglePc,
                          // label: option.Type === 'P'  ? option.ProdVariantName !== 'Variant 1'
                          // ? `${option?.ProdName} (${option.Size} ${option.UomName}) (${option.ProdVariantName}${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''})`
                          //   : `${option?.ProdName} (${option.Size} ${option.UomName}) ${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''}`
                          //   : `${option?.ProdName} (1 Combo)`
                          label:
                            option.Type === 'P'
                              ? option.ProdVariantName !== 'Variant 1'
                                ? `${option?.ProdName} (${option.Size} ${option?.SinglePc === 'PCS' ? 'PCS' : option.UomName}) (${option.ProdVariantName}${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''})`
                                : `${option?.ProdName} (${option.Size}${option?.SinglePc === 'PCS' ? 'PCS' : option.UomName}) ${BookingTypeBoth ? ` (${option?.BookingTypeName})` : ''}`
                              : `${option?.ProdName} (1 Combo)`,
                        }))}
                        label={<label className="required">Product Name</label>}
                        className="field-DropDown"
                        onChangeFunction={(e) => onChangeProduct(e)}
                        valueData={selectedProduct}
                      />
                    </div>
                  </Form.Item>
                )}
                <div>
                  {Checkbox1 ? (
                    <div>
                      <Table
                        components={components}
                        rowClassName={() => 'editable-row'}
                        bordered
                        dataSource={dataSource}
                        columns={columns}
                      />
                    </div>
                  ) : (
                    <div>
                      {/* JSX specific to false branch */}
                      <Table
                        dataSource={dataSource1}
                        columns={defaultColumns1}
                      />
                    </div>
                  )}

                  {!Checkbox1 && (
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'right',
                        width: '100%',
                      }}
                    >
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'flex-end',
                          width: '100px',
                        }}
                      >
                        <Buttons
                          buttonText="SAVE"
                          color="901D77"
                          icon={<ArrowRightOutlined />}
                        //  handleSubmit={() => { globalamount1() }}
                        />
                      </div>
                    </div>
                  )}
                  {!Checkbox1 && (
                    <div>
                      <Table
                        columns={columns1}
                        rowClassName={() => 'editable-row'}
                        components={components1}
                        bordered
                        dataSource={TableName}
                        width={'120px'}
                      //pagination={column2?.length < "11" ? false : true}
                      ></Table>
                    </div>
                  )}
                </div>
                {Checkbox1 && (
                  <div style={{ display: 'flex' }}>
                    <h3>Total Amount:</h3>
                    <h3>{safeRound(totalAmount)}</h3>
                  </div>
                )}{' '}
                <br />
                {Checkbox1 && (
                  <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Buttons
                      buttonText="SUBMIT"
                      color="901D77"
                      icon={<ArrowRightOutlined />}
                      handleSubmit={() => {
                        globalamount(extdata);
                      }}
                    />
                  </div>
                )}
                {!Checkbox1 && (
                  <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Buttons
                      buttonText="SUBMIT"
                      color="901D77"
                      icon={<ArrowRightOutlined />}
                      handleSubmit={() => {
                        globalamount2(TableName);
                      }}
                    />
                  </div>
                )}
              </Form>
            </>
          }
          handleCancel={props.ExtraChargesCancle}
        />
      </div>
      <div>
        <DefaultModal
          open={WeightScale}
          title="Item Info"
          width={1000}
          footer={false}
          children={
            <>
              <br />
              <div className="WeightScaleMainDiv">
                <Form ref={formWsRef} onFinish={onFinish}>
                  <div className="WeightScaleSubDiv">
                    <Form.Item
                      name="ItemName"
                      rules={[
                        {
                          required: true,
                          message: 'Please Enter Item Name',
                        },
                      ]}
                    >
                      <AutoComplete
                        value={ProductValue}
                        options={WSProductList?.map((option) => ({
                          value: option.ProdName,
                          label: option.ProdName,
                        }))}
                        style={{
                          width: 200,
                        }}
                        // onSearch={(text) => setOptions(getPanelValue(text))}
                        onChange={WSProductChange}
                        onSelect={WSProductSelect}
                        placeholder="Product Name"
                        allowClear={{
                          clearIcon: <CloseSquareFilled />,
                        }}
                      />
                    </Form.Item>
                    {WeightScale === true && (
                      <WeightScaleComp
                        testfun={myfun}
                        setportfun={setWsport}
                        portval={wsport}
                        portclose={WeightScale2}
                        WeightScale={WeightScale}
                      />
                    )}

                    <Form.Item name="WSProductWeight">
                      <InputField
                        label={<label>Product Weight</label>}
                        autocomplete="off"
                        isOnChange={WSProductWeight ? true : false}
                        readOnly={true}
                      />
                    </Form.Item>
                    <Form.Item name="WSProductRate">
                      <InputField
                        label={<label>Product Price</label>}
                        autocomplete="off"
                        isOnChange={WSProductRate ? true : false}
                        valueData={WSProductRate}
                        readOnly={true}
                        disabled={
                          formWsRef.current?.getFieldsValue().WSProductRate
                            ? true
                            : false
                        }
                      />
                    </Form.Item>
                    <CiCalculator1
                      className="WSCalculator-icon"
                      onClick={CalculateWeightOpen}
                    />
                    {CalcPriceWeightOpen && (
                      <>
                        <Form.Item
                          name="CalcProductRate"
                          rules={[
                            {
                              pattern: /^[1-9]\d*(\.\d+)?$/,
                              message: 'Please Enter Valid Price',
                            },
                            { validator: HandleProductName },
                          ]}
                        >
                          <InputField
                            label={<label> Customer Product Price</label>}
                            autocomplete="off"
                            isOnChange={CalcProductRate > 0 ? true : false}
                            valueData={CalcProductRate}
                            onChange={CalculateWeight}
                          />
                        </Form.Item>
                        <Form.Item name="CalcProductWeight">
                          <InputField
                            label={<label> Weight For Given Price</label>}
                            autocomplete="off"
                            isOnChange={CalcProductWeight > 0 ? true : false}
                            valueData={CalcProductWeight}
                            readOnly={true}
                          />
                        </Form.Item>
                      </>
                    )}
                    <Form.Item name="WSTotalPrice">
                      <InputField
                        label={<label>Product Total Price</label>}
                        autocomplete="off"
                        isOnChange={WSTotalPrice > 0 ? true : false}
                        valueData={WSTotalPrice}
                        readOnly={true}
                      />
                    </Form.Item>

                    <Buttons
                      buttonText="ADD"
                      color="901D77"
                      icon={<ArrowRightOutlined />}
                      disabled={WSTotalPrice > 0 ? false : true}
                    />
                  </div>
                </Form>

                {WSProductDataSource?.length > 0 ? (
                  <div className="WeightScale-table">
                    <Tables
                      columns={WSStockColumns}
                      data={WSProductDataSource}
                    />
                  </div>
                ) : (
                  ProductValue && (
                    <div>
                      <p>No Data Found</p>
                    </div>
                  )
                )}
              </div>
            </>
          }
          handleCancel={WSModalPortclose}
        />
      </div>
    </div>
  );
};
export default FeaturesFunctionalities;
