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

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

  if (charblogs.data == null) return notFound();

  const 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,
    }[]
  } = JSON.parse(charblogs.data.body.replace(/[“”]/g, "\""));
  const images = await fetch(`https://blog.abtmtr.link/api/collections/gallery/posts/${character.picture}`, { next: { revalidate: 3600 } }).then(x=>x.json());

  let allPosts = [];
  let currentPage = 1;

  const initReq = await fetch(`https://blog.abtmtr.link/api/collections/gallery/posts`, { next: { revalidate: 3600 } }).then(x=>x.json());
  const totalPosts:number = initReq.data.total_posts;

  while (currentPage * 10 < totalPosts) {
    const newPostList = await fetch(`https://blog.abtmtr.link/api/collections/gallery/posts?page=${currentPage}`, { next: { revalidate: 3600 } }).then(x=>x.json());
    allPosts.push(...newPostList.data.posts);

    currentPage++;
  }

  const myPosts = allPosts.filter(post => post.tags?.includes(character.id));

  return (
    <MainLayout currentPage="/characters/" title="Characters" backButton>
      <div style={{display:"block",marginBottom:16,overflow:"auto"}}>
        <img style={{float:"right",width:"60%", marginLeft:16, marginTop:16}} src={images.data.images[0]}></img>
        <h1 style={{marginBottom: 0}}>{character.name}</h1>
        <small>{character.pronunciation}</small>
        <ConditionalNull condition={character.spec != null}>
          <p>Spec: <Link href={`https://spec.abtmtr.link/#${character.spec}`} target="_blank">#{character.spec}</Link></p>
        </ConditionalNull>
        <p>{character.pronouns}, {character.age}</p>
        <p>{character.species}, {character.gender}, {HeightConverter(character.height)}</p>
        <ConditionalNull condition={character.description != null}>
          <Markdown rehypePlugins={[rehypeRaw]}>{`*${character.description?.join("\n")}*`}</Markdown>
        </ConditionalNull>
      </div>
      <h2>Gallery</h2>
      <div className={styles.CharacterContainerGrid}>
        {myPosts.map(async (img:{
          slug: string,
          title: string,
          created: string,
          images: string[]
        }) => {
          return (
            <Link href={`/gallery/${img.slug}`} className={styles.CharacterContainerLink}>
              <div style={{
                backgroundImage: `linear-gradient(0deg, #000c 0%, #000c 50%, #0004 100%), url(${img.images[0]})`,
              }} className={styles.CharacterContainer}>
                <h2>{img.title}</h2>
                <p>{new Date(img.created).toLocaleDateString()}</p>
              </div>
            </Link>
          );
        })}
      </div>
    </MainLayout>
  )
}