import { ConditionalNull } from "@/components/utility/Conditional";
import { MainLayout } from "@/layout/MainLayout/MainLayout";
import Link from "next/link";
import Markdown from "react-markdown";
import rehypeRaw from "rehype-raw";

export default async function Home({
  searchParams
}: {
  searchParams: { 
    page: string
  }
}) {
  const curPage = parseInt(searchParams?.page) || 1;
  const blogs = await fetch(`https://blog.abtmtr.link/api/collections/stories/posts?page=${curPage}`, { next: { revalidate: 3600 } }).then(x=>x.json());
  return (
    <MainLayout currentPage="/stories/" title="Stories" subtitle="via blog.abtmtr.link">
      <img className="headerImage" src="/headers/stories.png" alt="STORIES"></img>
      {blogs.data.posts.map((post:{
        title: string,
        body: string,
        created: string,
        updated: string,
        tags: string[],
        views: number,
        slug: string
      }) => (
        <div style={{
          margin: "16px 0"
        }}>
          <h2><Link href={`/stories/${post.slug}`}>{post.title}</Link></h2>
          <p><small>Posted {new Date(post.created).toLocaleDateString()} - {post.views} views</small></p>
          <Markdown 
            rehypePlugins={[rehypeRaw]} 
            allowedElements={[]} 
            unwrapDisallowed={true}
          >
            {post.body.split("\n").slice(0, 2).join("\n")}
          </Markdown>
        </div>
      ))}
      <div className="navigation">
        <ConditionalNull condition={curPage > 1}>
          <Link href={`?page=${curPage - 1}`}>Previous</Link>
        </ConditionalNull>
        <ConditionalNull condition={curPage * 10 < blogs.data.total_posts}>
          <Link href={`?page=${curPage + 1}`}>Next</Link>
        </ConditionalNull>
      </div>
    </MainLayout>
  )
}
