"use client";

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

//Products page
//Searchable grid of all store products with pagination
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(setProducts)
      .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);

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

  return (
    <main className="min-h-screen">
      <section className="text-center py-16 px-8 bg-gradient-to-b from-[#f9f9f9] to-white">
        <h1 className="text-5xl font-bold text-[#333] mb-4 tracking-tight max-[768px]:text-3xl max-[480px]:text-[1.6rem]">Shop Our Products</h1>
        <p className="text-2xl font-light text-[#666] mb-8 max-[768px]:text-[1.2rem]">Everything your pet needs, all in one place</p>
        <div className="w-[100px] h-1 bg-[#e68672] mx-auto mt-8 rounded-sm"></div>
      </section>

      <section className="max-w-[1200px] mx-auto mb-6 px-8">
        <div className="flex items-center justify-between flex-wrap gap-4">
          <form className="flex gap-3 items-center" onSubmit={handleSearch}>
            <input
              className="flex-1 max-w-[400px] px-4 py-[0.6rem] border-2 border-[#ddd] rounded-md text-base outline-none transition-colors focus:border-[#e68672] font-[inherit]"
              type="text"
              placeholder="Search"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            <button className="px-[1.4rem] py-[0.6rem] bg-[#e68672] text-white border-none rounded-md text-base cursor-pointer transition-colors hover:bg-[#d4705e] font-[inherit]" type="submit">Search</button>
            {query && (
              <button
                className="px-4 py-[0.6rem] bg-transparent text-[#666] border-2 border-[#ddd] rounded-md text-base cursor-pointer transition-all hover:border-[#aaa] hover:text-[#333] font-[inherit]"
                type="button"
                onClick={() => { setLoading(true); setError(null); setSearch(""); setQuery(""); }}
              >
                Clear
              </button>
            )}
          </form>
        </div>
      </section>

      <section className="max-w-[1200px] mx-auto px-8 pb-16">
        {loading && <p className="text-center text-[#666] text-[1.1rem] py-12">Loading products...</p>}
        {error && <p className="text-center text-[#666] text-[1.1rem] py-12">Unable to load products, please try again later.</p>}
        {!loading && !error && products.length === 0 && (
          <p className="text-center text-[#666] text-[1.1rem] py-12">No products found.</p>
        )}

        {!loading && !error && products.length > 0 && (
          <div className="grid grid-cols-4 gap-7 max-[1024px]:grid-cols-3 max-[480px]:grid-cols-2 max-[360px]:grid-cols-1">
            {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="flex items-center justify-center gap-[0.4rem] py-6 px-4 flex-wrap mt-6">
            <button
              className="border-none rounded-lg px-[0.9rem] py-2 text-[0.9rem] font-semibold cursor-pointer transition-colors bg-[#e8e8e8] text-[#333] hover:bg-[#d0d0d0] disabled:bg-[#f0f0f0] disabled:text-[#aaa] disabled:cursor-not-allowed"
              onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
              disabled={currentPage === 0}
            >
              ← Prev
            </button>
            <span className="text-[0.9rem] text-[#555] font-medium">Page {currentPage + 1} of {totalPages}</span>
            <button
              className="border-none rounded-lg px-[0.9rem] py-2 text-[0.9rem] font-semibold cursor-pointer transition-colors bg-[#e8e8e8] text-[#333] hover:bg-[#d0d0d0] disabled:bg-[#f0f0f0] disabled:text-[#aaa] disabled:cursor-not-allowed"
              onClick={() => setCurrentPage((p) => Math.min(totalPages - 1, p + 1))}
              disabled={currentPage === totalPages - 1}
            >
              Next →
            </button>
          </div>
        )}
      </section>
    </main>
  );
}
