import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { WillingToInvest } from "../redux/features/authSlice";

import { toast } from "react-toastify";

const FundToInvest = () => {
  const { user } = useSelector((state) => ({ ...state.auth }));
  console.log("user", user);
  const dispatch = useDispatch();

  const [formData, setFormData] = useState({
    userId: user?.result?.userId || "",
    fundAmount: user?.result?.fundAmount || "",
  });

  useEffect(() => {
    if (user) {
      setFormData({
        userId: user?.result?.userId,
        fundAmount: user?.result?.fundAmount,
      });
    }
  }, [user]);

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (formData.fundAmount <= 0) {
      return toast.error("Please enter a valid funding amount greater than 0");
    }

    dispatch(WillingToInvest({formData, toast }));
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <div className="col-4">
          <div className="form-floating mb-3">
            Willing to Invest
            <input
              type="text"
              className="form-control"
              placeholder="Enter Fund Amount"
              name="fundAmount"
              value={formData.fundAmount}
              onChange={handleChange}
            />
          </div>
        </div>

        <div className="col-12">
          <div className="d-grid">
            <button
              className="btn btn-primary btn-lg"
              type="submit"
              style={{
                backgroundColor: "#fda417",
                border: "#fda417",
              }}
            >
              submit
            </button>
          </div>
        </div>
      </form>
    </>
  );
};

export default FundToInvest;
