import { useState, useEffect, useCallback, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, useLocation } from 'react-router-dom';
import { ArrowRightOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { Space, Form } 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,
} from '../../Features/UpiDetails/UpiDetails.js';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';

const UpiDetailslist = () => {
  const navigateTo = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const ref = useRef();
  //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 [apiotp, setapiotp] = useState('1234');
  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 [timeLeft, setTimeLeft] = useState(null);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');

  const subDirectory = import.meta.env.ENV_BASE_URL;

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

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

  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '100px',
      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',
      render: (_, record, index) =>
        tabledata.length >= 1 ? (
          <Space size="middle">
            {record.ActiveStatus === 'A' ? (
              <a>
                <EditFilled
                  style={{ color: '#1292EE' }}
                  onClick={() => OpenOtpModal(record, index)}
                />
              </a>
            ) : (
              ''
            )}
            <a>
              {record.ActiveStatus === 'A' ? (
                <DeleteFilled
                  style={{
                    color: '#FF4D4F',
                  }}
                  onClick={() => statusFormatter(record)}
                />
              ) : (
                <ReloadOutlined
                  style={{
                    color: '#52C41A',
                  }}
                  onClick={() => statusFormatter(record)}
                />
              )}
            </a>
          </Space>
        ) : null,
    },
  ];
  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/upi-details/update`,
          { state: { editstate: SelectedRow } },
          { key: SelectedRowIndex }
        );
      } else {
        setMessageType('error');
        setMessageData('InCorrect Otp');
      }
      // if (SelectedRow.ActiveStatus !== "D") {
      //   if(apiotp === otp){
      //     setOtpModal(false)
      //   navigateTo(
      //     `${subDirectory}setting/upi-details/update`,
      //     { state: { editstate: SelectedRow } },
      //     { key: SelectedRowIndex }
      //   );
      //   }
      //   else{
      //     setMessageType("error")
      //     setMessageData("Invalid Otp")
      //   }
      // }
    }
  };
  const actionsFormatter = async (row, rowIndex) => {
    if (row.ActiveStatus !== 'D') {
      navigateTo(
        `${subDirectory}setting/upi-details/update`,
        { state: { editstate: row } },
        { key: rowIndex }
      );
    }
  };
  const OpenOtpModal = async (row, rowIndex) => {
    setOtpModal(true);
    setSelectedRow(row);
    setSelectedRowIndex(rowIndex);

    SendOtp(row, rowIndex);
  };
  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();
    }
  };

  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/upi-details/new`);
  };

  const TableDatas = async () => {
    let data = { CompId: CompId, BranchId: BranchId, AppId: AppId };
    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();
      }
    }
  };

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew">
          <div>
            <FormHeader title={'Upi Details'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>
            <Buttons
              buttonText={'Add New'}
              handleSubmit={() => handelAddButton()}
              color="901D77"
              icon={<PlusOutlined />}
            >
              OPEN
            </Buttons>
          </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
                  // type="submit"
                  buttonText="Resend OTP"
                  style={{ width: '5rem' }}
                  handleSubmit={() => SendOtp()}
                  icon={<ArrowRightOutlined />}
                ></Buttons>
              ) : (
                ''
              )}
            </div>
          </div>
        }
        handleCancel={CloseOtpModal}
      />
    </div>
  );
};

export default UpiDetailslist;
