import BookPoster from "@/components/BookPoster";
import db from "./../../../../db";
import { SimilarBook } from "./../../../../types";

// Refresh cache every 24 hours
export const revalidate = 60 * 60 * 24;

async function SearchTerm({
  params: { term },
}: {
  params: {
    term: string;
  };
}) {
  const books = db.collection("books");

  let similarBooks: SimilarBook[];
  try {
    // Query the database for similar books
    similarBooks = (await books
      .find(
        {},
        {
          vectorize: term,
          limit: 12, // Fetch more results than needed to handle duplicates
          includeSimilarity: true,
        }
      )
      .toArray()) as SimilarBook[];
  } catch (error) {
    console.error("Error fetching similar books: ", error);
    return (
      <div className="flex flex-col items-center justify-center p-20">
        <h1 className="text-xl text-red-500">
          An error occurred while fetching data. Please try again later.
        </h1>
      </div>
    );
  }

  // Deduplicate the results
  const seenIds = new Set();
  const deduplicatedBooks = similarBooks.filter((book) => {
    if (seenIds.has(book.$similarity)) {
      return false; // Skip duplicate
    }
    seenIds.add(book.$similarity);
    return true; // Keep unique book
  });

  // Handle case where no books are found
  if (deduplicatedBooks.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center p-20">
        <h1 className="text-xl text-gray-100">
          No results found for your search.
        </h1>
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center justify-center p-20 pt-10">
      <h1 className="mb-10 text-xl text-gray-100">
        Suggested results based on your search
      </h1>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-10">
        {deduplicatedBooks.map((book, i) => (
          <div key={i} className="flex space-x-2 relative">
            <p className="absolute flex items-center justify-center left-4 top-2 text-white font-extrabold text-xl z-40 rounded-full bg-indigo-500/80 w-10 h-10">
              {i + 1}
            </p>

            <BookPoster key={book._id} book={book} />
          </div>
        ))}
      </div>
    </div>
  );
}

export default SearchTerm;
