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

export const handler = define.handlers({
  async GET(ctx) {
    const req = ctx.req;
    const articles = await listResources<ArticleResource>("articles");
    const searchParams = parseResourceUrl(req.url);
    const searchResults = searchParams &&
      await searchResource({ ...searchParams, types: ["articles"] });
    return { data: { articles, searchResults } };
  },
});

export default define.page(function Greet(
  props: PageProps<
    { articles: ArticleResource[] | null; searchResults: GenericResource[] }
  >,
) {
  const { articles, searchResults } = props.data;
  return (
    <MainLayout
      url={props.url}
      title="Articles"
      context={{ type: "articles" }}
      searchResults={searchResults}
    >
      <header class="flex gap-4 items-center mb-5 md:hidden">
        <Link
          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
        </Link>

        <h3 class="text-2xl text-white font-light">📝 Articles</h3>
      </header>
      <RedirectSearchHandler />
      <KMenu type="main" context={{ type: "articles" }} />
      <Grid>
        {articles?.map((doc, i) => (
          <ResourceCard
            key={doc.name || i}
            sublink="articles"
            res={doc}
          />
        ))}
      </Grid>
    </MainLayout>
  );
});
