import Container from "@/components/elements/Container";
import { cookies } from "next/headers";
import SearchFilter from "@/components/search/SearchFilter";
import { fetchSearch } from "@/api/fetchSearch";
import InfiniteSearch from "@/components/search/InfiniteSearch";
import { Metadata } from "next";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import {
  getListSeoTemplates,
  getSeoPage,
  interpolateTemplate,
} from "@/lib/i18n/seo";
import { generateSeoPageMetadata, getServerLanguage } from "@/lib/i18n/server";

interface ISearchProps {
  searchParams: Promise<{
    search?: string;
    type?: string;
  }>;
}

export async function generateMetadata({ searchParams }: ISearchProps): Promise<Metadata> {
  const lang = await getServerLanguage();
  const { search } = await searchParams;

  if (!search) {
    return generateSeoPageMetadata("search", { lang });
  }

  const templates = getListSeoTemplates(lang).search as Record<string, string>;
  const searchPage = getSeoPage("search", lang);

  return generatePageMetadata({
    title: interpolateTemplate(templates.resultsTitle, { query: search }),
    description: interpolateTemplate(templates.resultsDescription, {
      query: search,
    }),
    path: `${searchPage.path}?search=${encodeURIComponent(search)}`,
    keywords: searchPage.keywords,
    lang,
  });
}

export default async function Search({ searchParams }: ISearchProps) {
  const token = (await cookies()).get("token")?.value || "";
  const filters = await searchParams;

  const initialData =
    filters.search && filters.type
      ? await fetchSearch(1, 10, filters, token)
      : null;

  return (
    <Container className="pb-28">
      <SearchFilter />
      <InfiniteSearch token={token} initialData={initialData} filters={filters} />
    </Container>
  );
}
