import { MainLayout } from "@/layout/MainLayout/MainLayout";
import { notFound } from "next/navigation";
import Markdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import styles from "../style.module.css";
import Link from "next/link";
import { ConditionalNull } from "@/components/utility/Conditional";

export default async function Home({
  params
}:{
  params: {
    slug: string
  }
}) {
  const blog = await fetch(`https://blog.abtmtr.link/api/collections/gallery/posts/${params.slug}`, { cache: 'no-store' }).then(x=>x.json());
  if (blog.data == null)
    return notFound();

  let allCharacters:{
    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,
    }[]
  }[] = [];

  await (blog.data.tags.reduce(async (p:Promise<any>, tag:string) => {
    const tagCharacter = await fetch(`https://blog.abtmtr.link/api/collections/characters/posts/${tag}`, { next: { revalidate: 1800 } }).then(x=>x.json());
    if (tagCharacter.data == null) return;

    allCharacters.push(JSON.parse(tagCharacter.data.body.replace(/[“”]/g, "\"")));
  }, Promise.resolve()));

  return (
    <MainLayout currentPage={`/gallery/${params.slug}`} title="Gallery" subtitle="via img.abtmtr.link" backButton>
      <h1>{blog.data.title}</h1>
      <p><small>Posted {new Date(blog.data.created).toLocaleString()} - {blog.data.views} views</small></p>
      <div style={{
          margin: "16px 0"
        }}>
        <Markdown rehypePlugins={[rehypeRaw]}>{blog.data.body}</Markdown>
      </div>
      <ConditionalNull condition={allCharacters.length >= 1}><h2>Characters</h2></ConditionalNull>
      <div className={styles.ImageContainerGrid}>
        {allCharacters.map(async (character) => {
          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.ImageContainerLink}>
              <div style={{
                backgroundImage: `linear-gradient(0deg, #000c 0%, #000c 50%, #0004 100%), url(${charblogs.data.images[0]})`,
              }} className={styles.ImageContainer}>
                <h2>{character.name}</h2>
                <p>{character.pronouns}</p>
              </div>
            </Link>
          );
        })}
      </div>
    </MainLayout>
  )
}
