import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { customerDetails, userchatlist, depositRequest } from "../../redux/_reducers/_reducers";
import moment from "moment";
import { toast } from "react-toastify";
import Loader from "../../component/Loader/Loader";

function Withdrawal({ WithdrawClose }) {
  const [Isdeposit, Setdeposit] = useState(0);
  const [defaultAllData, setDefaultAllData] = useState()
  const [accountNumber, setAccountNumber] = useState("");
  const [ifscCode, setIfscCode] = useState("");
  const [accountHolderName, setAccountHolderName] = useState("");
  const [bankName, setBankName] = useState("");
  const [amount, setAmount] = useState("");
  const [phoneNo, setPhoneNo] = useState("");
  const [accountName, setAccountName] = useState("");
  const [amountUpi, setAmountUpi] = useState("");

  const [accountNumberError, setAccountNumberError] = useState('');
  const [ifscCodeError, setIfscCodeError] = useState('');
  const [accountHolderNameError, setAccountHolderNameError] = useState('');
  const [bankNameError, setBankNameError] = useState('');
  const [amountError, setAmountError] = useState('');

  const [phoneNoError, setPhoneNoError] = useState('');
  const [accountNameError, setAccountNameError] = useState('');
  const [amountUpiError, setAmountUpiError] = useState('');


  const dispatch = useDispatch();

  const handleAccountNumberChange = (e) => {
    setAccountNumber(e.target.value);
  };
  const handleIfscCodeChange = (e) => {
    setIfscCode(e.target.value);
  };
  const handleAccountHolderNameChange = (e) => {
    setAccountHolderName(e.target.value);
  };
  const handleBankNameChange = (e) => {
    setBankName(e.target.value);
  };
  const handleAmountChange = (e) => {
    const numericValue = Number(e.target.value);
    if (!isNaN(numericValue)) {
      setAmount(numericValue);
    } else {
      setAmount(0);
    }
  };
  const handlePhoneNoChange = (e) => {
    setPhoneNo(e.target.value);
  };

  const handleAccountNameChange = (e) => {
    setAccountName(e.target.value);
  };

  const handleAmountChangeUpi = (e) => {
    setAmountUpi(e.target.value);
  };

  const DepositClick = (index) => {
    Setdeposit(index);
    setPhoneNoError('');
    setAccountNameError('');
    setAmountUpiError('');
    setAccountNumberError('');
    setIfscCodeError('');
    setAccountHolderNameError('');
    setBankNameError('');
    setAmountError('');
  };

  const { defaultSettingData, customerDetailsData, userchatlistData, loading } = useSelector((state) => state.authentication);


  const customerData = () => {
    const payload = { "type": "D" };
    dispatch(customerDetails(payload));
  }

  const userChatListData = () => {
    const data = {
      "limit": 15,
      "page": 1,
      "status": "AL",
      "type": "W"
    };
    dispatch(userchatlist(data));
  }

  useEffect(() => {
    userChatListData();
    customerData();
  }, [dispatch]);

  useEffect(() => {
    if (defaultSettingData) {
      setDefaultAllData(defaultSettingData);
    }
  }, [defaultSettingData]);

  const handleSubmitUpi = async (element) => {
    let isValid = true;
    setPhoneNoError('');
    setAccountNameError('');
    setAmountUpiError('');

    if (!phoneNo || phoneNo.length < 10) {
      setPhoneNoError('Please enter a valid Phone No./UPI with at least 10 digits.');
      isValid = false;
    }

    if (!accountName) {
      setAccountNameError('Please enter the account name.');
      isValid = false;
    }

    if (!amountUpi) {
      setAmountUpiError('Please enter a valid amount.');
      isValid = false;
    } else if (Number(amountUpi) < 100) {
      setAmountUpiError('Amount must be at least 100.');
      isValid = false;
    }

    if (!isValid) {
      console.error('Form validation failed');
      return;
    }

    const data = {
      "amount": amountUpi,
      "account_number": phoneNo,
      "ifsc": '',
      "account_name": accountName,
      'type': "W",
      'user_id': 0,
      'transaction_id': '',
      'sender': '',
      'reciver': '',
      'dwtype': 'normal',
      'method': "UPI",
      "attachment": '',
    };

    try {
      await dispatch(depositRequest(data));
      userChatListData();

    } catch (error) {
      console.error("API call failed", error);
      toast.error("Submission failed. Please try again.");
    }

    setLoading(false)
    setPhoneNoError('');
    setAccountNameError('');
    setAmountUpiError('');

  };



  const handleSubmit = async (element) => {
    let isValid = true;

    setAccountNumberError('');
    setIfscCodeError('');
    setAccountHolderNameError('');
    setBankNameError('');
    setAmountError('');

    if (!accountNumber) {
      setAccountNumberError('Please enter an account number.');
      isValid = false;
    }

    if (!ifscCode) {
      setIfscCodeError('Please enter an IFSC code.');
      isValid = false;
    }

    if (!accountHolderName) {
      setAccountHolderNameError('Please enter the account holder name.');
      isValid = false;
    }

    if (!bankName) {
      setBankNameError('Please enter the bank name.');
      isValid = false;
    }
    if (!amount) {
      setAmountError('Please enter a valid amount.');
      isValid = false;
    } else if (Number(amount) < 100) {
      setAmountError('Amount must be at least 100.');
      isValid = false;
    }


    if (!isValid) {
      console.error('Form validation failed');
      return;
    }


    const data = {
      "amount": Number(amount),
      "account_number": accountNumber,
      "ifsc": ifscCode,
      "account_name": accountHolderName,
      'type': "W",
      'user_id': 0,
      'transaction_id': '',
      'sender': '',
      'reciver': '',
      'dwtype': 'normal',
      'method': element?.account_type,
      "attachment": bankName
    };

    try {
      await dispatch(depositRequest(data));
      userChatListData();

    } catch (error) {
      console.error("API call failed", error);
      toast.error("Submission failed. Please try again.");
    }


    setAccountNumberError('');
    setIfscCodeError('');
    setAccountHolderNameError('');
    setBankNameError('');
    setAmountError('');
  };

  return (
    <>
      {loading && <Loader />}
      <section className="px-2">
        <div className="w-full">
          {/* <div className="lg:w-9/12 w-full  mt-3"> */}
          <div className="row mx-0">
            <div className="col-12 px-0 scoretabcontent-work shadow-none d-flex flex-column flex-sm-row align-items-start pb-2">
              <div className="tabs w-100 mt-2">
                <div className="shadow bg-white w-full">
                  {/* <div className="border-l-4 border-l-[var(--primary)] text-left px-2 border-b border-b-black">Payment Method</div> */}
                  <div className="flex flex-wrap justify-center py-5 gap-2 rounded w-full mx-auto">
                    {customerDetailsData && customerDetailsData?.length > 0 ? customerDetailsData?.map((element, index) => (
                      <div
                        key={index}
                        onClick={() => DepositClick(index)}
                        className={`cursor-pointer px-5 py-2 rounded-lg text-[12px] text-center ${Isdeposit === index ? 'bg-[var(--light-header)] text-white' : 'bg-white border'}`}>
                        {element.account_type === "IMPS" ? (
                          <>
                            <h4 className="uppercase font-[600]">Account</h4>
                            <img src="/assets/bank-account.png" alt="Bank Account" className="mx-auto w-[45px] h-[45px]" />
                          </>
                        ) : (
                          <>
                            <h4 className="uppercase font-[700]">UPI</h4>
                            <img src="/assets/upi-icon.png" alt="UPI Icon" className="mx-auto w-[45px] h-[45px]" />
                          </>
                        )}
                      </div>
                    )) : null}
                  </div>
                </div>
                {customerDetailsData && customerDetailsData.length > 0 ? customerDetailsData.map((element, index) => (
                  <div className="tab-content mt-2">
                    {Isdeposit === index &&
                      <div>
                        {element.account_type === "IMPS" ?
                          <>
                            <div className='depositbank bg-white p-5 shadow-md rounded'>
                              <h3 className="text-lg font-semibold mb-4 text-center">BANK ACCOUNT</h3>
                              <div className="max-w-4xl mx-auto">
                                <div className="bg-white lg:px-4 text-[13px] text-black font-[500]">
                                  {/* Account Number */}
                                  <div className="mb-4">
                                    <label className="block text-left">
                                      Account Number <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="Account Number"
                                      className="w-full px-3 py-2 bg-white border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={accountNumber}
                                      onChange={handleAccountNumberChange}
                                    />
                                    {accountNumberError && <span className="text-red-500 text-sm">{accountNumberError}</span>}
                                  </div>

                                  {/* IFSC Code */}
                                  <div className="mb-4">
                                    <label className="block text-left">
                                      IFSC Code <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="IFSC Code"
                                      className="w-full px-3 py-2 border bg-white border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={ifscCode}
                                      onChange={handleIfscCodeChange}
                                    />
                                    {ifscCodeError && <span className="text-red-500 text-sm">{ifscCodeError}</span>}
                                  </div>

                                  {/* Account Holder Name */}
                                  <div className="mb-4">
                                    <label className="block text-left">
                                      Account Holder Name <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="Account Holder Name"
                                      className="w-full px-3 py-2 border bg-white border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={accountHolderName}
                                      onChange={handleAccountHolderNameChange}
                                    />
                                    {accountHolderNameError && <span className="text-red-500 text-sm">{accountHolderNameError}</span>}
                                  </div>

                                  {/* Bank Name */}
                                  <div className="mb-4">
                                    <label className="block text-left">
                                      Bank Name <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="Bank Name"
                                      className="w-full px-3 py-2 border border-gray-300 bg-white rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={bankName}
                                      onChange={handleBankNameChange}
                                    />
                                    {bankNameError && <span className="text-red-500 text-sm">{bankNameError}</span>}
                                  </div>

                                  {/* Amount */}
                                  <div className="mb-4">
                                    <label className="block text-left">
                                      Amount <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="Amount"
                                      className="w-full px-3 py-2 border bg-white border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={amount}
                                      onChange={handleAmountChange}
                                    />
                                    {amountError && <span className="text-red-500 text-sm">{amountError}</span>}
                                  </div>

                                  {/* Submit Button */}
                                  <div className="text-center">
                                    <button
                                      onClick={() => handleSubmit(element)}
                                      className="hover:bg-green-600 bg-[#64cc2f] text-white font-semibold px-6 py-2.5 w-full rounded transition-all"
                                    >
                                      SUBMIT
                                    </button>
                                  </div>
                                </div>
                              </div>
                            </div>
                            <div>
                              <ul className="bg-white p-5 text-[11px] mt-3 rounded text-left">
                                <li className="list">1.  Deposit money only in the below available accounts to get the fastest credits and avoid possible delays. </li>
                                <li className="list">2.Deposits made 45 minutes after the account removal from the site are valid & will be added to their wallets.</li>
                                <li className="list">3. Site is not responsible for money deposited to Old, Inactive or Closed accounts.</li>
                                <li className="list">4. After deposit, add your UTR and amount to receive balance.</li>
                                <li className="list">5 .NEFT receiving time varies from 40 minutes to 2 hours.</li>
                                <li className="list">6. In case of account modification: payment valid for 1 hour after changing account details in deposit page.</li>
                              </ul>
                            </div>
                          </> : <>
                            <div className="depositbank bg-white p-5 shadow-md rounded">
                              <h3 className="text-lg font-semibold mb-4 text-center">UPI</h3>
                              <div className="max-w-4xl mx-auto">
                                <div className="bg-white lg:px-4 text-[13px] text-black font-[500]">
                                  {/* Phone No./UPI */}
                                  <div className="mb-4">
                                    <label className="block text-left">
                                      Phone No./UPI <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="Phone No./UPI"
                                      className="w-full bg-white px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={phoneNo}
                                      onChange={handlePhoneNoChange}
                                    />
                                    {phoneNoError && <span className="text-red-500 text-sm">{phoneNoError}</span>}
                                  </div>

                                  {/* Account Name */}
                                  <div className="mb-4">
                                    <label className="block text-left">
                                      Account Name <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="Account Name"
                                      className="w-full px-3 py-2 border bg-white border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={accountName}
                                      onChange={handleAccountNameChange}
                                    />
                                    {accountNameError && <span className="text-red-500 text-sm">{accountNameError}</span>}
                                  </div>

                                  {/* Amount */}
                                  <div className="mb-4">
                                    <label className="block  text-left">
                                      Amount <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                      type="text"
                                      placeholder="Amount"
                                      className="w-full px-3 py-2 bg-white border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      value={amountUpi}
                                      onChange={handleAmountChangeUpi}
                                    />
                                    {amountUpiError && <span className="text-red-500 text-sm">{amountUpiError}</span>}
                                  </div>

                                  {/* Submit Button */}
                                  <div className="text-center">
                                    <button
                                      onClick={() => handleSubmitUpi(element)}
                                      className="hover:bg-green-600 bg-[#64cc2f] text-white font-semibold px-6 py-2.5 rounded w-full transition-all"
                                    >
                                      SUBMIT
                                    </button>
                                  </div>
                                </div>
                              </div>
                            </div>
                            <div>
                              <ul className="bg-white p-5 text-[11px] mt-3 rounded text-left">
                                <li className="list">1.  Deposit money only in the below available accounts to get the fastest credits and avoid possible delays. </li>
                                <li className="list">2.Deposits made 45 minutes after the account removal from the site are valid & will be added to their wallets.</li>
                                <li className="list">3. Site is not responsible for money deposited to Old, Inactive or Closed accounts.</li>
                                <li className="list">4. After deposit, add your UTR and amount to receive balance.</li>
                                <li className="list">5 .NEFT receiving time varies from 40 minutes to 2 hours.</li>
                                <li className="list">6. In case of account modification: payment valid for 1 hour after changing account details in deposit page.</li>
                              </ul>
                            </div>
                          </>}
                      </div>}
                    {/* {Isdeposit === 1 &&
                                            <div>
                                                <>
                                                    <div className="">
                                                        <div className='depositbank bg-white p-4 rounded-2'>
                                                            <h3>UPI</h3>
                                                            <div className='row'>
                                                                <div className="col-sm-6 col-12">
                                                                    <div className='account-detail-deposit'>
                                                                        <div className='depositbank-detail'>
                                                                            <ul>
                                                                                <li className='d-flex flex-wrap justify-content-between'>
                                                                                    <div className='d-flex flex-wrap bankname'>
                                                                                        <div className="bankName">Name :</div>
                                                                                        <span className="bankSubName">Dataniya Rajesh</span>
                                                                                    </div>
                                                                                    <div className='bankcopy text-end'><IoCopyOutline /></div>
                                                                                </li>
                                                                                <li className='d-flex flex-wrap justify-content-between'>
                                                                                    <div className='d-flex flex-wrap bankname'>
                                                                                        <div className="bankName">UPI ID :</div>
                                                                                        <span className="bankSubName">dataniyarajesh@axl</span>
                                                                                    </div>
                                                                                    <div className='bankcopy text-end'><IoCopyOutline /></div>
                                                                                </li>
                                                                                <li className='d-flex flex-wrap justify-content-between'>
                                                                                    <div className='d-flex flex-wrap bankname'>
                                                                                        <div className="bankName">Min Amount :</div>
                                                                                        <span className="bankSubName">100</span>
                                                                                    </div>
                                                                                    <div className='bankcopy text-end'><IoCopyOutline /></div>
                                                                                </li>
                                                                                <li className='d-flex flex-wrap justify-content-between'>
                                                                                    <div className='d-flex flex-wrap bankname'>
                                                                                        <div className="bankName">Max Amount :</div>
                                                                                        <span className="bankSubName">1000000</span>
                                                                                    </div>
                                                                                    <div className='bankcopy text-end'><IoCopyOutline /></div>
                                                                                </li>
                                                                                <li>
                                                                                    <img className="qrimage" src={qr} alt="" />
                                                                                </li>
                                                                            </ul>
                                                                        </div>
                                                                    </div>
                                                                    <div className="wpBtnWrapper">
                                                                        <button className="wpBtn w-full d-flex flex-column align-items-center">FOR PAYMENT RELATED ISSUES <span className="wpAnimation"><RiWhatsappLine /></span></button>
                                                                    </div>
                                                                </div>
                                                                <div className="col-sm-6 col-12 mt-4 sm-mt-0">
                                                                    <div>
                                                                        <div className='depositform-data'>
                                                                            <div className='input'>
                                                                                <label>Unique Transaction Reference <span>*</span></label>
                                                                                <input type='text' placeholder='6 to 12 Digits UTR Number' className='d-block depositInp' />
                                                                                <span>Enter valid UTR number.</span>
                                                                            </div>

                                                                            <div className="my-3 upload-container">
                                                                                <label htmlFor="paymentProof" className="form-label">
                                                                                    Upload Your Payment Proof{" "}
                                                                                    <span className="required-text">[Required]</span>
                                                                                </label>
                                                                                <input type="hidden" name="hiddenInput" />
                                                                                <input
                                                                                    type="file"
                                                                                    className="form-control custom-file-input"
                                                                                    id="paymentProof"
                                                                                    aria-describedby="paymentProofHelp"
                                                                                />
                                                                                <div></div>
                                                                                <div>
                                                                                    <p></p>
                                                                                </div>
                                                                            </div>

                                                                            <div className='input'>
                                                                                <label>Amount  <span>*</span></label>
                                                                                <input type='number' placeholder='6 to 12 Digits UTR Number' className='d-block depositInp' />
                                                                                <span>Enter valid UTR number.</span>
                                                                            </div>
                                                                            <div><button className="submitBtn">SUBMIT</button></div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </>
                                            </div>
                                        } */}
                  </div>)) : null}
              </div>
            </div>
          </div>
          {/* </div> */}
          {/* <div className="lg:w-1/4 w-full mt-3 lg:pr-0 bg-white"> */}
          <div className="w-full">
            <div className="bg-white shadow-md overflow-hidden">
              <div className="overflow-y-auto h-full">
                <table className="w-full border border-[#96c6ef]">
                  <thead>
                    <tr className="bg-[#96c6ef] text-black text-center text-nowrap">
                      <th className="p-2">Account No.</th>
                      <th>Amount</th>
                      <th>Status</th>
                      <th>Date</th>
                      <th>Reason</th>
                    </tr>
                  </thead>
                  <tbody>
                    {userchatlistData && userchatlistData?.length > 0 ? userchatlistData?.map((element, index) => (
                      <tr key={index} className="bg-gray-100 text-center">
                        <td className="px-2 py-2">{element.UTR}</td>
                        <td className="px-2 py-2">{element.amount}</td>
                        <td className="px-2 py-2">
                          <div className={`m-2 px-2 py-1 border-2 rounded text-black ${element.status === "D" ? "border-red-500" :
                            element.status === "S" ? "border-green-500" :
                              element.status === "A" ? "border-blue-500" :
                                "border-red-500"
                            }`}
                          >
                            {element.status === "D" ? "Decline" :
                              element.status === "S" ? "Success" :
                                element.status === "A" ? "Approve" : "Pending"}
                          </div>
                        </td>
                        <td className="px-2 py-2">{moment.unix(element.created_at).format("DD-MM-YYYY HH:MM:SS A")}</td>
                        <td className="px-2 py-2">{element.reason ? element.reason : "-"}</td>
                      </tr>
                    )) : null}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          {/* </div> */}
        </div>
      </section>
    </>
  )
}

export default Withdrawal;