// "use client";
// import { usePathname, useRouter, useSearchParams } from "next/navigation";
// import { useDebouncedCallback } from "use-debounce";


// export function Search() {
//   const searchParams = useSearchParams();
//   const { replace } = useRouter();
//   const pathname = usePathname();

//   const handleSearch = useDebouncedCallback((term: string) => {
//     console.log(`Searching... ${term}`);
//     const params = new URLSearchParams(searchParams);
//     params.set("page", "1");

//     if (term) {
//       params.set("query", term);
//     } else {
//       params.delete("query");
//     }

//     replace(`search?${params.toString()}`);
//   }, 300);

//   return (
//     <div>
//       <input
//         type="text"
//         placeholder="Search"
//         className="w-full border-b border-white bg-transparent py-1 outline-none ltr:pl-2 ltr:pr-8 rtl:pr-2 rtl:pl-8"
//         onChange={(e) => handleSearch(e.target.value)}
//         defaultValue={searchParams.get("query")?.toString()}
//       />

//     </div>
//   );
// }



import Head from "next/head"
import Image from "next/image"
import Link from "next/link"
import { formatDate } from "../../utils"
import { DrupalNode } from "next-drupal"
import React from "react"

export default function Search() {
    const [status, setStatus] = React.useState<"error" | "success" | "loading">()
    const [results, setResults] = React.useState<DrupalNode[]>([])
  
    async function handleSubmit(event: { preventDefault: () => void; target: { keywords: { value: any } } }) {
      event.preventDefault()
  
      setStatus("loading")
  
      const response = await fetch("/api/search/default_index", {
        method: "POST",
        body: JSON.stringify({
          params: {
            fields: {
              "node--article": "id,title,created,field_image",
            },
            include: "field_image",
            filter: {
              fulltext: event.target.keywords.value,
            },
          },
        }),
      })
  
      if (!response.ok) {
        return setStatus("error")
      }
  
      setStatus("success")
  
      const results = await response.json()
  
      setResults(results)
    }
  
    return (
      <>
        <Head>
          <title>Next.js for Drupal | Search API Example</title>
        </Head>
        <div className="container max-w-2xl px-6 py-10 mx-auto">
          <article className="prose lg:prose-xl">
            <h1>Next.js for Drupal</h1>
            <h2>Search API Example - Simple</h2>
            <p>
              A simple full text search implemented using Search API and JSON:API
              Search API.
            </p>
            <p>Use the form below to search for article nodes.</p>
   
            {status === "error" ? (
              <div className="px-4 py-2 text-sm text-red-600 bg-red-100 border-red-200 rounded-md">
                An error occured. Please try again.
              </div>
            ) : null}
            {!results.length ? (
              <p className="text-sm" data-cy="search-no-results">
                No results found. Try searching for <strong>static</strong> or{" "}
                <strong>preview</strong>.
              </p>
            ) : (
              <div className="pt-4">
                <h3 className="mt-0" data-cy="search-results">
                  Found {results.length} result(s).
                </h3>
                {results.map((node) => (
                  <div key={node.id} className="pb-4 mb-4 border-b">
                    <article
                      className="grid-cols-3 gap-4 sm:grid"
                      data-cy="search-result"
                    >
                      {node.field_image?.uri && (
                        <div className="col-span-1 mb-4 sm:mb-0">
                          {/* <Image
                            src={`${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}${node.field_image.uri.url}`}
                            width={200}
                            height={110}
                            layout="responsive"
                            objectFit="cover"
                          /> */}
                        </div>
                      )}
                      <div className="col-span-2 not-prose">
                        <h4 className="font-semibold text-black leading-normal">
                          {node.title}
                        </h4>
                        <p className="mb-0">
                          <small>{formatDate(node.created)}</small>
                        </p>
                      </div>
                    </article>
                  </div>
                ))}
              </div>
            )}
            <p>
              <Link href="/" passHref>
               Go back
              </Link>
            </p>
          </article>
        </div>
      </>
    )
  }
  




