import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { getProperties } from "../redux/features/propertySlice"; // Redux action to fetch properties
import profilepic from "../img/propertydummy.jpg";
import { NavLink } from "react-router-dom";
import Navbar from "./Navbar";
import Footer from "./Footer";
import "../searchmysqlresults.css";

const SearchProperties = () => {
  const dispatch = useDispatch();
  const { properties, loading, totalPages, currentPage } = useSelector(
    (state) => state.property
  );
  const [keyword, setKeyword] = useState("");
  const [filteredProperties, setFilteredProperties] = useState([]);

  // Set pagination state
  const [page, setPage] = useState(1);
  const limit = 10; // Number of results per page

  // Dispatch getProperties to load properties on page change
//   useEffect(() => {
//     dispatch(getProperties({ page, limit }));
//   }, [dispatch, page]);

  // Dispatch getProperties to load properties on page or keyword change
useEffect(() => {
    dispatch(getProperties({ page, limit, keyword }));
  }, [dispatch, page, keyword]);
  

  // Filter properties based on the keyword entered
  useEffect(() => {
    if (keyword.trim()) {
      setFilteredProperties(
        properties.filter((property) =>
          property.address.toLowerCase().includes(keyword.toLowerCase())
        )
      );
    } else {
      setFilteredProperties(properties); // Show all properties when no keyword
    }
  }, [keyword, properties]);

  const handleSearchChange = (e) => {
    setKeyword(e.target.value);
  };

  const handleSearchSubmit = (e) => {
    e.preventDefault();
  };

//   const handlePageChange = (newPage) => {
//     setPage(newPage); // Update the current page when user clicks pagination
//   };

  const handlePageChange = (newPage) => {
    setPage(newPage);
    dispatch(getProperties({ page: newPage, limit, keyword })); // Pass the keyword when changing page
  };
  

  return (
    <>
      <Navbar />
      <br />
      <br />
      <br />
      <br />
      <br />
      <br />
      <div className="container col-12">
        <div className="row">
          <div className="col-lg-12 card-margin col-12">
            <div className="card search-form col-12">
              <div className="card-body p-0">
                <form id="search-form" onSubmit={handleSearchSubmit}>
                  <div className="row">
                    <div className="col-12">
                      <div className="row no-gutters">
                        <div className="col-lg-8 col-md-6 col-sm-12 p-0">
                          <input
                            type="text"
                            value={keyword}
                            onChange={handleSearchChange}
                            placeholder="Enter the keyword and hit ENTER button..."
                            className="form-control"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>

        {/* Display the properties */}
        <div className="row">
          <div className="col-12">
            <div className="card card-margin">
              <div className="card-body">
                {loading ? (
                  <div>Loading...</div>
                ) : (
                  <div className="table-responsive">
                    <table className="table widget-26">
                      <thead style={{ color: "#fda417", fontSize: "15px" }}>
                        <tr>
                          <th>Image</th>
                          <th>Details</th>
                          <th>Total Living Square Foot</th>
                          <th>Year Built</th>
                          <th>Cost per Square Foot</th>
                        </tr>
                      </thead>
                      <tbody>
                        {filteredProperties.length > 0 ? (
                          filteredProperties.map((property) => (
                            <tr key={property.id}>
                              <td>
                                {property.images && property.images[0] ? (
                                  <img
                                    src={property.images[0].file || profilepic}
                                    alt="Property Thumbnail"
                                    style={{ width: "100px", height: "auto" }}
                                  />
                                ) : (
                                  <img
                                    src={profilepic}
                                    alt="Default Property Thumbnail"
                                    style={{ width: "100px", height: "auto" }}
                                  />
                                )}
                              </td>
                              <td>
                                <div className="widget-26-job-title">
                                  <NavLink
                                    to={`/property/${property.propertyId}`}
                                    className="link-primary text-decoration-none"
                                    target="_blank"
                                  >
                                    {property.address}
                                  </NavLink>
                                  <p className="m-0">
                                    <span className="employer-name">
                                      <i
                                        className="fa fa-map-marker"
                                        style={{ color: "#F74B02" }}
                                      />
                                      {property.city}, {property.county},{" "}
                                      {property.state}
                                    </span>
                                    <p className="text-muted m-0">
                                      House Id: {property.propertyId}
                                    </p>
                                  </p>
                                </div>
                              </td>
                              <td>{property.totallivingsqft}</td>
                              <td>{property.yearBuild}</td>
                              <td>{property.costpersqft}</td>
                            </tr>
                          ))
                        ) : (
                          <tr>
                            <td colSpan="5">No properties found.</td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Pagination Controls */}
        {/* Pagination */}
        <nav aria-label="Page navigation">
          <ul className="pagination justify-content-center">
            <li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
              <button
                className="page-link"
                onClick={() => handlePageChange(currentPage - 1)}
              >
                Previous
              </button>
            </li>
            {Array.from({ length: totalPages }, (_, index) => (
              <li
                key={index + 1}
                className={`page-item ${
                  currentPage === index + 1 ? "active" : ""
                }`}
              >
                <button
                  className="page-link"
                  onClick={() => handlePageChange(index + 1)}
                >
                  {index + 1}
                </button>
              </li>
            ))}
            <li
              className={`page-item ${
                currentPage === totalPages ? "disabled" : ""
              }`}
            >
              <button
                className="page-link"
                onClick={() => handlePageChange(currentPage + 1)}
              >
                Next
              </button>
            </li>
          </ul>
        </nav>
      </div>
      <Footer />
    </>
  );
};

export default SearchProperties;
