import { useDispatch, useSelector } from "react-redux";
import { submitProperty } from "../redux/features/propertySlice";
import { useState, useEffect } from "react";
import Navbar from "./Navbar";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import "../addproperty.css";

const Addproperty = () => {
  const [activeTab, setActiveTab] = useState("propertydetails");

  const handleContinue = () => {
    if (activeTab === "propertydetails") setActiveTab("shipping");
  };

  const handleBack = () => {
    if (activeTab === "shipping") setActiveTab("propertydetails");
  };

  const dispatch = useDispatch();
  const { status, error } = useSelector((state) => state.property);
  const { user } = useSelector((state) => ({ ...state.auth }));

  const [formData, setFormData] = useState({
    propertyType: "",
    title: "",
    yearBuild: "",
    totalSqft: "", // Used in the shipping tab
  });

  const [submitted, setSubmitted] = useState(false);

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

  const handleSubmit = () => {
    if (
      formData.propertyType &&
      formData.title &&
      formData.yearBuild &&
      formData.totalSqft
    ) {
      // Add user info to formData
      const formDataWithUserInfo = {
        ...formData,
        userfirstname: user?.result?.firstName,
        usermiddlename: user?.result?.middleName,
        userlastname: user?.result?.lastName,
        usertitle: user?.result?.title,
        useremail: user?.result?.email,
        userId:user?.result?.userId,
      };

      // Dispatch the form data with user info
      dispatch(submitProperty(formDataWithUserInfo));
      setSubmitted(true);
    } else {
      toast.error("Please fill all fields before submitting", {
        position: "top-right",
        autoClose: 3000,
      });
    }
  };

  useEffect(() => {
    if (submitted) {
      if (status === "succeeded") {
        toast.success("Property submitted successfully!", {
          position: "top-right",
          autoClose: 3000,
        });
        setSubmitted(false);
      } else if (status === "failed") {
        toast.error(`Failed to submit: ${error}`, {
          position: "top-right",
          autoClose: 3000,
        });
        setSubmitted(false);
      }
    }
  }, [status, error, submitted]);

  return (
    <>
      <div className="container tabs-wrap">
        <Navbar />

        <ul className="nav nav-tabs" role="tablist">
          <li
            role="presentation"
            className={activeTab === "propertydetails" ? "active tab" : "tab"}
          >
            <a onClick={() => setActiveTab("propertydetails")} role="tab">
              Property Details
            </a>
          </li>
          <li
            role="presentation"
            className={activeTab === "shipping" ? "active tab" : "tab"}
          >
            <a onClick={() => setActiveTab("shipping")} role="tab">
              Delivery Address
            </a>
          </li>
        </ul>

        <div className="tab-content">
          {activeTab === "propertydetails" && (
            <div role="tabpanel" className="tab-pane active">
              <h3>Property Details</h3>
              <form>
                <div className="row gy-3 overflow-hidden">
                  <div className="col-12">
                    <select
                      className="form-floating mb-3 form-control"
                      name="propertyType"
                      value={formData.propertyType}
                      onChange={handleInputChange}
                      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="title"
                        value={formData.title}
                        onChange={handleInputChange}
                        placeholder="Property title"
                        required
                      />
                      <label htmlFor="title" className="form-label">
                        Property Title
                      </label>
                    </div>
                  </div>
                  <div className="col-12">
                    <div className="form-floating mb-3">
                      <input
                        type="text"
                        className="form-control"
                        name="yearBuild"
                        value={formData.yearBuild}
                        onChange={handleInputChange}
                        placeholder="Year build"
                        required
                      />
                      <label htmlFor="yearBuild" className="form-label">
                        Year Build
                      </label>
                    </div>
                  </div>
                </div>
              </form>
              <button
                className="btn btn-primary continue"
                onClick={handleContinue}
                style={{ backgroundColor: "#fda417", border: "#fda417" }}
              >
                Continue
              </button>
            </div>
          )}
          {activeTab === "shipping" && (
            <div role="tabpanel" className="tab-pane active">
              <h3>Shipping Address</h3>
              <form>
                <div className="row gy-3 overflow-hidden">
                  <div className="col-12">
                    <div className="form-floating mb-3">
                      <input
                        type="text"
                        className="form-control"
                        name="totalSqft"
                        value={formData.totalSqft}
                        onChange={handleInputChange}
                        placeholder="Total SQFT"
                        required
                      />
                      <label htmlFor="totalSqft" className="form-label">
                        Total SQFT
                      </label>
                    </div>
                  </div>
                </div>
              </form>
              <button
                className="btn btn-primary back"
                onClick={handleBack}
                style={{ backgroundColor: "#fda417", border: "#fda417" }}
              >
                Go Back
              </button>{" "}
              <button
                type="button"
                className="btn btn-primary continue"
                style={{ backgroundColor: "#fda417", border: "#fda417" }}
                onClick={handleSubmit}
              >
                Submit
              </button>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default Addproperty;
