import type { Metadata } from "next";
import { Suspense } from "react";

import { BrowseFilters } from "@/components/browse/browse-filters";
import { BrowseShell } from "@/components/browse/browse-shell";
import { GridSkeleton, PosterGrid } from "@/components/browse/poster-grid";
import { Pagination } from "@/components/browse/pagination";
import {
  TV_SORT_OPTIONS,
  loadCatalogue,
  loadGenreOptions,
  queryWithoutPage,
} from "@/lib/catalogue";

export const metadata: Metadata = {
  title: "TV Shows",
  description:
    "Stream series and binge-worthy shows. Filter by genre, year and rating across the whole FlixTV catalogue.",
  alternates: { canonical: "/tv" },
};

export default async function TvPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;

  return (
    <BrowseShell
      title="TV Shows"
      description="Series worth committing to — from a single episode to the whole season."
      hero
    >
      <Suspense fallback={<GridSkeleton />}>
        <TvCatalogue params={params} />
      </Suspense>
    </BrowseShell>
  );
}

async function TvCatalogue({
  params,
}: {
  params: Record<string, string | string[] | undefined>;
}) {
  const [{ result }, genres] = await Promise.all([
    loadCatalogue("tv", params),
    loadGenreOptions("tv"),
  ]);

  return (
    <>
      <BrowseFilters
        genres={genres}
        sortOptions={TV_SORT_OPTIONS}
        resultCount={result.totalResults}
      />
      <PosterGrid
        items={result.items}
        priorityCount={8}
        emptyMessage="No shows match these filters."
      />
      <Pagination
        page={result.page}
        totalPages={result.totalPages}
        basePath="/tv"
        query={queryWithoutPage(params)}
      />
    </>
  );
}
