import React, { useState } from "react";
import "./Withdrow_Modal.css";
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 { useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import {
  getAllWalletHistory,
  postWithdrawRequest,
} from "../../../../features/wallet/walletSlice";
import Success_Modal from "../success_modal/Success_Modal";
import Green_btn from "../../common_btn/green_btn/Green_btn";

function Withdrow_Modal({ currentBalance, ...props }) {
  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm();
  const dispatch = useDispatch();

  const onSubmit = async (data) => {
    console.log(errors, "Error messageuyyg");
    const res = await dispatch(postWithdrawRequest({ data }));
    if (res.meta?.requestStatus === "fulfilled") {
      setShowSucsessModal(true);
      reset();
      props?.onHide();
      await dispatch(getAllWalletHistory());
    } else if (res.meta?.requestStatus === "rejected") {
    }
  };

  return (
    <Modal className="Withdrow_Modal" {...props} centered>
      <Modal.Header closeButton className="modal-header-custom">
        <Modal.Title>Withdraw Money</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <Form>
          {/* Amount */}
          <div className="form-group input_group">
            <Form.Label>Amount</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter amount"
              {...register("amount", {
                required:
                  Number(currentBalance) > 0
                    ? "Amount is required"
                    : "No balance available",
                min: {
                  value: 1,
                  message: "Minimum amount is 1",
                },
                max: {
                  value: currentBalance,
                  message: `Amount must be less than or equal to ${currentBalance}`,
                },
              })}
              disabled={Number(currentBalance) === 0} // ✅ disable input if balance is 0
              onKeyDown={(e) => {
                if (currentBalance === 0) {
                  e.preventDefault(); // Prevent typing if balance is 0
                  return;
                }

                // 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();
                }
              }}
            />

            {/* Show custom error if balance is 0 */}
            {Number(currentBalance) === 0 && (
              <p className="text-danger">You have no balance available</p>
            )}

            {errors.amount && (
              <p className="text-danger">{errors.amount.message}</p>
            )}
          </div>

          {/* ifsc_code Code */}
          <div className="form-group input_group">
            <Form.Label>IFSC Code</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter IFSC code"
              {...register("ifsc_code", {
                required: "IFSC Code is required",
                pattern: {
                  value: /^[A-Z]{4}0[A-Z0-9]{6}$/,
                  message: "Enter a valid IFSC code (e.g., HDFC0001234)",
                },
              })}
            />
            {errors.ifsc_code && (
              <p className="text-danger">{errors.ifsc_code.message}</p>
            )}
          </div>

          {/* Account No */}
          <div className="form-group input_group">
            <Form.Label>Account No</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter account number"
              {...register("account_no", {
                required: "Account number is required",
                pattern: {
                  value: /^[0-9]{9,18}$/,
                  message: "Enter a valid account number (9 to 18 digits)",
                },
              })}
            />
            {errors.account_no && (
              <p className="text-danger">{errors.account_no.message}</p>
            )}
          </div>

          <div className="form-group input_group">
            <Form.Label>Branch Name</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Branch Name"
              {...register("branch_name", {
                required: "Branch Name Code is required",
              })}
            />
            {errors.branch_name && (
              <p className="text-danger">{errors.branch_name.message}</p>
            )}
          </div>

          <div className="form-group input_group">
            <Form.Label>Banking Name</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Banking Name"
              {...register("banking_name", {
                required: "Banking Name Code is required",
              })}
            />
            {errors.banking_name && (
              <p className="text-danger">{errors.banking_name.message}</p>
            )}
          </div>

          <div className="btn_holder mt-3">
            <Gray_Btn
              btnText={"No"}
              onClick={() => {
                props?.onHide();
                reset();
              }}
            />
            <Green_btn
              btnText="Yes"
              type="button"
              onClick={handleSubmit(onSubmit)}
            />
          </div>
        </Form>
      </Modal.Body>

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

export default Withdrow_Modal;
