import React, {
  useCallback,
  useEffect,
  useRef,
  useState,
  useContext,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Divider, Form, Input, Segmented, Table } from 'antd';
import { Modal, Tooltip, DatePicker } from 'antd';
import { Messages } from '../../Components/Notifications/Messages';
import FormHeader from '../PageComponents/FormHeader';
import { InputField } from '../../Components/Forms/InputField';
import Buttons from '../../Components/Forms/Buttons';
import { ArrowRightOutlined } from '@ant-design/icons';
import { DropDowns } from '../../Components/Forms/DropDown';
import '../../Styles/CancelReschedule/ChangePaymentMode.scss';
import {
  ChangeSelectedCustDisable,
  GlobalSelCustId,
  GlobalpaymentOptionData,
  changeSelectedCustId,
  changeSelectedOption,
  getAllCustomer,
  getCancelReshRules,
  getCreditCustomer,
  getPaymentModeDetail,
  getPaymentOptions,
  putpaymentStatus,
  putpaymentModeChange,
  PostSalesCancellation,
} from '../../Features/BookingScreen/BookingData/BookingData.js';
import {
  ExtractDateFormate,
  extractLastNumber,
  getSession,
  validateSafeInput,
} from '../../Services/Others.js';
import PozoAddCustomerIcon from '../BookingScreen/Components/UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
import BSCustomerSelect from '../BookingScreen/Components/UtillComponents/BSSelectCustomer.jsx';
import FeaturesFunctionalities from '../BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.jsx';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
import { useAuth } from '../../AuthContext.jsx';
import dayjs from 'dayjs';
import { IoEye } from 'react-icons/io5';
import { ApplicationPreferences } from '../../Features/BrachLogin/BranchLogin.js';
const subDirectory = import.meta.env.BASE_URL;
const containerStyle = {
  display: 'flex',
  flexDirection: 'column',
  overflow: 'scroll',
};

const rowStyle = {
  display: 'flex',
  flexDirection: 'row',
  width: '90%',
  fontSize: '16px',
};

const labelStyle = {
  display: 'flex',
  justifyContent: 'flex-start',
  width: '50%',
};

const valueStyle = {
  display: 'flex',
  justifyContent: 'flex-end',
  width: '30%',
};

const ChangePaymentmode = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Payment Mode Change'
  );

  const formRef = useRef();
  const dispatch = useDispatch();
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');
  const EditableContext = React.createContext(null);
  const PaymentOptions = useSelector(GlobalpaymentOptionData);
  const SelectCustId = useSelector(GlobalSelCustId);

  const appPreferences = useSelector(ApplicationPreferences);
  const commonModulePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Common Module'
  )?.PreferenceCatDetails;
  const sportsAppPreference = commonModulePreference?.find(
    (preference) =>
      preference?.PreferredSubCatName === 'SportsApp' &&
      preference?.PreferredStatus == 'Y'
  );

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [selCancelPay, setselCancelPay] = useState('CR');
  const [selActivityType, setselActivityType] = useState('Cancel');
  const [paybtns, setpaybtns] = useState([]);
  const [CanReason, setCanReason] = useState([]);
  const [SelCanReason, setSelCanReason] = useState([]);
  const [RescheduleReason, setRescheduleReason] = useState([]);
  // const [SelRescheduleReason, setSelRescheduleReason] = useState([])
  const [SalesDetail, setSalesDetail] = useState([]);
  const [FullSalesDetail, setFullSalesDetail] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [SelectedOrderId, setSelectedOrderId] = useState(null);
  // const [SelPayMode, setSelPayMode] = useState()
  const [ApiPaymentName, setApiPaymentName] = useState(null);
  const [DropSelPaymentName, setDropSelPaymentName] = useState(null);
  const [SelectSalesId, setSelectSalesId] = useState();
  const [SelCanPaymode, setSelCanPaymode] = useState();
  const [SelCancelType, setSelCancelType] = useState('OverAll');
  const [CancelModalOpen, setCancelModalOpen] = useState(false);
  const [CancellationCharge, setCancellationCharge] = useState(null);
  const [addcustomer, setAddCustomer] = useState(false);
  const [SelectCust, setSelectCust] = useState(false);
  const [CreditCustDetails, setCreditCustDetails] = useState([]);
  const [CreditCustomer, setCreditCustomer] = useState(false);
  const [NewCustomer, setNewCustomer] = useState([]);
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const [isdisabled, setisdisabled] = useState(true);
  const [segmentValue, setSegmentValue] = useState('Bill No');
  const [selectedRowKey, setSelectedRowKey] = useState(null);
  const [selectedPayments, setSelectedPayments] = useState([]);
  const [viewProductDetails, setViewProductDetails] = useState({
    view: false,
    productDetails: [],
  });

  const [viewPaymentDetails, setViewPaymentDetails] = useState({
    view: false,
    paymentDetails: [],
  });
  const [isPosting, setIsPosting] = useState(false);
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
    {
      name: ' Cancel/Payment Change',
      link: `${subDirectory}setting/cancel-paymentchange`,
    },
  ];

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchPaymentOption();
    GetCancellationReason();
  }, []);

  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);

  useEffect(() => {
    let hasAccess = false;
    if (UserType === 'Admin' || UserType === 'Super Admin') {
      hasAccess = true;
    } else if (UserType === 'Employee') {
      hasAccess = empData?.AddAccess === 'Y';
    } else if (UserType === 'Super Admin User') {
      hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
    }
    setaddnewAccess(!hasAccess);
  }, [empData, SAAccessCommonMaster, UserType]);

  useEffect(() => {
    getCreditcustDetail();
  }, [SelectCustId, SelectCust]);

  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);
  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Payment Mode Change'
    );
    setEmpData(datas?.[0]);
  };

  useEffect(() => {
    const withoutCustomer = PaymentOptions?.filter?.(
      (item) => item?.ConfigName?.toLowerCase() !== 'credit'?.toLowerCase()
    );
    setpaybtns(withoutCustomer);
  }, [PaymentOptions]);

  const OverAllOrderCancel = (second) => {
    // third;
  };
  const disabledDate = (current) => current && current > dayjs().endOf('day');

  const getCreditcustDetail = async () => {
    let Credata = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      CustId: SelectCustId,
    };
    let res = await dispatch(getCreditCustomer(Credata)).unwrap();
    if (res?.data?.statusCode === 1) {
      setCreditCustDetails(res?.data?.data);
    } else {
      let res = await dispatch(
        getAllCustomer({ CompId: CompId, AppId: AppId, branchId: BranchId })
      ).unwrap();
      if (res?.data?.statusCode == 1) {
        let allcustomer = res?.data?.data;
        let SelectedCustomer = allcustomer?.filter(
          (item) => item?.CustId === SelectCustId
        );
        setNewCustomer(SelectedCustomer);
        setCreditCustDetails([]);
      } else {
        setCreditCustDetails([]);
        setNewCustomer([]);
      }
    }
  };

  const getSalesOrderDetail = async () => {
    let fromDate;
    let toDate;
    let date;
    const billormobile =
      formRef.current?.getFieldsValue()?.[
        selCancelPay === 'CR' ? 'OrderId' : 'PaymodeOrderId'
      ];
    if (segmentValue === 'Mobile') {
      if (selCancelPay === 'CR') {
        if (selActivityType === 'Cancel') {
          fromDate = formRef.current
            ?.getFieldsValue()
            ?.CancelFromDate?.format('YYYY-MM-DD');
          toDate = formRef.current
            ?.getFieldsValue()
            ?.CancelToDate?.format('YYYY-MM-DD');
        } else if (selActivityType === 'Reschedule') {
          fromDate = formRef.current
            ?.getFieldsValue()
            ?.ReschedulFromDate?.format('YYYY-MM-DD');
          toDate = formRef.current
            ?.getFieldsValue()
            ?.ReschedulToDate?.format('YYYY-MM-DD');
        }
      } else if (selCancelPay === 'CP') {
        fromDate = formRef.current
          ?.getFieldsValue()
          ?.['Change-PaymentFromDate']?.format('YYYY-MM-DD');
        toDate = formRef.current
          ?.getFieldsValue()
          ?.['Change-PaymentToDate']?.format('YYYY-MM-DD');
      }
    }
    if (segmentValue === 'Date') {
      const fieldname =
        selCancelPay === 'CR'
          ? selActivityType === 'Cancel'
            ? 'Canceldate'
            : 'RescheduleApidate'
          : 'Change-Paymentdate';
      date = formRef.current
        ?.getFieldsValue()
        ?.[fieldname]?.format('YYYY-MM-DD');
    }

    const data = {
      segmentValue,
      mobileNumber: billormobile,
      fromDate,
      toDate,
      date,
      AppId,
      CompId,
      BranchId,
      OrderId:
        'O' +
        AppId +
        '-' +
        CompId +
        '-' +
        BranchId +
        '-' +
        UserId +
        '-' +
        billormobile,
    };

    const res = await dispatch(getPaymentModeDetail(data)).unwrap();

    if (res?.data?.statusCode === 1) {
      const data = res?.data?.data;
      setFullSalesDetail(data);
      setSelCancelType('OverAll');
      const tempListData = data?.[0]?.productDetails?.map((item) => ({
        key: item?.InwardDtlId,
        ...item,
      }));
      setSalesDetail(tempListData);
    } else {
      setSalesDetail([]);
      setFullSalesDetail([]);

      if (segmentValue == 'Mobile' && billormobile && fromDate && toDate) {
        setMessageType('error');
        setMessageData(res?.data?.response);
      } else {
        setMessageType('error');
        setMessageData(res?.data?.response);
      }
    }
    setisdisabled(true);
  };

  const fetchPaymentOption = async () => {
    await dispatch(getPaymentOptions()).unwrap();
  };

  const GetCancellationReason = async () => {
    let data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
    };
    let res = await dispatch(getCancelReshRules(data)).unwrap();
    if (res?.data?.statusCode === 1) {
      let getActivedatas = res?.data?.data?.filter(
        (item) => item?.ActiveStatus === 'A' && item?.ActivityType === 'C'
      );
      let getReschDatas = res?.data?.data?.filter(
        (item) => item?.ActiveStatus === 'A' && item?.ActivityType === 'R'
      );
      setCanReason(getActivedatas);
      setRescheduleReason(getReschDatas);
    } else {
      setCanReason([]);
      setRescheduleReason([]);
    }
  };

  const selectCancelOrPaymentType = (e) => {
    setisdisabled(true);
    setselCancelPay(e);
    formRef.current?.resetFields();
    setSelectedOrderId();
    // setSelPayMode()
    setSelectedRowKey(null);
    setFullSalesDetail([]);
  };

  const selectActivityType = (e) => {
    setisdisabled(true);
    setselActivityType(e);
    formRef.current?.resetFields();
    setSelectedOrderId();
    setSelectedRowKey(null);
    setFullSalesDetail([]);
  };

  // Debounce utility
  const debounce = (func, delay) => {
    let timer;
    return (...args) => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        func(...args);
      }, delay);
    };
  };

  const getSalesDetailapi = debounce(async (e) => {
    setSelectedOrderId(e);
    if (segmentValue === 'Bill No') {
      selActivityType === 'Cancel' ? getSalesOrderDetail() : getPaymentMode();
      return;
    }
    let fromDate;
    let toDate;
    if (selCancelPay === 'CR') {
      if (selActivityType === 'Cancel') {
        fromDate = formRef.current?.getFieldsValue()?.CancelFromDate;
        toDate = formRef.current?.getFieldsValue()?.CancelToDate;
      } else if (selActivityType === 'Reschedule') {
        fromDate = formRef.current?.getFieldsValue()?.ReschedulFromDate;
        toDate = formRef.current?.getFieldsValue()?.ReschedulToDate;
      }
    } else if (selCancelPay === 'CP') {
      fromDate = formRef.current?.getFieldsValue()?.['Change-PaymentFromDate'];
      toDate = formRef.current?.getFieldsValue()?.['Change-PaymentToDate'];
    }
    if (
      segmentValue === 'Mobile' &&
      fromDate != undefined &&
      toDate !== undefined
    ) {
      selActivityType === 'Cancel' ? getSalesOrderDetail() : getPaymentMode();
    } else {
      setMessageType('error');
      setMessageData('Please select From Date and To Date');
    }
  }, 300);

  const selectCancelType = (e) => {
    setSelCancelType(e);
  };

  const onOrderSelectChange = (newselectedRowKeys) => {
    setSelectedRowKeys(newselectedRowKeys);
  };

  const getPaymentMode = async (e) => {
    let fromDate;
    let toDate;
    let date;
    const billormobile =
      formRef.current?.getFieldsValue()?.[
        selCancelPay === 'CR' ? 'OrderId' : 'PaymodeOrderId'
      ];
    if (segmentValue === 'Mobile') {
      if (selCancelPay === 'CR') {
        if (selActivityType === 'Cancel') {
          fromDate = formRef.current
            ?.getFieldsValue()
            ?.CancelFromDate?.format('YYYY-MM-DD');
          toDate = formRef.current
            ?.getFieldsValue()
            ?.CancelToDate?.format('YYYY-MM-DD');
        } else if (selActivityType === 'Reschedule') {
          fromDate = formRef.current
            ?.getFieldsValue()
            ?.ReschedulFromDate?.format('YYYY-MM-DD');
          toDate = formRef.current
            ?.getFieldsValue()
            ?.ReschedulToDate?.format('YYYY-MM-DD');
        }
      } else if (selCancelPay === 'CP') {
        fromDate = formRef.current
          ?.getFieldsValue()
          ?.['Change-PaymentFromDate']?.format('YYYY-MM-DD');
        toDate = formRef.current
          ?.getFieldsValue()
          ?.['Change-PaymentToDate']?.format('YYYY-MM-DD');
      }
    }
    if (segmentValue === 'Date') {
      const fieldname =
        selCancelPay === 'CR'
          ? selActivityType === 'Cancel'
            ? 'Canceldate'
            : 'RescheduleApidate'
          : 'Change-Paymentdate';
      date = formRef.current
        ?.getFieldsValue()
        ?.[fieldname]?.format('YYYY-MM-DD');
    }

    formRef.current?.setFieldsValue({ PaymodeOrderId: e });
    let data = {
      segmentValue,
      mobileNumber: billormobile,
      fromDate,
      toDate,
      date,
      AppId,
      CompId,
      BranchId,
      passType: false,
      OrderId:
        'O' +
        AppId +
        '-' +
        CompId +
        '-' +
        BranchId +
        '-' +
        UserId +
        '-' +
        billormobile,
    };

    const res = await dispatch(getPaymentModeDetail(data)).unwrap();
    if (res?.data?.statusCode === 1) {
      const sales = res?.data?.data;
      setFullSalesDetail(sales);
      if (segmentValue === 'Bill No') {
        const { PaymentType, PaymentTypeName, OrderId, CustSuppId } =
          sales?.[0];
        // setSelPayMode(PaymentType)
        setApiPaymentName(PaymentTypeName);
        // formRef.current?.setFieldsValue({ CpPaymentMode: PaymentType })
        const configName = PaymentOptions?.find(
          (item) => item.ConfigId === PaymentType
        )?.ConfigName;
        setSelectCust(configName === 'Credit');
        setSelectSalesId(OrderId);
        dispatch(changeSelectedCustId(CustSuppId));
        handleCustomerSelection(CustSuppId);
      } else {
      }
    } else if (res?.data?.statusCode === 0) {
      // setSelPayMode()
      // formRef.current?.setFieldsValue({ CpPaymentMode: "" })
      setSelectSalesId();
      setSelectedOrderId();
      setMessageType('error');
      setMessageData(res?.data?.response);
    }
    setisdisabled(true);
  };

  // const onChangePaymentMode = (e) => {
  //   setSelPayMode(e)
  //   formRef.current?.setFieldsValue({ CpPaymentMode: e });
  //   const selPayment = PaymentOptions?.find(item => item.ConfigId === e)
  //   setDropSelPaymentName(selPayment?.ConfigName)
  //   setSelectCust(selPayment?.ConfigName === "Credit")
  // }

  const SelectCanPaymode = (e) => {
    setSelCanPaymode(e);
    formRef.current?.setFieldsValue({ PaymentMode: e });
    selectedRowKey !== undefined && setisdisabled(false);
  };

  const defaultColumns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '100px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{index + 1}</a>
      ),
    },
    {
      title: 'Product Name',
      dataIndex: 'ProdNameQty',
      key: 'ProdNameQty',
      width: '100px',
    },

    {
      title: 'Quantity ',
      dataIndex: 'SalesQty',
      key: 'SalesQty',
      width: '100px',
      align: 'right',
      editable: true,
    },
    {
      title: 'Total Amount',
      dataIndex: 'TotalAmt',
      key: 'TotalAmt',
      width: '100px',
      align: 'right',
    },
  ];

  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 EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };

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

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

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

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

    let childNode = children;

    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              pattern: /^[1-9]\d*(\.\d+)?$/,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input
            ref={inputRef}
            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 components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const handleSave = (row) => {
    const newData = [...SalesDetail];
    const index = newData.findIndex(
      (item) => row.InwardDtlId === item.InwardDtlId
    );
    const item = newData[index];
    if (item?.SalesQty > row?.SalesQty) {
      newData.splice(index, 1, {
        ...item,
        ...row,
      });
      setSalesDetail(newData);
    } else {
      setMessageType('error');
      setMessageData('only less or equal quantity applicable.');
    }
  };

  const onChangeCanReason = async (e) => {
    formRef.current?.setFieldsValue({ CalReason: e });
    let selectedCanReason = CanReason?.filter((item) => item?.UniqueId === e);
    setSelCanReason(selectedCanReason);
    selectedRowKey !== undefined && setisdisabled(false);
  };

  const onChangeRescheduleReason = async (e) => {
    formRef.current?.setFieldsValue({ RescheduleReason: e });
    let selectedRescheduleReason = RescheduleReason?.filter(
      (item) => item?.UniqueId === e
    );
    // setSelRescheduleReason(selectedRescheduleReason)
  };

  const onFinish = async () => {
    const isCreditApi = ApiPaymentName?.toLowerCase() === 'credit';
    const isCreditDrop = DropSelPaymentName?.toLowerCase() === 'credit';

    if (selCancelPay === 'CP') {
      if (isCreditApi && isCreditDrop) {
        setMessageType('error');
        setMessageData('Not Processable data');
        return;
      }

      if (isCreditApi || (isCreditDrop && SelectCustId !== null)) {
        setCreditCustomer(true);
        return;
      }

      if (isCreditDrop && SelectCustId === null) {
        setMessageType('error');
        setMessageData('Please Select Customer');
        return;
      }

      const data = {
        AppId,
        CompId,
        BranchId,
        UpdatedBy: UserId,
        OrderId: SelectSalesId,
        CustSuppId: SelectCustId,
        PaymentModes: selectedPayments,
      };
      try {
        const response = await dispatch(putpaymentModeChange(data)).unwrap();
        if (response?.data?.statusCode === 1) {
          formRef.current?.resetFields();
          setSelectSalesId();
          // setSelPayMode();
          setMessageType('success');
          setMessageData('Payment Mode Updated Successfully');
          setSelectSalesId(SelectSalesId);
          dispatch(changeSelectedCustId(SelectCustId));
          setSelectedPayments([]);
          setSelectedRowKey(null);
          setSelectedRowKeys(null);
          setisdisabled(true);
          setSalesDetail([]);
          setFullSalesDetail([]);
          setSelectCust(false);
          dispatch(changeSelectedCustId(null));
          dispatch(changeSelectedOption({}));
          dispatch(ChangeSelectedCustDisable(false));
          SelectCanPaymode(null);
        }
      } catch (error) {
        console.error('Payment mode change failed:', error);
      }
    }
    if (selCancelPay === 'CR' && selActivityType === 'Cancel') {
      if (SelCancelType === 'OverAll') {
        const { NetAmount } = FullSalesDetail?.[0];
        const { ChargeType, ChargesFixed } = SelCanReason?.[0];

        if (ChargeType === 'P') {
          const temCanCharge = (NetAmount * ChargesFixed) / 100;
          setCancellationCharge(temCanCharge);
        } else if (ChargeType === 'F') {
          setCancellationCharge(ChargesFixed);
        }

        setIsPosting(true);
        try {
          const prodDtl = (FullSalesDetail || [])?.find(
            (f) => f.OrderId === selectedRowKey
          )?.productDetails;
          const SalesId = prodDtl?.[0]?.SalesId;
          const ProductDetails = (prodDtl || []).map(
            ({
              ProdId,
              InwardDtlId,
              Type,
              SalesQty,
              Rate,
              TaxAmt,
              SinglePc,
            }) => ({
              ProdId,
              InwardDtlId,
              Type,
              Qty: SalesQty,
              Rate,
              TotalAmt: SalesQty * Rate,
              TaxAmt,
              SinglePc,
            })
          );

          if (ProductDetails?.length === 0) {
            throw new Error('No orders selected');
          }

          const Amount = ProductDetails.reduce(
            (acc, item) => acc + (item.TotalAmt || 0),
            0
          );
          const payload = {
            AppId,
            CompId,
            BranchId,
            SalesId,
            ProductDetails,
            SalesType: 'C',
            OrderId: selectedRowKey,
            CreatedBy: UserId,
            CreatedDate: dayjs()?.format('YYYY-MM-DD'),
            OrderPaymentDtl: [
              {
                PaymentType: SelCanPaymode,
                Amount,
                PaymentStatus: 'S',
              },
            ],
          };

          const res = await dispatch(PostSalesCancellation(payload)).unwrap();
          if (res?.data?.statusCode === 1) {
            setMessageType('success');
            setMessageData(res?.data?.response || 'Posted successfully');
            setSelectedRowKey();
            formRef.current?.resetFields();
            setFullSalesDetail([]);
            SelectCanPaymode(null);
            setSegmentValue('Bill No');
          } else {
            setMessageType('success');
            setMessageData(res?.data?.response || 'Posted successfully');
          }
        } catch (error) {
          setMessageType('error');
          setMessageData(error?.message || 'An error occurred');
        } finally {
          setIsPosting(false); // enable button
        }
      }
    }
  };

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

  const CancelModalClose = () => {
    setCancelModalOpen(false);
  };

  const handleAddCustomer = () => {
    setAddCustomer(true);
  };

  const handleAddCustomerCancel = () => {
    setAddCustomer(false);
  };

  const handleOk = async () => {
    let data = {
      OrderId: SelectSalesId,
      PaymentType: 0, // SelPayMode shifayath this flow need to discuss
      UpdatedBy: getSession('UserId'),
      CustSuppId: SelectCustId,
    };
    let response = await dispatch(putpaymentStatus(data)).unwrap();
    if (response?.data?.statusCode == 1) {
      formRef.current?.resetFields();
      setSelectSalesId();
      // setSelPayMode()
      setMessageType('success');
      setMessageData('Payment Mode Updated Succesfully');
      setSelectCust(false);
      dispatch(changeSelectedCustId(null));
      dispatch(changeSelectedOption({}));
      dispatch(ChangeSelectedCustDisable(false));
    }
    setCreditCustomer(false);
  };

  const handlemodalclose = () => {
    setCreditCustomer(false);
  };

  const segmentOnChange = (value) => {
    setSegmentValue(value);
    setSelectedOrderId();
    formRef.current?.resetFields();
    setSelectedRowKey(null);
    setFullSalesDetail([]);
    setisdisabled(true);
  };

  const onChangeDate = (date) => {
    if (date) {
      selActivityType === 'Cancel' ? getSalesOrderDetail() : getPaymentMode();
    }
  };

  const onChangeFromDate = (date) => {
    if (date) {
      const formatted = date?.format('YYYY-MM-DD');
      const billormobile =
        formRef.current?.getFieldsValue()?.[
          selCancelPay === 'CR' ? 'OrderId' : 'PaymodeOrderId'
        ];
      let toDate;
      if (selCancelPay === 'CR') {
        if (selActivityType === 'Cancel') {
          toDate = formRef.current?.getFieldsValue()?.CancelToDate;
        } else if (selActivityType === 'Reschedule') {
          toDate = formRef.current?.getFieldsValue()?.ReschedulToDate;
        }
      } else if (selCancelPay === 'CP') {
        toDate = formRef.current?.getFieldsValue()?.['Change- PaymentToDate'];
      }

      if (segmentValue === 'Mobile' && formatted && toDate !== undefined) {
        if (billormobile === undefined) {
          setMessageType('error');
          setMessageData('Please enter the mobile number.');
        } else {
          selActivityType === 'Cancel'
            ? getSalesOrderDetail()
            : getPaymentMode();
        }
      }
    }
  };

  const onChangeToDate = (date) => {
    if (date) {
      const formatted = date?.format('YYYY-MM-DD');
      const billormobile =
        formRef.current?.getFieldsValue()?.[
          selCancelPay === 'CR' ? 'OrderId' : 'PaymodeOrderId'
        ];
      let fromDate;
      if (selCancelPay === 'CR') {
        if (selActivityType === 'Cancel') {
          fromDate = formRef.current?.getFieldsValue()?.CancelFromDate;
        } else if (selActivityType === 'Reschedule') {
          fromDate = formRef.current?.getFieldsValue()?.ReschedulFromDate;
        }
      } else if (selCancelPay === 'CP') {
        fromDate =
          formRef.current?.getFieldsValue()?.['Change-PaymentFromDate'];
      }
      if (segmentValue === 'Mobile' && fromDate != undefined && formatted) {
        if (billormobile === undefined) {
          setMessageType('error');
          setMessageData('Please enter the mobile number.');
        } else {
          selActivityType === 'Cancel'
            ? getSalesOrderDetail()
            : getPaymentMode();
        }
      }
    }
  };

  const viewOrderdetails = (prdDetls) => {
    setViewProductDetails({
      view: true,
      productDetails: prdDetls,
    });
  };

  const viewPaymentdetails = (pymDetls) => {
    setViewPaymentDetails({
      view: true,
      paymentDetails: pymDetls,
    });
  };

  const paymentModeOnChange = (newPaymentType, UniqueId) => {
    setisdisabled(false);
    setSelectedPayments((prev) => {
      if (!Array.isArray(prev)) {
        console.error('prev is not an array!', prev);
        return [];
      }

      const updated = [...prev];
      const index = updated.findIndex((item) => item.UniqueId === UniqueId);

      const newItem = {
        PaymentType: newPaymentType,
        UniqueId: UniqueId,
      };

      if (index !== -1) {
        updated[index] = newItem; // overwrite existing
      } else {
        updated.push(newItem); // add new
      }

      return updated;
    });
  };

  const paymentRowRadiocolumns = [
    {
      title: 'PaymentType Name',
      dataIndex: 'PaymentTypeName',
      key: 'PaymentTypeName',
      width: '100px',
      render: (text) => <span>{text ?? '-'}</span>,
    },
    {
      title: 'Order Date',
      dataIndex: 'CreatedDate',
      key: 'CreatedDate',
      width: '100px',
      render: (text) => <span>{ExtractDateFormate(text)}</span>,
    },
    {
      title: 'Amount',
      dataIndex: 'Amount',
      key: 'Amount',
      width: '100px',
    },
    {
      title: 'Change PaymentType',
      dataIndex: 'PaymentType',
      key: 'PaymentType',
      width: '100px',
      render: (text, record) => {
        const { UniqueId } = record;
        const selectedItem = PaymentOptions?.find(
          (item) => item.UniqueId === UniqueId
        )?.PaymentType;
        return (
          <DropDowns
            className="field-DropDown"
            valueData={selectedItem}
            isOnChange={!!selectedItem}
            label={<label class="required">Change Payment Mode</label>}
            onChangeFunction={(e) => paymentModeOnChange(e, UniqueId)}
            options={PaymentOptions?.filter((f) => f.ConfigId !== text)?.map(
              (option) => ({
                value: option.ConfigId,
                label: option.ConfigName,
              })
            )}
          />
        );
      },
    },
  ];
  const viewPaymentColumns = [
    {
      title: 'PaymentType Name',
      dataIndex: 'PaymentTypeName',
      key: 'PaymentTypeName',
      width: '100px',
    },
    {
      title: 'Order Date',
      dataIndex: 'CreatedDate',
      key: 'CreatedDate',
      width: '100px',
      render: (text) => <span>{ExtractDateFormate(text)}</span>,
    },
    {
      title: 'Amount',
      dataIndex: 'Amount',
      key: 'Amount',
      width: '100px',
    },
  ];

  const productDetailscolumns = [
    {
      title: appPreferences ? 'Slot' : 'Product Name',
      dataIndex: 'ProdName',
      key: 'ProdName',
      width: '100px',
      render: (text, record) => (
        <span>
          {record?.ProdName +
            (record?.Size
              ? ' - ' +
                record?.Size +
                (record?.UomName ? ' - ' + record?.UomName : '')
              : '')}
        </span>
      ),
    },
    {
      title: 'Variant Name',
      dataIndex: 'ProdVariantName',
      key: 'ProdVariantName',
      width: '100px',
    },
    {
      title: 'Quantity',
      dataIndex: 'SalesQty',
      key: 'SalesQty',
      width: '100px',
    },
    {
      title: 'Rate',
      dataIndex: 'Rate',
      key: 'Rate',
      width: '100px',
    },
    {
      title: 'Total Amount',
      dataIndex: 'TotalAmt',
      key: 'TotalAmt',
      width: '100px',
    },
  ];

  const rowradiocolumns = [
    {
      title: 'Order Id',
      dataIndex: 'OrderId',
      key: 'OrderId',
      width: '100px',
      render: (text) => <span>{text.match(/\d+/g).pop()}</span>,
    },
    {
      title: 'Order Date',
      dataIndex: 'OrderDate',
      key: 'OrderDate',
      width: '100px',
      render: (text) => <span>{ExtractDateFormate(text)}</span>,
    },
    {
      title: 'Net Amount',
      dataIndex: 'NetAmount',
      key: 'NetAmount',
      width: '100px',
    },
    {
      title: 'Order Payment Details',
      dataIndex: 'OrderPaymentDtls',
      key: 'OrderPaymentDtls',
      width: '100px',
      render: (OrderPaymentDtls) => (
        <span>
          {OrderPaymentDtls?.length === 0 ? (
            'No Record Exist'
          ) : (
            <IoEye
              style={{ color: '#1292EE', fontSize: '25px', cursor: 'pointer' }}
              onClick={() => viewPaymentdetails(OrderPaymentDtls)}
            />
          )}
        </span>
      ),
    },
    {
      title: 'Customer Details',
      dataIndex: 'CustomerDetails',
      key: 'CustomerDetails',
      width: '100px',
      render: (CustomerDetails) => (
        <div>
          <span>
            {CustomerDetails?.[0]?.CustSuppName
              ? CustomerDetails?.[0]?.CustSuppName + ' / '
              : ''}
          </span>
          <span>
            {CustomerDetails?.[0]?.MobileNo
              ? CustomerDetails?.[0]?.MobileNo
              : CustomerDetails?.[0]?.CustSuppName
                ? '-'
                : 'No Details Found'}
          </span>
        </div>
      ),
    },
    //  {
    //   title: 'BookingType Name',
    //   dataIndex: 'BookingTypeName',
    //   key: 'BookingTypeName',
    //   width: '100px',
    // },
    ...(appPreferences
      ? []
      : [
          {
            title: 'BookingType Name',
            dataIndex: 'BookingTypeName',
            key: 'BookingTypeName',
            width: '100px',
          },
        ]),
    {
      title: sportsAppPreference ? 'Slot Details' : 'Product Details',
      dataIndex: 'productDetails',
      key: 'productDetails',
      width: '100px',
      render: (ProductDetail) => (
        <IoEye
          style={{ color: '#1292EE', fontSize: '25px', cursor: 'pointer' }}
          onClick={() => viewOrderdetails(ProductDetail)}
        />
      ),
    },
  ];

  const handleCustomerSelection = async (CustSuppId) => {
    if (CustSuppId) {
      // Get all customers
      const responseAllCustomer = await dispatch(
        getAllCustomer({ CompId, AppId, branchId: BranchId })
      ).unwrap();

      // Find the selected customer
      const selected = responseAllCustomer?.data?.data?.find(
        (item) => item.CustId === CustSuppId
      );
      if (selected) {
        const { CustId, CustName, CustMobile } = selected;
        dispatch(
          changeSelectedOption({
            CustId,
            CustName,
            label: CustName ? CustName : CustMobile,
            value: CustMobile,
          })
        );
        dispatch(ChangeSelectedCustDisable(true));
      }

      // Get credit customer data
      const responseCreditCustomer = await dispatch(
        getCreditCustomer({
          CompId,
          BranchId,
          AppId,
          CustId: CustSuppId,
        })
      ).unwrap();

      if (responseCreditCustomer?.data?.statusCode === 1) {
        setCreditCustDetails(responseCreditCustomer?.data?.data);
      } else {
        if (responseAllCustomer?.data?.statusCode === 1) {
          const selectedCustomer = responseAllCustomer?.data?.data?.filter(
            (item) => item?.CustId === CustSuppId
          );
          setNewCustomer(selectedCustomer);
        } else {
          setNewCustomer([]);
        }
        setCreditCustDetails([]);
      }
    } else {
      dispatch(changeSelectedOption({}));
      dispatch(ChangeSelectedCustDisable(false));
    }
  };

  const rowSelection = {
    type: 'radio',
    selectedRowKeys: selectedRowKey !== null ? [selectedRowKey] : [],
    onChange: (selectedRowKeys, selectedRows) => {
      setisdisabled(selCancelPay === 'CR' ? false : true);
      setSelectedRowKey(selectedRowKeys[0]);
      const { OrderId, CustSuppId } = FullSalesDetail?.find(
        (f) => f.OrderId === selectedRowKeys[0]
      );
      setSelectSalesId(OrderId);
      dispatch(changeSelectedCustId(CustSuppId));
      setSelectedPayments([]);
      if (selCancelPay === 'CR') {
        handleCustomerSelection(CustSuppId);
      }
    },
  };

  return (
    <>
      <div className="pageOverAll">
        <div className="userPage">
          <div className="userPageContent">
            <Messages
              messageType={messageType}
              messageData={messageData}
              onComplete={onComplete}
            />
            <div className="formName">
              <FormHeader title={'Cancel / Payment Change'} />
            </div>
            <div className="formDiv">
              <div className="Cancelform">
                <Form ref={formRef} onFinish={onFinish}>
                  <div className="CancelPay-div">
                    <div
                      style={{
                        display: 'flex',
                        width: '100%',
                        flexDirection: 'column',
                      }}
                    >
                      <div
                        style={{
                          display: 'flex',
                          gap: '1rem',
                          border: '1px solid rgb(163, 163, 163)',
                          padding: '0.5rem',
                          borderRadius: '10px',
                          alignItems: 'center',
                        }}
                      >
                        <div
                          style={{
                            display: 'flex',
                            gap: '0.5rem',
                            alignItems: 'center',
                            flexWrap: 'wrap',
                          }}
                        >
                          <div style={{ fontWeight: 500 }}>Mode Type :</div>
                          <Segmented
                            size="medium"
                            options={[
                              {
                                value: 'CR',
                                // label: 'Cancellation/Re-scheduling',
                                label: 'Cancellation',
                              },
                              { value: 'CP', label: 'Change Payment Mode' },
                            ]}
                            value={selCancelPay}
                            onChange={(value) =>
                              selectCancelOrPaymentType(value)
                            }
                          />
                        </div>
                        <Divider
                          type="vertical"
                          style={{ height: '2.5rem', borderColor: '#ccc' }}
                        />
                        {/* <div
                          style={{
                            display: 'flex',
                            gap: '0.5rem',
                            alignItems: 'center',
                          }}
                        >
                          <div style={{ fontWeight: 500 }}>
                            Search Bill Type :
                          </div>
                          <Segmented
                            size="large"
                            options={['Bill No', 'Mobile Number', 'Date']}
                            value={segmentValue}
                            onChange={segmentOnChange}
                          />
                        </div> */}
                      </div>
                    </div>
                    {selCancelPay === 'CR' && (
                      <div
                        className="Cancel-resche"
                        style={{ borderRadius: '10px' }}
                      >
                        {/* <div>
                          <Form.Item name="ActivityType">
                            <li className="drp_btn_Emp">
                              <div>
                                <div
                                  style={{ marginBottom: 8, fontWeight: 500 }}
                                >
                                  Activity Type :
                                </div>
                                <Segmented
                                  options={[
                                    { value: 'Cancel', label: 'Cancellation' },
                                    {
                                      value: 'Reschedule',
                                      label: 'Re-scheduling',
                                    },
                                  ]}
                                  value={selActivityType}
                                  onChange={(value) =>
                                    selectActivityType(value)
                                  }
                                />
                              </div>
                            </li>
                          </Form.Item>
                        </div> */}

                        <div
                          style={{
                            display: 'flex',
                            gap: '0.5rem',
                            alignItems: 'center',
                          }}
                        ></div>
                        {selActivityType === 'Cancel' && (
                          <div className="Cancellation-div">
                            <div style={{ marginBottom: '10px' }}>
                              <DropDowns
                                options={[
                                  { value: 'Bill No', label: 'Bill No' },
                                  { value: 'Mobile', label: 'Mobile Number' },
                                  { value: 'Date', label: 'Date' },
                                ]}
                                label={'Bill Type'} // No label inside dropdown; we already have label outside
                                className="field-DropDown"
                                onChangeFunction={(e) => segmentOnChange(e)}
                                valueData={segmentValue}
                                isOnChange={true}
                              />
                            </div>
                            <div
                              style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '10px',
                                // marginTop: '10px',
                                flexWrap: 'wrap',
                              }}
                            >
                              {segmentValue === 'Date' ? (
                                <Form.Item
                                  name="Canceldate"
                                  label="Date"
                                  rules={[
                                    {
                                      required: true,
                                      message: 'Please select Date',
                                    },
                                  ]}
                                >
                                  <DatePicker
                                    onChange={onChangeDate}
                                    disabledDate={disabledDate}
                                  />
                                </Form.Item>
                              ) : (
                                <Form.Item
                                  name="OrderId"
                                  rules={[
                                    {
                                      validator: async (_, value) => {
                                        await validateSafeInput(value); // Your existing input sanitization

                                        if (!value) {
                                          return Promise.reject(
                                            `Please enter ${segmentValue}`
                                          );
                                        }

                                        const digitOnlyRegex = /^[0-9]+$/;
                                        if (!digitOnlyRegex.test(value)) {
                                          return Promise.reject(
                                            `${segmentValue} should contain digits only`
                                          );
                                        }

                                        if (segmentValue === 'Bill No') {
                                          if (value.length > 30) {
                                            return Promise.reject(
                                              'Bill No should not exceed 30 characters'
                                            );
                                          }
                                        }

                                        if (segmentValue === 'Mobile') {
                                          const mobileRegex = /^[6-9]\d{9}$/;

                                          if (!value || value.length !== 10) {
                                            return Promise.reject(
                                              'Mobile Number must be exactly 10 digits'
                                            );
                                          }

                                          if (!mobileRegex.test(value)) {
                                            return Promise.reject(
                                              'Mobile number must start with 6, 7, 8, or 9'
                                            );
                                          }

                                          await getSalesDetailapi(value);
                                        }
                                        await getSalesDetailapi(value);
                                        return Promise.resolve();
                                      },
                                    },
                                  ]}
                                >
                                  <InputField
                                    field="OrderId"
                                    autoComplete="off"
                                    inputMode="numeric"
                                    maxLength={
                                      segmentValue === 'Mobile' ? 10 : 30
                                    }
                                    onInput={(e) =>
                                      (e.target.value = e.target.value.replace(
                                        /[^0-9]/g,
                                        ''
                                      ))
                                    }
                                    label={
                                      <label class="required">
                                        {segmentValue}
                                      </label>
                                    }
                                    isOnChange={SelectedOrderId ? true : false}
                                  />
                                </Form.Item>
                              )}
                              {segmentValue === 'Mobile' && (
                                <div
                                  style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '10px',
                                    flexWrap: 'wrap',
                                  }}
                                >
                                  <Form.Item
                                    label="From Date"
                                    name="CancelFromDate"
                                    rules={[
                                      {
                                        required: true,
                                        message: 'Please select From Date',
                                      },
                                    ]}
                                  >
                                    <DatePicker
                                      format="YYYY-MM-DD"
                                      onChange={onChangeFromDate}
                                      disabledDate={disabledDate}
                                    />
                                  </Form.Item>

                                  <Form.Item
                                    label="To Date"
                                    name="CancelToDate"
                                    rules={[
                                      {
                                        required: true,
                                        message: 'Please select To Date',
                                      },
                                    ]}
                                  >
                                    <DatePicker
                                      format="YYYY-MM-DD"
                                      onChange={onChangeToDate}
                                      disabledDate={disabledDate}
                                    />
                                  </Form.Item>
                                </div>
                              )}
                            </div>

                            <div>
                              <Form.Item
                                name="CalReason"
                                rules={[
                                  {
                                    required: true,
                                    pattern: /^(?!\s*$).+/,
                                    message: 'Please Enter Cancellation Reason',
                                  },
                                ]}
                              >
                                <DropDowns
                                  options={CanReason?.map((option) => ({
                                    value: option.UniqueId,
                                    label: option.Description,
                                  }))}
                                  label={
                                    <label class="required">
                                      Cancellation Reason
                                    </label>
                                  }
                                  className="field-DropDown"
                                  onChangeFunction={(e) => onChangeCanReason(e)}
                                  // valueData={seletedprodDropdown}
                                  isOnChange={
                                    formRef.current?.getFieldsValue()
                                      ?.CalReason != undefined
                                      ? true
                                      : false
                                  }
                                />
                              </Form.Item>
                            </div>
                            <div>
                              <Form.Item
                                name="PaymentMode"
                                rules={[
                                  {
                                    required: true,
                                    pattern: /^(?!\s*$).+/,
                                    message: 'Please Enter Payment Mode',
                                  },
                                ]}
                              >
                                <DropDowns
                                  options={paybtns?.map((option) => ({
                                    value: option.ConfigId,
                                    label: option.ConfigName,
                                  }))}
                                  label={
                                    <label class="required">
                                      Refund Payment Mode
                                    </label>
                                  }
                                  className="field-DropDown"
                                  onChangeFunction={(e) => SelectCanPaymode(e)}
                                  valueData={SelCanPaymode}
                                />
                              </Form.Item>
                            </div>

                            {/* {SalesDetail?.length > 0 &&
                              selectedRowKey !== null && (
                                <div>
                                  <Form.Item name="CancelType">
                                    <li className="drp_btn_Emp">
                                      <div className="Cancel-Form-radio">
                                        <Segmented
                                          options={[
                                            {
                                              value: 'OverAll',
                                              label: 'OverAll Cancellation',
                                            },
                                            {
                                              value: 'ProdCancel',
                                              label: 'Product Cancel',
                                            },
                                          ]}
                                          value={SelCancelType}
                                          onChange={(value) =>
                                            selectCancelType(value)
                                          }
                                          size="large"
                                        />
                                      </div>
                                    </li>
                                  </Form.Item>
                                </div>
                              )} */}
                            {/* {SelCancelType === 'ProdCancel' && SalesDetail && (
                              <div style={{ width: '100%' }}>
                                <Table
                                  columns={columns}
                                  components={components}
                                  rowClassName={() => 'editable-row'}
                                  bordered
                                  data={SalesDetail}
                                  dataSource={SalesDetail}
                                  rowSelection={{
                                    selectedRowKeys,
                                    onChange: onOrderSelectChange,
                                  }}
                                />
                              </div>
                            )} */}
                          </div>
                        )}
                        {/* {selActivityType === 'Reschedule' && (
                          <div className="Reschedule-div">
                             <DropDowns
                                options={[
                                { value: 'Bill No', label: 'Bill No' },
                                { value: 'Mobile', label: 'Mobile Number' },
                                { value: 'Date', label: 'Date' },
                                ]}
                                label={'Bill Type'} // No label inside dropdown; we already have label outside
                                className="field-DropDown"
                                onChangeFunction={(e) => segmentOnChange(e)}
                                valueData={segmentValue}
                                isOnChange={true}
                              />
                            <div
                              style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '10px',
                              }}
                            >
                              {segmentValue === 'Date' ? (
                                <Form.Item
                                  name="RescheduleApidate"
                                  label="Date"
                                  rules={[
                                    {
                                      required: true,
                                      message: 'Please select Date',
                                    },
                                  ]}
                                >
                                  <DatePicker
                                    onChange={onChangeDate}
                                    disabledDate={disabledDate}
                                  />
                                </Form.Item>
                              ) : (
                                <Form.Item
                                  name="OrderId"
                                  rules={[
                                    {
                                      required: true,
                                      pattern: /^[0-9]+$/, // only digits allowed
                                      message: `Please enter a valid ${segmentValue} (numbers only)`,
                                    },
                                    {
                                      validator: async (_, value) => {
                                        await validateSafeInput(value);

                                        if (
                                          segmentValue === 'Bill No' &&
                                          value &&
                                          value.length > 30
                                        ) {
                                          return Promise.reject(
                                            'Bill No should not exceed 30 characters'
                                          );
                                        }
                                        if (
                                          segmentValue === 'Mobile' &&
                                          value &&
                                          value.length > 10
                                        ) {
                                          return Promise.reject(
                                            'Mobile Number should not exceed 30 characters'
                                          );
                                        }
                                       
                                        if (
                                          segmentValue === 'Mobile' &&
                                          value &&
                                          value.length === 10
                                        ) {
                                          getSalesDetailapi(value);
                                        }
                                        return Promise.resolve();
                                      },
                                    },
                                  ]}
                                >
                                  <InputField
                                    field="OrderId"
                                    autoComplete="off"
                                    label={
                                      <label class="required">
                                        {segmentValue}
                                      </label>
                                    }
                                  />
                                </Form.Item>
                              )}
                              {segmentValue === 'Mobile' && (
                                <div
                                  style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '10px',
                                  }}
                                >
                                  <Form.Item
                                    label="From Date"
                                    name="ReschedulFromDate"
                                    rules={[
                                      {
                                        required: true,
                                        message: 'Please select From Date',
                                      },
                                    ]}
                                  >
                                    <DatePicker
                                      format="YYYY-MM-DD"
                                      disabledDate={disabledDate}
                                      onChange={onChangeFromDate}
                                    />
                                  </Form.Item>

                                  <Form.Item
                                    label="To Date"
                                    name="ReschedulToDate"
                                    rules={[
                                      {
                                        required: true,
                                        message: 'Please select To Date',
                                      },
                                    ]}
                                  >
                                    <DatePicker
                                      format="YYYY-MM-DD"
                                      onChange={onChangeToDate}
                                      disabledDate={disabledDate}
                                    />
                                  </Form.Item>
                                </div>
                              )}
                            </div>
                            <div>
                              <Form.Item
                                name="RescheduleReason"
                                rules={[
                                  {
                                    required: true,
                                    pattern: /^(?!\s*$).+/,
                                    message: 'Please Enter Reschedule Reason',
                                  },
                                ]}
                              >
                                <DropDowns
                                  options={RescheduleReason?.map((option) => ({
                                    value: option.UniqueId,
                                    label: option.Description,
                                  }))}
                                  label={
                                    <label class="required">
                                      Reschedule Reason
                                    </label>
                                  }
                                  className="field-DropDown"
                                  onChangeFunction={(e) =>
                                    onChangeRescheduleReason(e)
                                  }
                                  isOnChange={
                                    formRef.current?.getFieldsValue()
                                      ?.RescheduleReason != undefined
                                      ? true
                                      : false
                                  }
                                />
                              </Form.Item>
                            </div>
                            <Form.Item
                              name="Rescheduledate"
                              label="Reshedule Date"
                              rules={[
                                {
                                  required: true,
                                  message: 'Please select Date',
                                },
                              ]}
                            >
                              <DatePicker
                                onChange={onChangeDate}
                                disabledDate={disabledFeatureDate}
                              />
                            </Form.Item>
                          </div>
                        )} */}
                        {FullSalesDetail?.length > 0 && (
                          <Table
                            rowSelection={rowSelection}
                            columns={rowradiocolumns}
                            rowKey="OrderId"
                            dataSource={FullSalesDetail}
                          />
                        )}
                      </div>
                    )}
                    {selCancelPay === 'CP' && (
                      <div
                        className="Change-Payment"
                        style={{ borderRadius: '10px' }}
                      >
                        <div className="Reschedule-div">
                          <div style={{ marginBottom: '20px' }}>
                            <DropDowns
                              options={[
                                { value: 'Bill No', label: 'Bill No' },
                                { value: 'Mobile', label: 'Mobile Number' },
                                { value: 'Date', label: 'Date' },
                              ]}
                              label={'Bill Type'} // No label inside dropdown; we already have label outside
                              className="field-DropDown"
                              onChangeFunction={(e) => segmentOnChange(e)}
                              valueData={segmentValue}
                              isOnChange={true}
                            />
                          </div>
                          <div
                            style={{
                              display: 'flex',
                              alignItems: 'center',
                              gap: '10px',
                            }}
                          >
                            {segmentValue === 'Date' ? (
                              <Form.Item
                                name="Change-Paymentdate"
                                label="Date"
                                rules={[
                                  {
                                    required: true,
                                    message: 'Please select Date',
                                  },
                                ]}
                              >
                                <DatePicker
                                  disabledDate={disabledDate}
                                  onChange={onChangeDate}
                                />
                              </Form.Item>
                            ) : (
                              <Form.Item
                                name="PaymodeOrderId"
                                rules={[
                                  {
                                    required: true,
                                    pattern: /^[0-9]+$/, // only digits allowed
                                    message: `Please enter a valid ${segmentValue} (numbers only)`,
                                  },
                                  {
                                    validator: async (_, value) => {
                                      await validateSafeInput(value); // Your existing input sanitization

                                      if (!value) {
                                        return Promise.reject(
                                          `Please enter ${segmentValue}`
                                        );
                                      }

                                      const digitOnlyRegex = /^[0-9]+$/;
                                      if (!digitOnlyRegex.test(value)) {
                                        return Promise.reject(
                                          `${segmentValue} should contain digits only`
                                        );
                                      }

                                      if (segmentValue === 'Bill No') {
                                        if (value.length > 30) {
                                          return Promise.reject(
                                            'Bill No should not exceed 30 characters'
                                          );
                                        }
                                      }

                                      if (segmentValue === 'Mobile') {
                                        const mobileRegex = /^[6-9]\d{9}$/;

                                        if (!value || value.length !== 10) {
                                          return Promise.reject(
                                            'Mobile Number must be exactly 10 digits'
                                          );
                                        }

                                        if (!mobileRegex.test(value)) {
                                          return Promise.reject(
                                            'Mobile number must start with 6, 7, 8, or 9'
                                          );
                                        }

                                        await getSalesDetailapi(value);
                                      }
                                      await getSalesDetailapi(value);
                                      return Promise.resolve();
                                    },
                                  },
                                ]}
                              >
                                <InputField
                                  field="PaymodeOrderId"
                                  autoComplete="off"
                                  label={
                                    <label className="required">
                                      {segmentValue}
                                    </label>
                                  }
                                  isOnChange={
                                    formRef.current?.getFieldsValue()
                                      ?.PaymodeOrderId !== undefined
                                  }
                                />
                              </Form.Item>
                            )}
                            {segmentValue === 'Mobile' && (
                              <div
                                style={{
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '10px',
                                }}
                              >
                                <Form.Item
                                  label="From Date"
                                  name="Change-PaymentFromDate"
                                  rules={[
                                    {
                                      required: true,
                                      message: 'Please select From Date',
                                    },
                                  ]}
                                >
                                  <DatePicker
                                    format="YYYY-MM-DD"
                                    onChange={onChangeFromDate}
                                    disabledDate={disabledDate}
                                  />
                                </Form.Item>

                                <Form.Item
                                  label="To Date"
                                  name="Change-PaymentToDate"
                                  rules={[
                                    {
                                      required: true,
                                      message: 'Please select To Date',
                                    },
                                  ]}
                                >
                                  <DatePicker
                                    format="YYYY-MM-DD"
                                    onChange={onChangeToDate}
                                    disabledDate={disabledDate}
                                  />
                                </Form.Item>
                              </div>
                            )}
                            {/* <Form.Item
                              name="CpPaymentMode"
                              rules={[
                                {
                                  required: true,
                                  pattern: /^(?!\s*$).+/,
                                  message: "Please Enter Payment Mode",
                                },
                              ]}
                            >
                              <DropDowns
                                options={(paymentSelectedRowKey !== null ? PaymentOptions?.filter(f => f.ConfigId !== paymentSelectedRowKey) : PaymentOptions)?.map((option) => ({
                                  value: option.ConfigId,
                                  label: option.ConfigName,
                                }))}
                                label={<label class="required">Payment Mode</label>}
                                className="field-DropDown"
                                onChangeFunction={(e) => onChangePaymentMode(e)}
                                valueData={SelPayMode}
                                isOnChange={
                                  SelPayMode
                                    ? true
                                    : false
                                }
                              />
                            </Form.Item> */}
                            {SelectCust && (
                              <div>
                                <FeaturesFunctionalities
                                  handleAddCustomerCancel={
                                    handleAddCustomerCancel
                                  }
                                  addcustomer={addcustomer}
                                />
                                <div
                                  style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    columnGap: '0.5rem',
                                  }}
                                >
                                  <BSCustomerSelect />

                                  <Tooltip title={'Add Customer'}>
                                    {' '}
                                    <PozoAddCustomerIcon
                                      className="BSBillingNav-icon-table-icon"
                                      onClick={handleAddCustomer}
                                      style={{
                                        fontSize: '25px',
                                        // color: selOption || GetCustId ? "#52c41a" : "#1292EE",
                                        // cursor: Custdisable ? "not-allowed" : "pointer"
                                      }}
                                    />
                                  </Tooltip>
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                        <div
                          style={{ display: 'flex', flexDirection: 'column' }}
                        >
                          {selectedRowKey !== null && (
                            <>
                              <Table
                                columns={paymentRowRadiocolumns}
                                rowKey="PaymentType"
                                dataSource={
                                  FullSalesDetail?.find(
                                    (f) => f.OrderId === selectedRowKey
                                  )?.OrderPaymentDtls
                                }
                              />
                            </>
                          )}
                          {FullSalesDetail?.length > 0 && (
                            <div
                              style={{
                                height: '60vh',
                                overflow: 'auto',
                              }}
                            >
                              <Table
                                rowSelection={rowSelection}
                                columns={rowradiocolumns}
                                rowKey="OrderId"
                                dataSource={FullSalesDetail}
                              />
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>

                  <div className="ChngPayment-submitButton">
                    <Buttons
                      buttonText="SUBMIT"
                      color="901D77"
                      icon={<ArrowRightOutlined />}
                      disabled={addnewAccess}
                    />
                  </div>
                </Form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <Modal
        open={viewPaymentDetails?.view}
        title={<FormHeader title={'Payment Details'} />}
        footer={false}
        width={900}
        onCancel={() => {
          setViewPaymentDetails({
            view: false,
            paymentDetails: [],
          });
        }}
        // onOk={() => {
        //   setViewPaymentDetails({
        //     view: false,
        //     paymentDetails: [],
        //   });
        // }}
        children={
          <Table
            columns={viewPaymentColumns}
            dataSource={viewPaymentDetails?.paymentDetails}
          />
        }
      />
      <Modal
        open={viewProductDetails?.view}
        title={
          <FormHeader
            title={sportsAppPreference ? 'Slot Details' : 'Product Details'}
          />
        }
        width={900}
        footer={false}
        onCancel={() => {
          setViewProductDetails({
            view: false,
            productDetails: [],
          });
        }}
        // onOk={() => {
        //   setViewProductDetails({
        //     view: false,
        //     productDetails: [],
        //   });
        // }}
        children={
          <Table
            columns={productDetailscolumns}
            dataSource={viewProductDetails?.productDetails}
          />
        }
      />

      <Modal
        open={CancelModalOpen}
        title={<FormHeader title={'Are You Sure To Cancel'} />}
        width={500}
        onCancel={CancelModalClose}
        onOk={OverAllOrderCancel}
        children={
          <div style={containerStyle}>
            <div style={rowStyle}>
              <div style={labelStyle}>Your Bill Amount:</div>
              <div style={valueStyle}>{FullSalesDetail?.[0]?.NetAmount}</div>
            </div>
            <div style={rowStyle}>
              <div style={labelStyle}>Cancellation Charge :</div>
              <div style={valueStyle}>{CancellationCharge}</div>
            </div>
            <div style={rowStyle}>
              <div style={labelStyle}>Remain Amount :</div>
              <div style={valueStyle}>
                {FullSalesDetail?.[0]?.NetAmount - CancellationCharge}
              </div>
            </div>
          </div>
        }
      />
      <Modal
        open={CreditCustomer}
        title={<FormHeader title={'Customer Details'} />}
        width={500}
        onOk={handleOk}
        onCancel={handlemodalclose}
        children={
          <>
            <br />
            <div className="CreditCustomerMainDiv">
              <div>
                <div className="CreCustIdDiv">
                  <div style={{ fontSize: '16px', fontWeight: '600' }}>
                    Mobile Number :{' '}
                    <span style={{ fontSize: '16px', fontWeight: '400' }}>
                      {CreditCustDetails?.length > 0
                        ? CreditCustDetails?.[0]?.MobileNo
                        : NewCustomer?.[0]?.MobileNo}
                    </span>
                  </div>
                  <div style={{ fontSize: '16px', fontWeight: '600' }}>
                    Customer Id :{' '}
                    <span style={{ fontSize: '16px', fontWeight: '400' }}>
                      {CreditCustDetails?.length > 0
                        ? extractLastNumber(CreditCustDetails?.[0]?.CustId)
                        : extractLastNumber(NewCustomer?.[0]?.CustId)}
                    </span>
                  </div>
                </div>
                {CreditCustDetails?.length > 0
                  ? CreditCustDetails?.[0]?.CustName && (
                      <div style={{ fontSize: '16px', fontWeight: '600' }}>
                        Name:{' '}
                        <span style={{ fontSize: '16px', fontWeight: '400' }}>
                          {CreditCustDetails?.[0]?.CustName}{' '}
                        </span>
                      </div>
                    )
                  : NewCustomer?.[0]?.CustName && (
                      <div style={{ fontSize: '16px', fontWeight: '600' }}>
                        Name:{' '}
                        <span style={{ fontSize: '16px', fontWeight: '400' }}>
                          {NewCustomer?.[0]?.CustName}
                        </span>
                      </div>
                    )}
                {CreditCustDetails?.length > 0
                  ? CreditCustDetails?.[0]?.Address1 && (
                      <div style={{ fontSize: '16px', fontWeight: '600' }}>
                        Address:{' '}
                        <span style={{ fontSize: '16px', fontWeight: '400' }}>
                          {CreditCustDetails?.[0]?.Address1},
                          {CreditCustDetails?.[0]?.Dist}
                        </span>
                      </div>
                    )
                  : NewCustomer?.[0]?.Address1 && (
                      <div style={{ fontSize: '16px', fontWeight: '600' }}>
                        Address:{' '}
                        <span style={{ fontSize: '16px', fontWeight: '400' }}>
                          {NewCustomer?.[0]?.Address1},{NewCustomer?.[0]?.Dist}
                        </span>
                      </div>
                    )}
              </div>
              <div>
                <p style={{ fontSize: '18px', fontWeight: '600' }}>
                  Sales Details
                </p>
                {CreditCustDetails?.length > 0 ? (
                  <>
                    <div
                      style={{
                        display: 'flex',
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        width: '70%',
                        fontSize: '16px',
                        fontWeight: '600',
                      }}
                    >
                      <div style={{ fontSize: '16px', fontWeight: '500' }}>
                        {Number(CreditCustDetails?.[0]?.OverAllBal) > 0
                          ? 'Advance Amount'
                          : 'Outstanding Amount'}
                      </div>
                      <div style={{ fontSize: '16px', fontWeight: '400' }}>
                        {CreditCustDetails?.[0]?.OverAllBal &&
                          Math.abs(
                            Number(CreditCustDetails?.[0]?.OverAllBal)
                          ).toFixed(2)}
                      </div>
                    </div>
                    <div
                      style={{
                        display: 'flex',
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        width: '70%',
                        fontSize: '16px',
                        fontWeight: '600',
                      }}
                    >
                      <div style={{ fontSize: '16px', fontWeight: '500' }}>
                        Bill Amount:
                      </div>
                      <div style={{ fontSize: '16px', fontWeight: '400' }}>
                        {FullSalesDetail?.[0]?.NetAmount}
                      </div>
                    </div>
                    {ApiPaymentName?.toLowerCase() === 'credit' &&
                    DropSelPaymentName?.toLowerCase() !== 'credit' ? (
                      <div
                        style={{
                          display: 'flex',
                          flexDirection: 'row',
                          justifyContent: 'space-between',
                          width: '70%',
                          fontSize: '16px',
                          fontWeight: '600',
                        }}
                      >
                        <div style={{ fontSize: '16px', fontWeight: '500' }}>
                          {CreditCustDetails?.[0]?.OverAllBal +
                            FullSalesDetail?.[0]?.NetAmount >
                          0
                            ? 'Remaining Amount'
                            : 'Payable Amount'}
                        </div>
                        <div
                          style={{
                            color:
                              CreditCustDetails?.[0]?.OverAllBal +
                                FullSalesDetail?.[0]?.NetAmount >
                              0
                                ? 'green'
                                : 'red',
                            fontSize: '16px',
                            fontWeight: '600',
                          }}
                        >
                          {Math.abs(
                            CreditCustDetails?.[0]?.OverAllBal +
                              FullSalesDetail?.[0]?.NetAmount
                          ).toFixed(2)}
                        </div>
                      </div>
                    ) : (
                      <div
                        style={{
                          display: 'flex',
                          flexDirection: 'row',
                          justifyContent: 'space-between',
                          width: '70%',
                          fontSize: '16px',
                          fontWeight: '600',
                        }}
                      >
                        <div style={{ fontSize: '16px', fontWeight: '500' }}>
                          {CreditCustDetails?.[0]?.OverAllBal -
                            FullSalesDetail?.[0]?.NetAmount >
                          0
                            ? 'Remaining Amount'
                            : 'Payable Amount'}
                        </div>
                        <div
                          style={{
                            color:
                              CreditCustDetails?.[0]?.OverAllBal -
                                FullSalesDetail?.[0]?.NetAmount >
                              0
                                ? 'green'
                                : 'red',
                            fontSize: '16px',
                            fontWeight: '600',
                          }}
                        >
                          {Math.abs(
                            CreditCustDetails?.[0]?.OverAllBal -
                              FullSalesDetail?.[0]?.NetAmount
                          ).toFixed(2)}
                        </div>
                      </div>
                    )}
                    {CreditCustDetails?.[0]?.OverAllBal !== 0 &&
                    DropSelPaymentName?.toLowerCase() === 'credit'
                      ? CreditCustDetails?.[0]?.OverAllBal -
                          FullSalesDetail?.[0]?.NetAmount <
                          0 && (
                          <div
                            style={{
                              fontSize: '16px',
                              fontWeight: '400',
                              padding: '10px 0',
                              margin: '5px 0',
                            }}
                          >
                            {CreditCustDetails?.[0]?.MobileNo
                              ? CreditCustDetails?.[0]?.MobileNo
                              : CreditCustDetails?.[0]?.CustName}{' '}
                            customer already has an outstanding amount (
                            {CreditCustDetails?.[0]?.OverAllBal &&
                              Math.abs(
                                Number(CreditCustDetails?.[0]?.OverAllBal)
                              ).toFixed(2)}
                            ) to pay. Therefore, should we proceed with the
                            current bill amount?
                          </div>
                        )
                      : ''}
                  </>
                ) : (
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'row',
                      justifyContent: 'space-between',
                      width: '70%',
                      fontSize: '16px',
                      fontWeight: '600',
                    }}
                  >
                    <div style={{ fontSize: '16px', fontWeight: '600' }}>
                      Bill Amount:
                    </div>
                    <div>{FullSalesDetail?.[0]?.NetAmount}</div>
                  </div>
                )}
              </div>
            </div>
          </>
        }
      />
    </>
  );
};
export default ChangePaymentmode;
