import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { fetchPropertyById } from "../redux/features/propertySlice";
import { updateProperty } from "../redux/features/propertySlice";
import { useParams } from "react-router-dom";

const EditProperty = () => {
  const { id } = useParams();
  const dispatch = useDispatch();
  const { selectedProperty } = useSelector((state) => state.property);

  const [formData, setFormData] = useState({
    propertyType: "",
    yearBuild: "",
    totalSqft: "",
  });

  useEffect(() => {
    dispatch(fetchPropertyById(id));
  }, [dispatch, id]);

  useEffect(() => {
    if (selectedProperty) {
      setFormData({
        propertyType: selectedProperty.propertyType,
        yearBuild: selectedProperty.yearBuild,
        totalSqft: selectedProperty.totalSqft,
      });
    }
  }, [selectedProperty]);

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

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch(updateProperty({ id, propertyData: formData }));
  };
  

  return (
    <div className="edit-property-form">
      <h2>Edit Property</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <select
            className="form-floating mb-3 form-control"
            name="propertyType"
            value={formData.propertyType}
            onChange={handleChange}
            required
          >
            <option value="">Please Select Property Type</option>
            <option value="Residential">Residential</option>
            <option value="Land">Land</option>
            <option value="Commercial">Commercial</option>
            <option value="Industrial">Industrial</option>
            <option value="Water">Water</option>
          </select>
        </div>

        <div className="col-12">
          <div className="form-floating mb-3">
            <input
              type="text"
              className="form-control"
              name="yearBuild"
              value={formData.yearBuild}
              onChange={handleChange}
              placeholder="Year build"
              required
            />
            <label htmlFor="yearBuild" className="form-label">
              Year Build
            </label>
          </div>
        </div>

        <div className="form-floating mb-3">
          <input
            type="text"
            className="form-control"
            name="totalSqft"
            value={formData.totalSqft}
            onChange={handleChange}
            placeholder="Total SQFT"
            required
          />
          <label htmlFor="totalSqft" className="form-label">
            Total SQFT
          </label>
        </div>

        <button type="submit">Update Property</button>
      </form>
    </div>
  );
};

export default EditProperty;
