import { MainLayout } from "@/layout/MainLayout/MainLayout";
import styles from "./style.module.css";
import Link from "next/link";
import { ConditionalNull } from "@/components/utility/Conditional";

export default async function Home({
  searchParams
}: {
  searchParams: { 
    page: string
  }
}) {
  const curPage = parseInt(searchParams?.page) || 1;

  const charblogs = await fetch(`https://blog.abtmtr.link/api/collections/characters/posts?page=${curPage}`, { next: { revalidate: 1800 } }).then(x=>x.json());
  const characters = charblogs.data.posts.map((post:{body:string}) => JSON.parse(post.body.replace(/[“”]/g, "\"")));

  return (
    <MainLayout currentPage="/characters/" title="Characters" subtitle="">
      <img className="headerImage" src="/headers/characters.png" alt="CHARACTERS"></img>
      <div className={styles.CharacterContainerGrid}>
        {characters.map(async (character:{
          id: string,
          name: string,
          description?: string[],
          picture: string,
          gender: string,
          pronunciation: string,
          pronouns: string,
          spec?: string,
          species: string,
          age: number,
          height: number,
          relationships: {
            id: string,
            status: string,
          }[]
        }) => {
          const charblogs = await fetch(`https://blog.abtmtr.link/api/collections/gallery/posts/${character.picture}`).then(x=>x.json());
          console.log(charblogs?.data?.images?.[0]);
          return (
            <Link href={`/characters/${character.id}`} className={styles.CharacterContainerLink}>
              <div style={{
                backgroundImage: `linear-gradient(0deg, #000c 0%, #000c 50%, #0004 100%), url(${charblogs.data.images[0]})`,
              }} className={styles.CharacterContainer}>
                <h2>{character.name}</h2>
                <p>{character.pronouns}</p>
              </div>
            </Link>
          );
        })}
      </div>
      <div className="navigation">
        <ConditionalNull condition={curPage > 1}>
          <Link href={`?page=${curPage - 1}`}>Previous</Link>
        </ConditionalNull>
        <ConditionalNull condition={curPage * 10 < charblogs.data.total_posts}>
          <Link href={`?page=${curPage + 1}`}>Next</Link>
        </ConditionalNull>
      </div>
    </MainLayout>
  )
}