"use client";

import { useState, useEffect } from "react";
import PetCard from "@/components/PetCard";
import { fetchAllPages } from "@/lib/fetchAllPages";

const API_BASE = "";

export default function AdoptPage() {
  const [pets, setPets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [health, setHealth] = useState(null);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("");

  const PAGE_SIZE = 100;

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/health`)
      .then((res) => (res.ok ? setHealth("online") : setHealth("error")))
      .catch(() => setHealth("offline"));
  }, []);

  useEffect(() => {
    setLoading(true);
    setError(null);

    fetchAllPages((page) => {
      const params = new URLSearchParams({
        page: String(page),
        size: String(PAGE_SIZE),
        sort: "id,asc",
        status: "Available",
      });
      if (query) {
        params.set("q", query);
      }
      return `${API_BASE}/api/v1/pets?${params}`;
    })
      .then((allPets) => {
        setPets(allPets);
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [query]);

  function handleSearch(e) {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setQuery(search.trim());
  }

  return (
    <main className="adopt-page">
      <section className="adopt-hero">
        <h1 className="adopt-hero-title">Find Your Perfect Companion</h1>
        <p className="adopt-hero-subtitle">Give a loving pet their forever home</p>
        <div className="title-decoration"></div>
      </section>

      <section className="adopt-controls">
        <div className="adopt-controls-row">
          <form className="adopt-search-form" onSubmit={handleSearch}>
            <input
              className="adopt-search-input"
              type="text"
               placeholder="Search by name, species, or breed..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            <button className="adopt-search-btn" type="submit">Search</button>
            {query && (
              <button
                className="adopt-clear-btn"
                type="button"
                onClick={() => { setLoading(true); setError(null); setSearch(""); setQuery(""); }}
              >
                Clear
              </button>
            )}
          </form>
          <span
            className={`backend-status backend-status--${health ?? "checking"}`}
            title={
              health === "online" ? "Backend online" :
              health === "offline" ? "Backend offline" :
              health === "error" ? "Backend error" : "Checking…"
            }
          />
        </div>
      </section>

      <section className="adopt-grid-section">
        {loading && <p className="adopt-status-msg">Loading pets...</p>}

        {error && (
          <div className="adopt-error-box">
            <p className="adopt-error-title">Failed to load pets</p>
            <code className="adopt-error-detail">{error}</code>
            <p className="adopt-error-hint">
              {health === "offline"
                ? "The Spring Boot backend is not reachable. Make sure it is running in IntelliJ on port 8080."
                : health === "error"
                ? "The backend responded with an error. Check the IntelliJ Run console for stack traces."
                : "The backend is reachable but the /pets endpoint failed. Check the IntelliJ Run console."}
            </p>
          </div>
        )}

        {!loading && !error && pets.length === 0 && (
          <p className="adopt-status-msg">No pets found.</p>
        )}

        {!loading && !error && pets.length > 0 && (
          <div className="adopt-grid">
            {pets.map((pet) => (
              <PetCard
                key={pet.petId}
                petId={pet.petId}
                petName={pet.petName}
                petSpecies={pet.petSpecies}
                petStatus={pet.petStatus}
                imageUrl={pet.imageUrl}
              />
            ))}
          </div>
        )}

      </section>
    </main>
  );
}
