import { useState, useEffect, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, useLocation } from 'react-router-dom';
import { ArrowRightOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { IoMdNotifications } from 'react-icons/io';
import { Space, Form, Tooltip } from 'antd';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { Tables } from '../../../Components/Tables/Table.jsx';
import { Search } from '../../../Components/Forms/Search.jsx';
import Buttons from '../../../Components/Forms/Buttons.jsx';
import { Messages } from '../../../Components/Notifications/Messages.jsx';
import FormHeader from '../../PageComponents/FormHeader.jsx';
import { getSession } from '../../../Services/Others.js';
import {
  gettableupi,
  delupi,
  sendupiotp,
  getupiotp,
  delPayment,
} from '../../../Features/Payment/PaymentDetails/PaymentDetails.js';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../../Features/AppPage/CenterPage.js';
import { DefaultModal } from '../../../Components/Modal/DefaultModal.jsx';
import { DropDowns } from '../../../Components/Forms/DropDown.jsx';
import { useAuth } from '../../../AuthContext.jsx';
import { FeatureAddon } from '../../../Features/BookingScreen/BookingData/BookingData.js';

const PaymentDetailsList = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Payment Details'
  );
  const navigateTo = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  //local states
  const [sortedInfo, setSortedInfo] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [tabledata, setTabledata] = useState();
  const [OtpModal, setOtpModal] = useState(false);
  const [SelectedRow, setSelectedRow] = useState();
  const [SelectedRowIndex, setSelectedRowIndex] = useState();
  const [otp1, setotp1] = useState('');
  const [otp2, setotp2] = useState('');
  const [otp3, setotp3] = useState('');
  const [otp4, setotp4] = useState('');
  const [page, setpage] = useState(1);
  const [disable, setDisable] = useState(false);
  const [Status, setStatus] = useState(false);
  const [filteredInfo, setFilteredInfo] = useState([]);
  const [detailType, setdetailType] = useState();
  const [timeLeft, setTimeLeft] = useState(null);
  const [gateWayAccess, setgateWayAccess] = useState([]);
  const [deviceAccess, setdeviceAccess] = useState([]);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const [UserType, setUserType] = useState(
    getSession('UserType') ? getSession('UserType') : 'Super Admin'
  );
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const [PaymentDatas, setPaymentDatas] = useState([]);

  const subDirectory = import.meta.env.ENV_BASE_URL;

  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },

    {
      name: 'PaymentDetails',
      link: `${subDirectory}setting/payment-details`,
    },
  ];

  const columns =
    detailType == 'upi'
      ? [
          {
            title: 'Sl.No',
            key: 'sno',
            align: 'center',
            width: '60px',
            render: (text, object, index) => (
              <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
            ),
          },
          {
            title: 'Name',
            dataIndex: 'Name',
            key: 'Name',
            width: '100px',
            render: (text) => <a style={{ color: 'black' }}>{text}</a>,
            filteredValue: [searchedText],
            onFilter: (value, record) => {
              return (
                String(record.Name)
                  ?.toLowerCase()
                  ?.includes(value?.toLowerCase()) ||
                String(record.Mobile)
                  ?.toLowerCase()
                  ?.includes(value?.toLowerCase()) ||
                String(record.Mobile)
                  ?.toLowerCase()
                  ?.includes(value?.toLowerCase()) ||
                String(record.Name)
                  ?.toLowerCase()
                  ?.includes(value?.toLowerCase())
              );
            },
            sorter: (a, b) => a?.Name?.localeCompare(b?.Name),
            sortOrder:
              sortedInfo.columnKey === 'Name' ? sortedInfo.order : null,
            ellipsis: true,
          },
          {
            title: 'Mobile No',
            dataIndex: 'Mobile',
            key: 'Mobile',
            width: '100px',
            align: 'right',
            render: (text) => <a style={{ color: 'black' }}>{text}</a>,
            sorter: (a, b) => a?.Mobile?.localeCompare(b?.Mobile),
            sortOrder:
              sortedInfo.columnKey === 'Name' ? sortedInfo.order : null,
            ellipsis: true,
          },
          {
            title: 'UPI ID',
            dataIndex: 'UPIId',
            key: 'UPIId',
            width: '100px',
            render: (text) => <a style={{ color: 'black' }}>{text}</a>,
            sorter: (a, b) => a?.UPIId?.localeCompare(b?.UPIId),
            sortOrder:
              sortedInfo.columnKey === 'UPIId' ? sortedInfo.order : null,
            ellipsis: true,
          },
          {
            title: 'UPI NAME',
            dataIndex: 'ModeName',
            key: 'ModeName',
            width: '100px',
            render: (text) => <a style={{ color: 'black' }}>{text}</a>,
            sorter: (a, b) => a?.ModeName?.localeCompare(b?.UPIId),
            sortOrder:
              sortedInfo.columnKey === 'ModeName' ? sortedInfo.order : null,
            ellipsis: true,
          },
          {
            title: 'Action',
            key: 'Action',
            dataIndex: 'Action',
            width: '100px',
            align: 'center',
            render: (_, record, index) =>
              tabledata.length >= 1 ? (
                <Space size="middle">
                  {record.ActiveStatus === 'A' ? (
                    <a>
                      <EditFilled
                        style={{ color: '#1292EE' }}
                        onClick={() =>
                          UserType === 'Super Admin' ||
                          (UserType === 'Super Admin User' &&
                            SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                          (UserType === 'Employee' &&
                            empData?.UpdateAccess === 'Y') ||
                          UserType === 'Admin'
                            ? OpenOtpModal(record, index)
                            : null
                        }
                      />
                    </a>
                  ) : (
                    ''
                  )}
                  <a>
                    {record.ActiveStatus === 'A' ? (
                      <DeleteFilled
                        style={{
                          color: '#FF4D4F',
                        }}
                        onClick={() =>
                          UserType === 'Super Admin' ||
                          (UserType === 'Super Admin User' &&
                            SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                          (UserType === 'Employee' &&
                            empData?.DeleteAccess === 'Y') ||
                          UserType === 'Admin'
                            ? statusFormatter(record)
                            : null
                        }
                      />
                    ) : (
                      <ReloadOutlined
                        style={{
                          color: '#52C41A',
                        }}
                        onClick={() =>
                          UserType === 'Super Admin' ||
                          (UserType === 'Super Admin User' &&
                            SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                          (UserType === 'Employee' &&
                            empData?.DeleteAccess === 'Y') ||
                          UserType === 'Admin'
                            ? statusFormatter(record)
                            : null
                        }
                      />
                    )}
                  </a>
                </Space>
              ) : null,
          },
        ]
      : detailType == 'bank'
        ? [
            {
              title: 'Sl.No',
              key: 'sno',
              align: 'center',
              width: '100px',
              render: (_, record, index) => (
                <a style={{ color: 'black' }}>
                  {(page - 1) * 10 + index + 1}
                  {record?.NewPaymentList.length > 0 &&
                    UserType == 'Super Admin' && (
                      <IoMdNotifications
                        style={{
                          width: '20px',
                          height: '30px',
                          color: '#ff4d4f',
                        }}
                      />
                    )}
                </a>
              ),
            },
            {
              title: 'Proprietor Name',
              dataIndex: 'ProprietorName',
              key: 'Name',
              width: '100px',
              render: (text) => <a style={{ color: 'black' }}>{text}</a>,
              filteredValue: [searchedText],
              onFilter: (value, record) => {
                return (
                  String(record.ProprietorName)
                    ?.toLowerCase()
                    ?.includes(value?.toLowerCase()) ||
                  String(record.Mobile)
                    ?.toLowerCase()
                    ?.includes(value?.toLowerCase()) ||
                  String(record.AccountNo)
                    ?.toLowerCase()
                    ?.includes(value?.toLowerCase()) ||
                  String(record.CompanyName)
                    ?.toLowerCase()
                    ?.includes(value?.toLowerCase())
                );
              },
              sorter: (a, b) => a?.Name?.localeCompare(b?.Name),
              sortOrder:
                sortedInfo.columnKey === 'Name' ? sortedInfo.order : null,
              ellipsis: true,
            },
            {
              title: 'Account No',
              dataIndex: 'AccountNo',
              key: 'AccountNo',
              width: '100px',
              align: 'right',
              render: (text) => <a style={{ color: 'black' }}>{text}</a>,
              ellipsis: true,
            },
            {
              title: 'IFSC Code',
              dataIndex: 'IFSCCode',
              key: 'IFSCCode',
              width: '100px',
              align: 'right',
              render: (text) => <a style={{ color: 'black' }}>{text}</a>,
              ellipsis: true,
            },
            {
              title: 'Bank Name',
              dataIndex: 'BankName',
              key: 'BankName',
              width: '100px',
              align: 'right',
              render: (text) => <a style={{ color: 'black' }}>{text}</a>,
              ellipsis: true,
            },
            {
              title: 'Branch Name',
              dataIndex: 'BranchName',
              key: 'BranchName',
              width: '100px',
              align: 'right',
              render: (text) => <a style={{ color: 'black' }}>{text}</a>,
              ellipsis: true,
            },

            {
              title: 'Action',
              key: 'Action',
              dataIndex: 'Action',
              width: '100px',
              render: (_, record, index) =>
                tabledata.length >= 1 ? (
                  <Space size="middle">
                    {record.ActiveStatus === 'A' ? (
                      <a>
                        <EditFilled
                          style={{ color: '#1292EE' }}
                          onClick={() =>
                            UserType === 'Super Admin' ||
                            (UserType === 'Super Admin User' &&
                              SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                            (UserType === 'Employee' &&
                              empData?.UpdateAccess === 'Y') ||
                            UserType === 'Admin'
                              ? OpenpaymentModal(record)
                              : null
                          }
                        />
                      </a>
                    ) : (
                      ''
                    )}
                    {
                      <a>
                        {record.ActiveStatus === 'A' ? (
                          <DeleteFilled
                            style={{
                              color: '#FF4D4F',
                            }}
                            onClick={() => statusFormatterPayment(record)}
                          />
                        ) : (
                          <ReloadOutlined
                            style={{
                              color: '#52C41A',
                            }}
                            onClick={() => statusFormatterPayment(record)}
                          />
                        )}
                      </a>
                    }
                  </Space>
                ) : null,
            },
          ]
        : detailType == 'payment'
          ? [
              {
                title: 'Sl.No',
                key: 'sno',
                align: 'center',
                width: '100px',
                render: (_, record, index) => (
                  <a style={{ color: 'black' }}>
                    {(page - 1) * 10 + index + 1}
                    {record?.NewPaymentList.length > 0 &&
                      UserType == 'Super Admin' && (
                        <IoMdNotifications
                          style={{
                            width: '20px',
                            height: '30px',
                            color: '#ff4d4f',
                          }}
                        />
                      )}
                  </a>
                ),
              },
              {
                title: 'Proprietor Name',
                dataIndex: 'ProprietorName',
                key: 'Name',
                width: '100px',
                render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                filteredValue: [searchedText],
                onFilter: (value, record) => {
                  return (
                    String(record.ProprietorName)
                      ?.toLowerCase()
                      ?.includes(value?.toLowerCase()) ||
                    String(record.Mobile)
                      ?.toLowerCase()
                      ?.includes(value?.toLowerCase()) ||
                    String(record.AccountNo)
                      ?.toLowerCase()
                      ?.includes(value?.toLowerCase()) ||
                    String(record.CompanyName)
                      ?.toLowerCase()
                      ?.includes(value?.toLowerCase())
                  );
                },
                sorter: (a, b) => a?.Name?.localeCompare(b?.Name),
                sortOrder:
                  sortedInfo.columnKey === 'Name' ? sortedInfo.order : null,
                ellipsis: true,
              },
              {
                title: 'Mobile No',
                dataIndex: 'Mobile',
                key: 'Mobile',
                width: '100px',
                align: 'right',
                render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                ellipsis: true,
              },
              {
                title: 'Account No',
                dataIndex: 'AccountNo',
                key: 'AccountNo',
                width: '100px',
                align: 'right',
                render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                ellipsis: true,
              },

              {
                title: 'Company Name',
                dataIndex: 'CompanyName',
                key: 'CompanyName',
                width: '100px',
                render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                ellipsis: true,
              },
              {
                title: 'Action',
                key: 'Action',
                dataIndex: 'Action',
                width: '100px',
                render: (_, record, index) =>
                  tabledata.length >= 1 ? (
                    <Space size="middle">
                      {record.ActiveStatus === 'A' ? (
                        <a>
                          <EditFilled
                            style={{ color: '#1292EE' }}
                            onClick={() =>
                              UserType === 'Super Admin' ||
                              (UserType === 'Super Admin User' &&
                                SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                              (UserType === 'Employee' &&
                                empData?.UpdateAccess === 'Y') ||
                              UserType === 'Admin'
                                ? OpenpaymentModal(record)
                                : null
                            }
                          />
                        </a>
                      ) : (
                        ''
                      )}
                      {UserType == 'Super Admin' && (
                        <a>
                          {record.ActiveStatus === 'A' ? (
                            <DeleteFilled
                              style={{
                                color: '#FF4D4F',
                              }}
                              onClick={() => statusFormatterPayment(record)}
                            />
                          ) : (
                            <ReloadOutlined
                              style={{
                                color: '#52C41A',
                              }}
                              onClick={() => statusFormatterPayment(record)}
                            />
                          )}
                        </a>
                      )}
                    </Space>
                  ) : null,
              },
            ]
          : detailType == 'business'
            ? [
                {
                  title: 'Sl.No',
                  key: 'sno',
                  align: 'center',
                  width: '100px',
                  render: (_, record, index) => (
                    <a style={{ color: 'black' }}>
                      {(page - 1) * 10 + index + 1}
                    </a>
                  ),
                },
                {
                  title: 'Merchant Name',
                  dataIndex: 'MerchantNameIdName',
                  key: 'MerchantNameIdName',
                  width: '150px',
                  render: (text) => (
                    <a style={{ color: 'black' }}>{text || '-'}</a>
                  ),
                  ellipsis: true,
                },
                {
                  title: 'Merchant ID',
                  dataIndex: 'MerchantId',
                  key: 'MerchantId',
                  width: '150px',
                  render: (text) => (
                    <a style={{ color: 'black' }}>{text || '-'}</a>
                  ),
                  ellipsis: true,
                },
                {
                  title: 'Merchant Mobile',
                  dataIndex: 'MerchantMobile',
                  key: 'MerchantMobile',
                  width: '150px',
                  render: (text) => (
                    <a style={{ color: 'black' }}>{text || '-'}</a>
                  ),
                  ellipsis: true,
                },

                {
                  title: 'Merchant Number',
                  dataIndex: 'MerchantNumber',
                  key: 'MerchantNumber',
                  width: '150px',
                  render: (text) => (
                    <a style={{ color: 'black' }}>{text || '-'}</a>
                  ),
                  ellipsis: true,
                },
                {
                  title: 'Merchant UPI ID',
                  dataIndex: 'MerchantUPIId',
                  key: 'MerchantUPIId',
                  width: '180px',
                  render: (text) => (
                    <a style={{ color: 'black' }}>{text || '-'}</a>
                  ),
                  ellipsis: true,
                },
                {
                  title: 'Action',
                  key: 'Action',
                  dataIndex: 'Action',
                  width: '120px',
                  render: (_, record, index) => (
                    <Space size="middle">
                      {record.ActiveStatus === 'A' ? (
                        <a>
                          <EditFilled
                            style={{ color: '#1292EE' }}
                            onClick={() => OpenpaymentBisiness(record)}
                          />
                        </a>
                      ) : (
                        ''
                      )}

                      <a>
                        {record.ActiveStatus === 'A' ? (
                          <DeleteFilled
                            style={{
                              color: '#FF4D4F',
                            }}
                            onClick={() => statusFormatterBisiness(record)}
                          />
                        ) : (
                          <ReloadOutlined
                            style={{
                              color: '#52C41A',
                            }}
                            onClick={() => statusFormatterBisiness(record)}
                          />
                        )}
                      </a>
                    </Space>
                  ),
                },
              ]
            : [
                {
                  title: 'Sl.No',
                  key: 'sno',
                  align: 'center',
                  width: '100px',
                  render: (_, record, index) => (
                    <a style={{ color: 'black' }}>
                      {(page - 1) * 10 + index + 1}
                      {record?.NewPaymentList.length > 0 &&
                        UserType == 'Super Admin' && (
                          <IoMdNotifications
                            style={{
                              width: '20px',
                              height: '30px',
                              color: '#ff4d4f',
                            }}
                          />
                        )}
                    </a>
                  ),
                },
                {
                  title: 'Proprietor Name',
                  dataIndex: 'ProprietorName',
                  key: 'Name',
                  width: '100px',
                  render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                  filteredValue: [searchedText],
                  onFilter: (value, record) => {
                    return (
                      String(record.ProprietorName)
                        ?.toLowerCase()
                        ?.includes(value?.toLowerCase()) ||
                      String(record.Mobile)
                        ?.toLowerCase()
                        ?.includes(value?.toLowerCase()) ||
                      String(record.AccountNo)
                        ?.toLowerCase()
                        ?.includes(value?.toLowerCase())
                    );
                  },
                  sorter: (a, b) => a?.Name?.localeCompare(b?.Name),
                  sortOrder:
                    sortedInfo.columnKey === 'Name' ? sortedInfo.order : null,
                  ellipsis: true,
                },
                {
                  title: 'Mobile No',
                  dataIndex: 'Mobile',
                  key: 'Mobile',
                  width: '100px',
                  align: 'right',
                  render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                  ellipsis: true,
                },
                {
                  title: 'Account No',
                  dataIndex: 'AccountNo',
                  key: 'AccountNo',
                  width: '100px',
                  align: 'right',
                  render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                  ellipsis: true,
                },
                {
                  title: 'Company Name',
                  dataIndex: 'CompanyName',
                  key: 'CompanyName',
                  width: '100px',
                  render: (text) => <a style={{ color: 'black' }}>{text}</a>,
                  ellipsis: true,
                },
                {
                  title: 'Action',
                  key: 'Action',
                  dataIndex: 'Action',
                  width: '100px',
                  render: (_, record, index) =>
                    tabledata.length >= 1 ? (
                      <Space size="middle">
                        {record.ActiveStatus === 'A' ? (
                          <a>
                            <EditFilled
                              style={{ color: '#1292EE' }}
                              onClick={() =>
                                UserType === 'Super Admin' ||
                                (UserType === 'Super Admin User' &&
                                  SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                                (UserType === 'Employee' &&
                                  empData?.UpdateAccess === 'Y') ||
                                UserType === 'Admin'
                                  ? OpenpaymentModal(record)
                                  : null
                              }
                            />
                          </a>
                        ) : (
                          ''
                        )}
                        {UserType == 'Super Admin' && (
                          <a>
                            {record.ActiveStatus === 'A' ? (
                              <DeleteFilled
                                style={{
                                  color: '#FF4D4F',
                                }}
                                onClick={() => statusFormatterDevice(record)}
                              />
                            ) : (
                              <ReloadOutlined
                                style={{
                                  color: '#52C41A',
                                }}
                                onClick={() => statusFormatterDevice(record)}
                              />
                            )}
                          </a>
                        )}
                      </Space>
                    ) : null,
                },
              ];

  useEffect(() => {
    FetchInitialPaymentData();
    onChangeDetailType('upi');
    // if (UserType === "Employee") {
    //   fetchApi()
    // }
  }, []);
  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]);
  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 Details'
    );
    setEmpData(datas?.[0]);
  };

  const FetchInitialPaymentData = async () => {
    // let data = { 'CompId': CompId, 'BranchId': BranchId, 'AppId': AppId, "detailType": e == "upi" ? "U" : e == "payment" ? "P" : e == "device" ? "D" : "" }
    let PaymrntGateway = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      detailType: 'P',
    };
    let PaymrntDevice = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      detailType: 'D',
    };
    let responseGateway = await dispatch(gettableupi(PaymrntGateway)).unwrap();
    let responseDevice = await dispatch(gettableupi(PaymrntDevice)).unwrap();
    if (responseGateway?.data?.statusCode == 1) {
      console.log(responseGateway?.data?.data, 'responselkj08');
      setgateWayAccess(responseGateway?.data?.data);
    }
    if (responseGateway?.data?.statusCode == 1) {
      console.log(responseDevice?.data?.data, 'responselkj08');
      setdeviceAccess(responseDevice?.data?.data);
    }
    if (UserType !== 'Super Admin' && UserType !== 'Super Admin User') {
      let Response = await dispatch(
        FeatureAddon({ AppId: AppId, UserId: UserId })
      ).unwrap();

      const features =
        Response?.data?.data?.[0]?.FeatAddonHdr?.[0]?.FeatureDtls;

      const availableOptions = [
        { value: 'upi', label: 'UPI Details' },
        { value: 'bank', label: 'Bank Details' },
        { value: 'payment', label: 'Payment Gateway' },
        { value: 'business', label: 'Business UPI' },
        { value: 'device', label: 'Payment Device' },
      ];

      const matchedOptions = availableOptions.filter((option) => {
        if (
          option.label === 'UPI Details' ||
          option.label === 'Bank Details' ||
          option.label === 'Business UPI'
        ) {
          return true; // Always include "UPI Details" and "Bank Details"
        }
        return features?.some(
          (feature) => feature.FeatureAddonName === option.label
        );
      });
      setPaymentDatas(matchedOptions);
      if (matchedOptions?.length == 1) {
        onChangeDetailType(matchedOptions?.[0]?.value);
      }
    }
  };
  useEffect(() => {
    if (timeLeft === 0) {
      setDisable(false);

      setTimeLeft(null);
    }

    // exit early when we reach 0
    if (!timeLeft) return;

    // save intervalId to clear the interval when the
    // component re-renders
    const intervalId = setInterval(() => {
      setTimeLeft(timeLeft - 1);
    }, 1000);

    // clear interval on re-render to avoid memory leaks
    return () => clearInterval(intervalId);
  }, [timeLeft]);
  useEffect(() => {
    SetOtpData();
  }, [otp1, otp2, otp3, otp4]);

  const SetOtpData = async () => {
    let otp = otp1 + '' + otp2 + '' + otp3 + '' + otp4;
    if (otp.length === 4) {
      let data = {
        MobileNo: SelectedRow?.AdminMobileNo
          ? SelectedRow?.AdminMobileNo
          : null,
        OTP: otp,
      };
      let response = await dispatch(getupiotp(data)).unwrap();

      if (response?.data?.statusCode === 1) {
        navigateTo(
          `${subDirectory}setting/payment-details/update`,
          { state: { editstate: SelectedRow, DetailType: detailType } },
          { key: SelectedRowIndex },
          { DetailType: detailType }
        );
      } else {
        setMessageType('error');
        setMessageData('Please enter correct OTP');
      }
    }
  };

  const OpenOtpModal = async (row, rowIndex) => {
    setOtpModal(true);
    setSelectedRow(row);
    setSelectedRowIndex(rowIndex);
    setotp1('');
    setotp2('');
    setotp3('');
    setotp4('');
    SendOtp(row, rowIndex);
  };

  const OpenpaymentModal = async (row, rowIndex) => {
    navigateTo(
      `${subDirectory}setting/payment-details/update`,
      { state: { editstate: row, DetailType: detailType } },
      { key: SelectedRowIndex },
      { DetailType: detailType }
    );
  };

  const OpenpaymentBisiness = async (row, rowIndex) => {
    navigateTo(
      `${subDirectory}setting/payment-details/update`,
      { state: { editstate: row, DetailType: 'upi' } },
      { key: SelectedRowIndex },
      { DetailType: 'upi' }
    );
  };

  const SendOtp = async (row, rowIndex) => {
    let PostData = {
      MobileNo: row?.AdminMobileNo ? row?.AdminMobileNo : null,
      CreatedBy: UserId,
    };
    let response = await dispatch(sendupiotp(PostData)).unwrap();
    if (response?.data?.statusCode == 1) {
      setMessageType('success');
      setMessageData('Otp Send Successfully');
      setStatus(true);
      setTimeLeft(30);
    }
  };
  const CloseOtpModal = () => {
    setOtpModal(false);
  };

  const statusFormatter = async (row) => {
    let deleteData = {
      UPIDetailId: row.UPIDetailId,
      Mode: row.Mode,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: getSession('UserId'),
      CompId: getSession('CompId'),
      BranchId: getSession('BranchId'),
      AppId: getSession('AppId'),
    };

    let response = await dispatch(delupi(deleteData)).unwrap();
    if (response?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
      // TableDatas();
      onChangeDetailType('upi');
    }
  };

  const statusFormatterPayment = async (row) => {
    let deleteData = {
      UPIDetailId: row.UPIDetailId,
      Mode: row.Mode,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: getSession('UserId'),
      CompId: getSession('CompId'),
      BranchId: getSession('BranchId'),
      AppId: getSession('AppId'),
    };

    let response = await dispatch(delPayment(deleteData)).unwrap();

    if (response?.data?.statusCode === 1) {
      let data = {
        CompId: CompId,
        BranchId: BranchId,
        AppId: AppId,
        detailType: 'B',
      };
      let response = await dispatch(gettableupi(data)).unwrap();
      if (response?.data?.statusCode == 1) {
        if (response?.data?.statusCode == 1) {
          setTabledata(response?.data?.data);
        }
      }
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
      onChangeDetailType('payment');
      // TableDatas();
    }
  };
  const statusFormatterDevice = async (row) => {
    let deleteData = {
      UPIDetailId: row.UPIDetailId,
      // Mode: row.Mode,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: getSession('UserId'),
      CompId: getSession('CompId'),
      BranchId: getSession('BranchId'),
      AppId: getSession('AppId'),
    };

    let response = await dispatch(delPayment(deleteData)).unwrap();

    if (response?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
      onChangeDetailType('device');
      // TableDatas();
    }
  };

  const statusFormatterBisiness = async (row) => {
    let deleteData = {
      UPIDetailId: row.UPIDetailId,
      // Mode: row.Mode,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: getSession('UserId'),
      CompId: getSession('CompId'),
      BranchId: getSession('BranchId'),
      AppId: getSession('AppId'),
    };
    let response = await dispatch(delPayment(deleteData)).unwrap();

    if (response?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
      onChangeDetailType('business');
      // TableDatas();
    }
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };

  useEffect(() => {
    try {
      if (location?.state?.Notiffy) {
        setMessageType(location?.state?.Notiffy.messageType);
        setMessageData(location?.state?.Notiffy.messageData);
      }
    } catch (err) {
      console.log(err, 'err');
    }
  }, []);

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

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

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };

  const handlePageChange = (current) => {
    setpage(current);
  };

  const handelAddButton = () => {
    navigateTo(`${subDirectory}setting/payment-details/new`, {
      state: { gateWayAccess, deviceAccess },
    });
  };

  const TableDatas = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      detailType: 'U',
    };
    let response = await dispatch(gettableupi(data)).unwrap();

    // if (response?.data?.statusCode == 1) {
    //   setTabledata(response?.data?.data);

    // }
  };
  const handleOtpChange = async (value1, e) => {
    switch (value1) {
      case 'setotp1':
        await setotp1(e?.target?.value);
        break;
      case 'setotp2':
        setotp2(e?.target?.value);
        break;
      case 'setotp3':
        setotp3(e?.target?.value);
        break;
      case 'setotp4':
        setotp4(e?.target?.value);
        break;
    }
  };
  const inputfocus = (elmnt) => {
    if (elmnt.key === 'Delete' || elmnt.key === 'Backspace') {
      const next = elmnt.target.tabIndex - 2;
      if (next > -1) {
        elmnt?.target?.form?.elements[next]?.focus();
      }
    } else {
      const next = elmnt.target.tabIndex;
      if (next < 6) {
        elmnt?.target?.form?.elements[next]?.focus();
      }
    }
  };

  const onChangeDetailType = async (e) => {
    setdetailType(e);
    setTabledata([]);

    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      detailType:
        e == 'upi'
          ? 'U'
          : e == 'payment'
            ? 'P'
            : e == 'device'
              ? 'D'
              : e == 'bank'
                ? 'B'
                : e == 'business'
                  ? 'BU'
                  : '',
    };
    let response = await dispatch(gettableupi(data)).unwrap();
    if (response?.data?.statusCode == 1) {
      if (response?.data?.statusCode == 1) {
        setTabledata(response?.data?.data);
      }
    }
  };

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew" style={{ marginTop: '10px' }}>
          <div>
            <FormHeader title={'Payment Details'} />
          </div>
          <div className="searchAddDiv">
            <div
              className="formSearch"
              style={{
                width: '100%',
                flexWrap: 'wrap',
                alignItems: 'flex-start',
                gap: '1rem',
              }}
            >
              <Tooltip
                title={
                  detailType === 'bank'
                    ? 'Search by Proprietor Name or Account No'
                    : detailType === 'upi'
                      ? 'Search by Name or Mobile No'
                      : 'Search'
                }
              >
                <div>
                  <Search
                    placeholder={
                      detailType === 'bank'
                        ? 'Search by Proprietor Name or Account No'
                        : detailType === 'upi'
                          ? 'Search by Name or Mobile No'
                          : 'Search'
                    }
                    onSearch={onSearch}
                    onSearchChange={onSearchChange}
                  />
                </div>
              </Tooltip>
              <div>
                <DropDowns
                  // options={[
                  //   { value: "upi", label: "UPI Details" },
                  //   { value: "payment", label: "Payment gateway" },
                  //   { value: "device", label: "Payment device" },
                  // ]}
                  options={PaymentDatas}
                  label={<label>Payment Type</label>}
                  className="field-DropDown"
                  onChangeFunction={(e) => onChangeDetailType(e)}
                  valueData={detailType}

                  // valueData={seletedprodDropdown}
                  // isOnChange={
                  //   formRef.current?.getFieldsValue()?.Mode != undefined
                  //     ? true
                  //     : false
                  // }
                />
              </div>
              <Buttons
                buttonText={'Add New'}
                handleSubmit={() => handelAddButton()}
                disabled={addnewAccess}
                color="901D77"
                icon={<PlusOutlined />}
              >
                OPEN
              </Buttons>
            </div>
          </div>
        </div>
        <div className="reportTable">
          <Tables
            columns={columns}
            data={tabledata}
            dataSource={tabledata}
            pagination={handlePageChange}
            onChange={handleChange}
          />
        </div>
      </div>
      <DefaultModal
        title={<div className="EditQuantity-title">Enter OTP</div>}
        open={OtpModal}
        width={300}
        footer={null}
        children={
          <div>
            <Form>
              <div className="otpContainer">
                <input
                  name="otp1"
                  type="text"
                  autoComplete="off"
                  className="otpInput"
                  value={otp1}
                  onChange={(e) => handleOtpChange('setotp1', e)}
                  tabIndex="1"
                  maxLength="1"
                  onKeyUp={(e) => inputfocus(e)}
                />
                <input
                  name="otp2"
                  type="text"
                  autoComplete="none"
                  className="otpInput"
                  value={otp2}
                  onChange={(e) => handleOtpChange('setotp2', e)}
                  tabIndex="2"
                  maxLength="1"
                  onKeyUp={(e) => inputfocus(e)}
                />
                <input
                  name="otp3"
                  type="text"
                  autoComplete="none"
                  className="otpInput"
                  value={otp3}
                  onChange={(e) => handleOtpChange('setotp3', e)}
                  tabIndex="3"
                  maxLength="1"
                  onKeyUp={(e) => inputfocus(e)}
                />
                <input
                  name="otp4"
                  type="text"
                  autoComplete="none"
                  className="otpInput"
                  value={otp4}
                  onChange={(e) => handleOtpChange('setotp4', e)}
                  tabIndex="4"
                  maxLength="1"
                  onKeyUp={(e) => inputfocus(e)}
                />
              </div>
            </Form>
            <div className="timersecdiv">
              {Status && timeLeft != null ? (
                <div className="timersecsubdiv">
                  <div>
                    <ClockCircleOutlined />
                  </div>
                  <div
                    style={{
                      color: timeLeft <= 10 ? '#FF4D4F' : '#52C41A',
                    }}
                  >
                    0 : {timeLeft < 10 ? '0' + timeLeft : timeLeft}{' '}
                  </div>
                </div>
              ) : Status ? (
                <Buttons
                  buttonText="Resend OTP"
                  style={{ width: '5rem' }}
                  handleSubmit={() => SendOtp()}
                  icon={<ArrowRightOutlined />}
                ></Buttons>
              ) : (
                ''
              )}
            </div>
          </div>
        }
        handleCancel={CloseOtpModal}
      />
    </div>
  );
};

export default PaymentDetailsList;
