import { useEffect, useState } from "react";
import { NavLink } from "react-router-dom";
import axios from "axios";
import Navbar from "./Navbar";
import Footer from "./Footer";
import "../searchmysqlresults.css";

const SearchMysqlProperties = () => {
  const [properties, setProperties] = useState([]);
  const [totalRecords, setTotalRecords] = useState(0);
  const [page, setPage] = useState(0);
  const [limit] = useState(10);
  const [search, setSearch] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [showResultsMessage, setShowResultsMessage] = useState(false);

  // Fetch properties from API
  const fetchProperties = async () => {
    setIsLoading(true);
    setShowResultsMessage(false); // Reset message before fetching
    try {
      const res = await axios.get(
        `${import.meta.env.VITE_REACT_APP_SECRET}/mysql/searchmysql`,
        {
          params: { limit, offset: page * limit, search },
          headers: { "Cache-Control": "no-cache" },
        }
      );
      setProperties(res.data.data);
      setTotalRecords(res.data.totalRecords);
      if (search.trim()) {
        setShowResultsMessage(true); // Show message if there's a search term
      }
    } catch (err) {
      console.log("Error fetching data:", err);
    } finally {
      setIsLoading(false);
    }
  };

  // Handle search input change
  const handleSearchChange = (e) => {
    setSearch(e.target.value);
    if (e.target.value.trim() === "") {
      setPage(0); // Reset to first page
      setProperties([]); // Clear properties
      setTotalRecords(0); // Clear total records
      setShowResultsMessage(false); // Hide message
      fetchProperties(); // Fetch default properties
    }
  };

  // Handle key press events (Enter)
  const handleKeyPress = (e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      fetchProperties(); // Fetch properties on Enter key
    }
  };

  // Use effect to fetch properties when search or page changes
  useEffect(() => {
    fetchProperties();
  }, [search, page]); // Fetch when search or page changes

  const totalPages = Math.ceil(totalRecords / limit);

  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">
                  <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"
                            placeholder="Enter the keyword and hit ENTER button..."
                            className="form-control"
                            id="search"
                            name="search"
                            value={search}
                            onChange={handleSearchChange}
                            onKeyDown={handleKeyPress}
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-12">
            <div className="card card-margin">
              <div className="card-body">
                {showResultsMessage && properties.length > 0 && (
                  <div>
                    Showing search results for the keyword{" "}
                    <span style={{ color: "#fda417", fontSize: "25px" }}>
                      {search}
                    </span>
                  </div>
                )}
                <div className="table-responsive">
                  <table className="table widget-26">
                    <thead style={{ color: "#fda417", fontSize: "15px" }}>
                      <tr>
                        <th>Details</th>
                        <th>Total Living Square Foot</th>
                        <th>Year Built</th>
                        <th>Cost per Square Foot</th>
                      </tr>
                    </thead>
                    <tbody>
                      {properties.length > 0 ? (
                        properties.map((property, index) => (
                          <tr key={index}>
                            <td>
                              <div className="widget-26-job-title">
                                <NavLink
                                  to={`/properties/${property.house_id}`}
                                  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.house_id}
                                  </p>
                                </p>
                              </div>
                            </td>
                            <td>
                              <div className="widget-26-job-info">
                                <p className="m-0">
                                  {property.total_living_sqft}
                                </p>
                              </div>
                            </td>
                            <td>
                              <div className="widget-26-job-info">
                                <p className="m-0">{property.year_built}</p>
                              </div>
                            </td>
                            <td>
                              <div className="widget-26-job-salary">
                                $ {property.cost_per_sqft}/sqft
                              </div>
                            </td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td colSpan="4">No results found</td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
                {/* Pagination Controls */}
                <div>
                  <button
                    onClick={() => setPage(page - 1)}
                    disabled={page === 0 || isLoading}
                    style={{
                      backgroundColor: "#fda417",
                      border: "#fda417",
                    }}
                  >
                    Previous
                  </button>
                  <span>
                    {" "}
                    Page {page + 1} of {totalPages}{" "}
                  </span>
                  <button
                    onClick={() => setPage(page + 1)}
                    disabled={page + 1 >= totalPages || isLoading}
                    style={{
                      backgroundColor: "#fda417",
                      border: "#fda417",
                    }}
                  >
                    Next
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </>
  );
};

export default SearchMysqlProperties;
