import { Handlers, PageProps } from "$fresh/server.ts";
import { MainLayout } from "@components/layouts/main.tsx";
import { Grid } from "@components/Grid.tsx";
import { IconArrowLeft } from "@components/icons.tsx";
import { RedirectSearchHandler } from "@islands/Search.tsx";
import { KMenu } from "@islands/KMenu.tsx";
import { ResourceCard } from "@components/Card.tsx";
import { listResources } from "@lib/marka/index.ts";
import { parseResourceUrl, searchResource } from "@lib/search.ts";
import { GenericResource, ReviewResource } from "@lib/marka/schema.ts";

export const handler: Handlers<
  { series: ReviewResource[] | null; searchResults?: GenericResource[] }
> = {
  async GET(req, ctx) {
    const series = await listResources<ReviewResource>("series");
    const searchParams = parseResourceUrl(req.url);
    const searchResults = searchParams &&
      await searchResource({ ...searchParams, types: ["series"] });
    return ctx.render({ series, searchResults });
  },
};

export default function Greet(
  props: PageProps<
    { series: ReviewResource[] | null; searchResults: GenericResource[] }
  >,
) {
  const { series, searchResults } = props.data;

  return (
    <MainLayout
      url={props.url}
      title="Series"
      context={{ type: "series" }}
      searchResults={searchResults}
    >
      <RedirectSearchHandler />
      <KMenu type="main" context={{ type: "series" }} />
      <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="/"
        >
          <IconArrowLeft class="w-5 h-5" />
          Back
        </a>

        <h3 class="text-2xl text-white font-light">🎥 Series</h3>
      </header>
      <Grid>
        {series?.map((doc, i) => {
          return <ResourceCard key={i} sublink="series" res={doc} />;
        })}
      </Grid>
    </MainLayout>
  );
}
