import React, { useState } from "react";
import { Form, Modal } from "react-bootstrap";
import Gray_Btn from "../../common_btn/gray_btn/Gray_Btn";
import Orange_Btn from "../../common_btn/orange_btn/Orange_Btn";
import { useDispatch } from "react-redux";
import {
  getAllWalletHistory,
  postAddMoney,
} from "../../../../features/wallet/walletSlice";
import { useForm } from "react-hook-form";
import Success_Modal from "../success_modal/Success_Modal";
import { useRazorpay } from "react-razorpay";
import Script from "next/script";

import Green_btn from "../../common_btn/green_btn/Green_btn";
function Add_Money_Modal({ ...props }) {
  const [amount, setAmount] = useState("");
  const [paymentMethod, setPaymentMethod] = useState("credit-card");
  const [cardNumber, setCardNumber] = useState("");
  const [expiryDate, setExpiryDate] = useState("");
  const [cvv, setCvv] = useState("");

  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm();
  const [razorid, setRazorId] = useState();
  const dispatch = useDispatch();
  const finalFunction = async (d) => {
    const data = {
      transaction_id: razorid,
      amount: d.amount,
      transaction_type: "credit",
    };
    const res = await dispatch(postAddMoney({ data }));
    if (res.meta?.requestStatus === "fulfilled") {
      setShowSucsessModal(true);
      reset();
      props?.onHide();
      await dispatch(getAllWalletHistory());
    } else if (res.meta?.requestStatus === "rejected") {
    }
  };

  const Razorpay = useRazorpay();

  const handleRazorpay = async (data) => {
    const amountInPaise = data.amount * 100;
    const options = {
      // key: "rzp_test_I05KCFb1v5JJRc",
      key: process.env.NEXT_PUBLIC_RAZORPAY_KEY,
      amount: amountInPaise,
      currency: "INR",
      name: "A-Mart",
      description: "Test Transaction",
      image:
        "http://localhost:3000/static/media/hippicart-logo.427718645d3015dbf003.png",

      handler: async (res) => {
        await setRazorId(res.razorpay_payment_id);
        finalFunction(data);
      },
      prefill: {
        name: "Piyush Garg",
        email: "youremail@example.com",
        contact: "9999999999",
      },
      notes: {
        address: "Razorpay Corporate Office",
      },
      theme: {
        color: "#052c65",
      },
    };

    // const rzpay = new Razorpay(options);
    const rzpay = new window.Razorpay(options);

    rzpay.open();
  };

  return (
    <>

      <Script
        src="https://checkout.razorpay.com/v1/checkout.js"
        strategy="lazyOnload"
      />

      <Modal className=" Withdrow_Modal" {...props} centered>
        <Modal.Header closeButton className="modal-header-custom">
          <Modal.Title>Add Money to Wallet</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <div className="form-group input_group">
              <Form.Label>Amount</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter amount"
                {...register("amount", {
                  required: "Amount is required",
                  min: {
                    value: 1,
                    message: "Minimum amount is 1",
                  },
                  //   max: {
                  //     value: currentBalance,
                  //     message: `Amount must be less than or equal to ${currentBalance}`,
                  //   },
                })}
                onKeyDown={(e) => {
                  // Allow: backspace, delete, tab, escape, enter, arrows
                  if (
                    [8, 9, 27, 13, 37, 38, 39, 40].includes(e.keyCode) ||
                    (e.keyCode === 65 && e.ctrlKey) // Ctrl+A
                  ) {
                    return;
                  }
                  // Block non-number keys
                  if (!/^[0-9]$/.test(e.key)) {
                    e.preventDefault();
                  }
                }}
              />
              {errors.amount && (
                <p className="text-danger">{errors.amount.message}</p>
              )}
            </div>

            {/* <div className="form-group input_group">
                            <Form.Label>Payment Method</Form.Label>
                            <Form.Select value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value)}>
                                <option value="credit-card">Credit Card</option>
                                <option value="debit-card">Debit Card</option>
                                <option value="bank-transfer">Bank Transfer</option>
                                <option value="paypal">PayPal</option>
                            </Form.Select>
                        </div>

                        {(paymentMethod === "credit-card" || paymentMethod === "debit-card") && (
                            <>
                                <div className="form-group input_group">
                                    <Form.Label>Card Number</Form.Label>
                                    <Form.Control
                                        type="text"
                                        placeholder="1234 5678 9012 3456"
                                        value={cardNumber}
                                        onChange={(e) => setCardNumber(e.target.value)}
                                        maxLength={19}
                                        required
                                    />
                                </div>

                                <div className="row">
                                    <div className="col-md-6">
                                        <div className="form-group input_group">
                                            <Form.Label>Expiry Date</Form.Label>
                                            <Form.Control
                                                type="text"
                                                placeholder="MM/YY"
                                                value={expiryDate}
                                                onChange={(e) => setExpiryDate(e.target.value)}
                                                maxLength={5}
                                                required
                                            />
                                        </div>
                                    </div>
                                    <div className="col-md-6">
                                        <div className="form-group input_group">
                                            <Form.Label>CVV</Form.Label>
                                            <Form.Control
                                                type="text"
                                                placeholder="123"
                                                value={cvv}
                                                onChange={(e) => setCvv(e.target.value)}
                                                maxLength={4}
                                                required
                                            />
                                        </div>
                                    </div>
                                </div>
                            </>
                        )}

                        {paymentMethod === "bank-transfer" && (
                            <div className="form-group input_group">
                                <Form.Label>Bank Account</Form.Label>
                                <Form.Control type="text" placeholder="Enter bank account number" required />
                            </div>
                        )}

                        {paymentMethod === "paypal" && (
                            <div className="form-group input_group">
                                <Form.Label>PayPal Email</Form.Label>
                                <Form.Control type="email" placeholder="Enter PayPal email" required />
                            </div>
                        )} */}
          </Form>
          <div className="btn_holder">
            <Gray_Btn
              btnText={"No"}
              onClick={() => {
                props?.onHide();
              }}
            />
            <Green_btn
              btnText="Yes"
              type="submit"
              onClick={handleSubmit(handleRazorpay)}
            />
          </div>
        </Modal.Body>

        <Success_Modal
          show={showSuccessModal}
          onHide={() => {
            setShowSucsessModal(false);
          }}
          successText="Withdraw Request Eend Successfully!"
        />
      </Modal>
    </>
  );
}

export default Add_Money_Modal;
