import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import { fetchPropertyById } from "../redux/features/propertySlice";
import propertydummy from "../img/propertydummy.jpg";
import Navbar from "./Navbar";
import Footer from "./Footer";
import { Modal, Button, Form } from "react-bootstrap"; // Importing Modal components
import { addFundDetails } from "../redux/features/propertySlice";
import { toast } from "react-toastify";
import { deleteFundDetail } from "../redux/features/propertySlice";
import "../propertyview.css";

const PropertyView = () => {
  const { id } = useParams(); // Extract the property ID from the route
  const dispatch = useDispatch();
  const { selectedProperty, status, error } = useSelector(
    (state) => state.property
  );
  const { user } = useSelector((state) => ({ ...state.auth }));
  // console.log("usr", user.result.userId);

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

  const [loading, setLoading] = useState(true); // Loader state
  const [showModal, setShowModal] = useState(false); // Modal state

  const [formData, setFormData] = useState({
    fundValue: "0",
    fundPercentage: "0",
  });

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

  useEffect(() => {
    if (status === "succeeded") {
      setLoading(false);
    }
  }, [status]);

  // if (status === "loading") {
  //   return <p>Loading property details...</p>;
  // }

  if (status === "failed") {
    return <p>Error loading property: {error}</p>;
  }

  // Handle conditions for the "Willing to Invest/Fund" button and messages
  const isOwner = user?.result?.userId === selectedProperty?.userId;
  const isLoggedIn = !!user;

  const handleShowModal = () => {
    setShowModal(true); // Show the modal
  };

  const handleCloseModal = () => {
    setShowModal(false); // Close the modal
  };

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

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

    // if (
    //   formData.fundValue <= 0 ||
    //   formData.fundPercentage <= 0 ||
    //   formData.fundPercentage > 100
    // ) {
    //   return toast.error("Please enter a valid funding amount and percentage (0-100)");
    // }

    if (formData.fundValue <= 0) {
      return toast.error("Please enter a valid funding amount greater than 0");
    }
    
    if (
      formData.fundValue > (selectedProperty?.totalCoststoBuyAtoB || 0)
    ) {
      return toast.error(`Funding amount cannot exceed ${selectedProperty?.totalCoststoBuyAtoB || "N/A"}`);
    }
    
    if (formData.fundPercentage <= 0 || formData.fundPercentage > 100) {
      return toast.error("Please enter a valid interest percentage (0-100)");
    }
    
    const fundDetails = {
      fundValue: Number(formData.fundValue), // Ensure number conversion if needed
      fundPercentage: Number(formData.fundPercentage),
      userId: user.result._id,
    };

    dispatch(addFundDetails({ id, fundDetails, toast }));
    handleCloseModal();
  };

  // const handleDelete = (fundDetailId) => {
  //   dispatch(deleteFundDetail({ id, fundDetailId }));
  // };

 

  const handleDelete = (fundDetailId) => {
    const token = JSON.parse(localStorage.getItem("profile")).token;
    dispatch(deleteFundDetail({ id, fundDetailId, token }));
  };

  const handleDeleteWithConfirmation = (id) => {
    const confirmed = window.confirm("Are you sure you want to delete this?");
    if (confirmed) {
      handleDelete(id);
    }
  };

  return (
    <>
      <Navbar />
      <br /> <br /> <br /> <br /><br />
     
      {/* <div className="container tabs-wrap col-12"> */}
      <div>

        <ul className="nav nav-tabs" role="tablist" style={{borderRadius: "12px 12px 0 0"}}>
          <li
            role="presentation"
            className={activeTab === "propertydetails" ? "active tab" : "tab"}
          >
            <a onClick={() => setActiveTab("propertydetails")} role="tab">
              Property Details
            </a>
          </li>
          <li
            role="presentation"
            className={activeTab === "Funding Details" ? "active tab" : "tab"}
          >
            <a onClick={() => setActiveTab("Funding Details")} role="tab">
              Funding Details
            </a>
          </li>

          <li
            role="presentation"
            className={activeTab === "Accounting" ? "active tab" : "tab"}
          >
            <a onClick={() => setActiveTab("Accounting")} role="tab">
              Accounting
            </a>
          </li>
        </ul>

        {/* <div className="tab-content"> */}
        <div>
          {activeTab === "propertydetails" && (
            <div
              role="tabpanel"
              className="card container tab-pane active col-12"
            >
              <div className="container col-12">
                {loading ? (
                  <div className="loader">Loading...</div> // Loader
                ) : selectedProperty ? (
                  <div className="py-3 py-md-5 bg-light">
                    <div className="card-header bg-white">
                      <div className="row">
                        <div className="col-md-5 mt-3">
                          <div>
                            {selectedProperty.images &&
                            selectedProperty.images[0] ? (
                              <img
                                src={
                                  selectedProperty.images[0].file ||
                                  propertydummy
                                }
                                alt="Property Thumbnail"
                                style={{
                                  marginTop: "0px",
                                  maxWidth: "400px",
                                  maxHeight: "400px",
                                }}
                              />
                            ) : (
                              <img
                                src={propertydummy}
                                alt="Default Property Thumbnail"
                                style={{
                                  marginTop: "0px",
                                  maxWidth: "400px",
                                  maxHeight: "400px",
                                }}
                              />
                            )}

                            {/* <img
  src={selectedProperty.images?.[0]?.file || propertydummy}
  alt="Property Thumbnail"
  style={{ marginTop: "0px", maxWidth: "400px", maxHeight: "400px" }}
  loading="lazy"
/> */}
                          </div>
                          <br />
                          <div className="label-stock border">
                            <p
                              style={{
                                color: "#fda417",
                                fontSize: "30px",
                                padding: "10px",
                                fontWeight: "normal",
                              }}
                            >
                              Funding Required:{" "}
                              <span
                                style={{ color: "#000000", fontSize: "25px" }}
                              >
                                <span
                                  className="fa fa-dollar"
                                  style={{ color: "#F74B02" }}
                                />{" "}
                                {selectedProperty?.totalCoststoBuyAtoB || "N/A"}
                              </span>
                            </p>
                            <p
                              style={{
                                color: "#fda417",
                                fontSize: "30px",
                                padding: "10px",
                                fontWeight: "normal",
                              }}
                            >
                              Net profit:{" "}
                              <span
                                style={{ color: "#000000", fontSize: "25px" }}
                              >
                                <span
                                  className="fa fa-dollar"
                                  style={{ color: "#F74B02" }}
                                />{" "}
                                {/* {selectedProperty.NetProfit} */}
                                {selectedProperty?.NetProfit || "N/A"}
                              </span>
                            </p>
                          </div>

                          <br />
                          {/* "Willing to Invest/Fund" Button and Conditional Messages */}
                          <button
                            className="btn btn-primary back"
                            style={{
                              backgroundColor: "#fda417",
                              border: "#fda417",
                            }}
                            disabled={isOwner || !isLoggedIn}
                            onClick={
                              isOwner || !isLoggedIn ? null : handleShowModal
                            } // Show modal only if not owner or logged in
                          >
                            <span
                              style={{
                                fontSize: "25px",
                                fontWeight: "normal",
                              }}
                            >
                              Willing to Invest/Fund
                            </span>{" "}
                          </button>
                          {isOwner && (
                            <span style={{ color: "red", marginTop: "10px" }}>
                              You cannot invest in your own property.
                            </span>
                          )}
                          {!isLoggedIn && (
                            <span style={{ color: "red", marginTop: "10px" }}>
                              Please login to invest.
                            </span>
                          )}
                        </div>

                        <div className="col-md-7 mt-3">
                          <div className="product-view">
                            <h4
                              className="product-name"
                              style={{ color: "#fda417", fontSize: "25px" }}
                            >
                              {selectedProperty.address}
                              <label className="label-stock bg-success">
                                Verified Property
                              </label>
                            </h4>
                            <hr />

                            <span className="product-path">
                              <span
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                City:{"   "}
                              </span>{" "}
                              {selectedProperty.city}
                              {"   "} /{"      "}
                              {"   "}
                              {"   "}
                              <span
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                County:{" "}
                              </span>{" "}
                              {selectedProperty.county} {"   "}/{"      "}
                              {"   "}
                              <span
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                State:{" "}
                              </span>{" "}
                              {selectedProperty.state} {"   "}/ {"     "}
                              {"   "}
                              <span
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                Zipcode:{" "}
                              </span>{" "}
                              {selectedProperty.zip}
                              {"    "}
                            </span>
                           
                            <br /> <br />
                            <div>
                              <span
                                className="selling-price"
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                Total Living Square Foot:{" "}
                              </span>
                              {selectedProperty.totallivingsqft}
                              <p></p>
                              <span
                                className="selling-price"
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                Cost per Square Foot:{" "}
                              </span>
                              ${selectedProperty.costpersqft}/sqft
                              <p></p>
                              <span
                                className="selling-price"
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                Year Built:{" "}
                              </span>
                              {selectedProperty.yearBuild}
                            </div>

                            <div className="mt-3 card bg-white label-stock border">
                              <h5
                                className="mb-0"
                                style={{ color: "#fda417", fontSize: "15px" }}
                              >
                                Legal Description
                              </h5>
                              <span>
                                {selectedProperty.legal
                                  ? selectedProperty.legal
                                  : "No data available"}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div className="row">
                        <div className="col-md-12 mt-3">
                          <div className="card">
                            <div className="card-header bg-white">
                              <h4
                                className="product-name"
                                style={{ color: "#fda417", fontSize: "25px" }}
                              >
                                Description
                              </h4>
                            </div>
                            <div className="card-body">
                              <p>
                                Lorem Ipsum is simply dummy text of the printing
                                and typesetting industry. Lorem Ipsum has been
                                the industry's standard dummy text ever since
                                the 1500s, when an unknown printer took a galley
                                of type and scrambled it to make a type specimen
                                book. It has survived not only five centuries,
                                but also the leap into electronic typesetting,
                                remaining essentially unchanged. It was
                                popularised in the 1960s with the release of
                                Letraset sheets containing Lorem Ipsum passages,
                                and more recently with desktop publishing
                                software like Aldus PageMaker including versions
                                of Lorem Ipsum.
                              </p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ) : (
                  <p>No property found.</p>
                )}
              </div>
            </div>
          )}

          {activeTab === "Funding Details" && (
            <div>
              {activeTab === "Funding Details" && (
                <div className="tab-pane active">
                <div>
  {selectedProperty.fundDetails.length === 0 ? (
    <p>No fund details available.</p>
  ) : (
    <ul style={{ listStyleType: "none", padding: 0 }}>
      {selectedProperty.fundDetails.map((detail, index) => (
        <li key={index} className="d-flex align-items-center">
          <div className="d-flex align-items-center">
            <span>
              Total Fund Value: $ {detail.fundValue}, Interest Percentage: {detail.fundPercentage}%
            
            </span>
            <br />  <br />
            {user?.result?.userId && user?.result?._id === detail.userId && (
              <button
                className="btn btn-danger ms-2"
                // onClick={() => handleDelete(detail._id)}
                onClick={() => handleDeleteWithConfirmation(detail._id)}
                style={{ padding: "2px 10px", marginLeft: "8px" }}
              >
                x
              </button>
            )}
          </div>
        </li>
      ))}
    </ul>
  )}
</div>


                </div>
              )}
            </div>
          )}

          {activeTab === "Accounting" && <div></div>}
        </div>
      </div>
      <Footer />
      {/* Modal for Investment/Funding */}
      <Modal show={showModal} onHide={handleCloseModal}>
        <Modal.Header closeButton>
          <Modal.Title>Investment/Funding Details</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form onSubmit={handleSubmit}>
            <Form.Group>
              <Form.Label>Total Fund Value</Form.Label>
              <Form.Control
                type="number"
                id="fundValue"
                name="fundValue" // Added the name attribute
                value={formData.fundValue}
                onChange={handleChange}
              />
            </Form.Group>
            <br />
            <Form.Group>
              <Form.Label>Interest Percentage</Form.Label>
              <Form.Control
                type="number"
                id="fundPercentage"
                name="fundPercentage" // Added the name attribute
                value={formData.fundPercentage}
                onChange={handleChange}
              />
            </Form.Group>
            <Button variant="primary" type="submit">
              Submit
            </Button>
          </Form>
        </Modal.Body>
      </Modal>
    </>
  );
};

export default PropertyView;
