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";
import { toast } from "react-toastify";

const UserProfile = () => {
  const { user, isLoading } = 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 || "",
    city: user?.result?.city || "",
    state: user?.result?.state || "",
    county: user?.result?.county || "",
    zip: user?.result?.zip || "",
    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,
        city: user.result.city,
        state: user.result.state,
        county: user.result.county,
        zip: user.result.zip,
        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, toast, navigate})); // Dispatching updateUser with form data
  };

  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>

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

                  <div className="col-md-4">
                    <div className="form-floating mb-3">
                      State
                      <select
                        className="form-floating mb-3 form-control"
                        name="state"
                        value={formData.state}
                        onChange={handleChange}
                        required
                      >
                        <option value="">Please Select State</option>
                        <option value="Alaska">Alaska</option>
                        <option value="Alabama">Alabama</option>
                        <option value="Arkansas">Arkansas</option>
                        <option value="Arizona">Arizona</option>
                        <option value="California">California</option>
                        <option value="Colorado">Colorado</option>
                        <option value="Connecticut">Connecticut</option>
                        <option value="District Of Columbia">
                          District Of Columbia
                        </option>
                        <option value="Delaware">Delaware</option>
                        <option value="Florida">Florida</option>
                        <option value="Georgia">Georgia</option>
                        <option value="Hawaii">Hawaii</option>
                        <option value="Iowa">Iowa</option>
                        <option value="Idaho">Idaho</option>
                        <option value="Illinois">Illinois</option>
                        <option value="Indiana">Indiana</option>
                        <option value="Kansas">Kansas</option>
                        <option value="Kentucky">Kentucky</option>
                        <option value="Louisiana">Louisiana</option>
                        <option value="Massachusetts">Massachusetts</option>
                        <option value="Maryland">Maryland</option>
                        <option value="Michigan">Michigan</option>
                        <option value="Minnesota">Minnesota</option>
                        <option value="Missouri">Missouri</option>
                        <option value="Mississippi">Mississippi</option>
                        <option value="Montana">Montana</option>
                        <option value="North Carolina">North Carolina</option>
                        <option value="North Dakota">North Dakota</option>
                        <option value="Nebraska">Nebraska</option>
                        <option value="New Hampshire">New Hampshire</option>
                        <option value="New Jersey">New Jersey</option>
                        <option value="New Mexico">New Mexico</option>
                        <option value="Nevada">Nevada</option>
                        <option value="New York">New York</option>
                        <option value="Ohio">Ohio</option>
                        <option value="Oklahoma">Oklahoma</option>
                        <option value="Oregon">Oregon</option>
                        <option value="Pennsylvania">Pennsylvania</option>
                        <option value="Rhode Island">Rhode Island</option>
                        <option value="South Carolina">South Carolina</option>
                        <option value="South Dakota">South Dakota</option>
                        <option value="Tennessee">Tennessee</option>
                        <option value="Texas">Texas</option>
                        <option value="Utah">Utah</option>
                        <option value="Virginia">Virginia</option>
                        <option value="Vermont">Vermont</option>
                        <option value="Washington">Washington</option>
                        <option value="Wisconsin">Wisconsin</option>
                        <option value="West Virginia">West Virginia</option>
                        <option value="Wyoming">Wyoming</option>
                      </select>
                    </div>
                  </div>

                  <div className="col-md-4">
                    County
                    <select
                      className="form-floating mb-3 form-control"
                      name="county"
                      value={formData.county}
                      onChange={handleChange}
                      required
                    >
                      <option value="">Please Select County</option>
                      <option value="Abbeville">Abbeville</option>
                      <option value="Aiken">Aiken</option>
                      <option value="Allendale">Allendale</option>
                      <option value="Anderson">Anderson</option>
                      <option value="Bamberg">Bamberg</option>
                      <option value="Barnwell">Barnwell</option>
                      <option value="Beaufort">Beaufort</option>
                      <option value="Berkeley">Berkeley</option>
                      <option value="Calhoun">Calhoun</option>
                      <option value="Charleston">Charleston</option>
                      <option value="Cherokee">Cherokee</option>
                      <option value="Chester">Chester</option>
                      <option value="Chesterfield">Chesterfield</option>
                      <option value="Clarendon">Clarendon</option>
                      <option value="Colleton">Colleton</option>
                      <option value="Darlington">Darlington</option>
                      <option value="Dillon">Dillon</option>
                      <option value="Dorchester">Dorchester</option>
                      <option value="Edgefield">Edgefield</option>
                      <option value="Fairfield">Fairfield</option>
                      <option value="Florence">Florence</option>
                      <option value="Georgetown">Georgetown</option>
                      <option value="Greenville">Greenville</option>
                      <option value="Greenwood">Greenwood</option>
                      <option value="Hampton">Hampton</option>
                      <option value="Horry">Horry</option>
                      <option value="Jasper">Jasper</option>
                      <option value="Kershaw">Kershaw</option>
                      <option value="Lancaster">Lancaster</option>
                      <option value="Laurens">Laurens</option>
                      <option value="Lee">Lee</option>
                      <option value="Lexington">Lexington</option>
                      <option value="Marion">Marion</option>
                      <option value="Marlboro">Marlboro</option>
                      <option value="McCormick">McCormick</option>
                      <option value="Newberry">Newberry</option>
                      <option value="Oconee">Oconee</option>
                      <option value="Orangeburg">Orangeburg</option>
                      <option value="Pickens">Pickens</option>
                      <option value="Richland">Richland</option>
                      <option value="Saluda">Saluda</option>
                      <option value="Spartanburg">Spartanburg</option>
                      <option value="Sumter">Sumter</option>
                      <option value="Union">Union</option>
                      <option value="Williamsburg">Williamsburg</option>
                      <option value="York">York</option>
                    </select>
                  </div>

                  <div className="col-4">
                    <div className="form-floating mb-3">
                      Zip
                      <input
                        type="text"
                        className="form-control"
                        name="zip"
                        placeholder="zip"
                        value={formData.zip}
                        onChange={handleChange}
                        required
                      />
                    </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>
       
      </form>
    </>
  );
};

export default UserProfile;
