"use client";

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

const API_BASE = "";

export default function ProductsPage() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("");

  const PAGE_SIZE = 100;
  const ITEMS_PER_PAGE = 20;
  const [currentPage, setCurrentPage] = useState(0);

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

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

  const totalPages = Math.ceil(products.length / ITEMS_PER_PAGE);
  const displayedProducts = products.slice(currentPage * ITEMS_PER_PAGE, (currentPage + 1) * ITEMS_PER_PAGE);

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

  return (
    <main className="products-page">
      <section className="products-hero">
        <h1 className="products-hero-title">Shop Our Products</h1>
        <p className="products-hero-subtitle">Everything your pet needs, all in one place</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 or category..."
              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>
        </div>
      </section>

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

        {error && (
          <p className="adopt-status-msg">Unable to load products, please try again later.</p>
        )}

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

        {!loading && !error && products.length > 0 && (
          <div className="adopt-grid">
            {displayedProducts.map((product) => (
              <ProductCard
                key={product.prodId}
                prodId={product.prodId}
                prodName={product.prodName}
                categoryName={product.categoryName}
                prodPrice={product.prodPrice}
                imageUrl={product.imageUrl}
              />
            ))}
          </div>
        )}
        {!loading && !error && totalPages > 1 && (
          <div className="pagination-controls">
            <button
              className="pagination-btn"
              onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
              disabled={currentPage === 0}
            >
              ← Prev
            </button>
            <span className="pagination-info">Page {currentPage + 1} of {totalPages}</span>
            <button
              className="pagination-btn"
              onClick={() => setCurrentPage((p) => Math.min(totalPages - 1, p + 1))}
              disabled={currentPage === totalPages - 1}
            >
              Next →
            </button>
          </div>
        )}
      </section>
    </main>
  );
}
