import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { updateUser } from "../redux/features/authSlice";
import { useNavigate } from "react-router-dom";
import FileBase from "react-file-base64";

const UserProfile = () => {
  const { user, isLoading, error } = useSelector((state) => state.auth);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [formData, setFormData] = useState({
    userId: user?.result?.userId || "",
    title: user?.result?.title || "",
    firstName: user?.result?.firstName || "",
    middleName: user?.result?.middleName || "",
    lastName: user?.result?.lastName || "",
    email: user?.result?.email || "",
    aboutme: user?.result?.aboutme || "",
    profileImage: user?.result?.profileImage || "", // For storing the image
  });

  useEffect(() => {
    if (user) {
      setFormData({
        userId: user.result.userId,
        title: user.result.title,
        firstName: user.result.firstName,
        middleName: user.result.middleName,
        lastName: user.result.lastName,
        email: user.result.email,
        aboutme: user.result.aboutme,
        profileImage: user.result.profileImage,
      });
    }
  }, [user]);

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

  const handleImageDelete = () => {
    setFormData({ ...formData, profileImage: "" }); // Reset the profileImage field
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch(updateUser(formData)); // Dispatching updateUser with form data
    navigate("/login");
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <div className="col-4">
          Title
          <select
            className="form-floating mb-3 form-control"
            aria-label="Default select example"
            name="title"
            value={formData.title}
            onChange={handleChange}
          >
            <option value="None">Please Select Title</option>
            <option value="Dr">Dr</option>
            <option value="Prof">Prof</option>
            <option value="Mr">Mr</option>
            <option value="Miss">Miss</option>
          </select>
        </div>

        <div className="col-4">
          <div className="form-floating mb-3">
            First Name
            <input
              type="text"
              className="form-control"
              placeholder="First Name"
              required="required"
              name="firstName"
              value={formData.firstName}
              onChange={handleChange}
            />
          </div>
        </div>

        <div className="col-4">
          <div className="form-floating mb-3">
            Middle Name
            <input
              type="text"
              className="form-control"
              placeholder="Middle Name"
              required="required"
              name="middleName"
              value={formData.middleName}
              onChange={handleChange}
            />
          </div>
        </div>

        <div className="col-4">
          <div className="form-floating mb-3">
            Last Name
            <input
              type="text"
              className="form-control"
              placeholder="Last Name"
              required="required"
              name="lastName"
              value={formData.lastName}
              onChange={handleChange}
            />
          </div>
        </div>

        <div className="col-4">
          <div className="form-floating mb-3">
            Email
            <input
              type="text"
              className="form-control"
              placeholder="Email"
              required="required"
              name="email"
              value={formData.email}
              onChange={handleChange}
              disabled
            />
          </div>
        </div>

        <div className="col-4">
          <div className="form-floating mb-3">
            About me
            <textarea
              type="text"
              id="aboutme"
              name="aboutme"
              className="form-control h-100"
              value={formData.aboutme}
              onChange={handleChange}
            />
          </div>
        </div>

        {/* Profile Image Upload Section */}
        <div className="col-4">
          <label>Profile Image</label>
          <div className="mb-3">
            <FileBase
              type="file"
              multiple={false}
              onDone={({ base64 }) =>
                setFormData({ ...formData, profileImage: base64 })
              }
            />
          </div>
        </div>

        {/* Display Preview of Uploaded Image */}
        {formData.profileImage && (
          <div className="col-4 mb-3">
            <img
              src={formData.profileImage}
              alt="Profile Preview"
              style={{ width: "150px", height: "150px", borderRadius: "50%" }}
            />
            {/* Delete Image Button */}
            <button
              type="button"
              className="btn btn-danger mt-2"
              onClick={handleImageDelete}
            >
              Delete Image
            </button>
          </div>
        )}

        <div className="col-12">
          <div className="d-grid">
            <button
              className="btn btn-primary btn-lg"
              type="submit"
              style={{
                backgroundColor: "#fda417",
                border: "#fda417",
              }}
              disabled={isLoading}
            >
              {isLoading ? "Updating..." : "Update"}
            </button>
          </div>
        </div>
        {error && <p>{error}</p>}
      </form>
    </>
  );
};

export default UserProfile;
