import { MainLayout } from "@components/layouts/main.tsx";
import { GenericResource, ReviewResource } from "@lib/marka/schema.ts";
import { ResourceCard } from "@components/Card.tsx";
import { Grid } from "@components/Grid.tsx";
import { KMenu } from "@islands/KMenu.tsx";
import { RedirectSearchHandler } from "@islands/Search.tsx";
import { PageProps } from "fresh";
import { listResources } from "@lib/marka/index.ts";
import { parseResourceUrl, searchResource } from "@lib/search.ts";
import { parseRating } from "@lib/helpers.ts";
import { TbArrowLeft } from "@preact-icons/tb";

function sortOptional(a: number | string = 0, b: number | string = 0) {
  return (parseRating(a) > parseRating(b)) ? 1 : -1;
}

export default async function MovieIndex(
  props: PageProps<
    { movies: ReviewResource[] | null; searchResults: GenericResource[] }
  >,
) {
  const allMovies = await listResources<ReviewResource>("movies");
  const searchParams = parseResourceUrl(props.url);
  const searchResults = searchParams &&
    await searchResource({ ...searchParams, types: ["movies"] });
  const movies = allMovies.sort((a, b) =>
    sortOptional(
      a.content.reviewRating?.ratingValue,
      b.content.reviewRating?.ratingValue,
    )
  );

  return (
    <MainLayout
      url={props.url}
      title="Movies"
      context={{ type: "movies" }}
      searchResults={searchResults}
    >
      <RedirectSearchHandler />
      <KMenu type="main" context={{ type: "movies" }} />
      <header class="flex gap-4 items-center mb-5 md:hidden">
        <a
          class="px-4 ml-4 py-2 bg-gray-300 text-gray-800 rounded-lg flex items-center gap-1"
          href="/"
        >
          {TbArrowLeft({ class: "w-5 h-5" })}
          Back
        </a>

        <h3 class="text-2xl text-white font-light">🍿 Movies</h3>
      </header>
      <Grid>
        {movies?.map((doc, i) => {
          return <ResourceCard key={doc.name || i} res={doc} />;
        })}
      </Grid>
    </MainLayout>
  );
}
