import { MainLayout } from "@/layout/MainLayout/MainLayout";
import { cookies } from "next/headers";
import { db, JamTable, UserTable } from "@/lib/mastoauth/kysely";
import { ConditionalNull } from "@/components/utility/Conditional";
import Link from "next/link";
import Markdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import { JSONJamTable, JSONUserTable } from "@/lib/mastoauth/realtypes";

export default async function Home({
  searchParams
}: {
  searchParams: { 
    until: string
  }
}) {
  const curDate = Date.now();
  const curPage = parseInt(searchParams?.until) || curDate;

  const cookieStore = cookies();
  const token = cookieStore.get('token')?.value;
  let existingUser: JSONUserTable | undefined;
  if (token != null) {
    let existingToken = await db
      .selectFrom('tokens')
      .where('tokens.id', '=', token)
      .select('owner')
      .executeTakeFirst();

    if (existingToken != null) {
      existingUser = await db
        .selectFrom('users')
        .where('users.id', '=', existingToken.owner)
        .selectAll()
        .executeTakeFirst() as unknown as JSONUserTable;
    }
  }
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let jams = await db
    .selectFrom('jams')
    .where('jams.created', '<=', curPage)
    .limit(20)
    .orderBy('jams.created', 'desc')
    .selectAll()
    .execute() as unknown[] as JSONJamTable[];

  jams.forEach((jam) => {
    const started = Date.now() >= parseInt(jam.date_start);
    if (!started && !existingUser?.admin && jam.author_id != existingUser?.id) {
      jam.theme = "";
      jam.theme_description = "";
    }
  })

  return (
    <MainLayout currentPage="/jams/" title="Jams" subtitle="">
      <img className="headerImage" src="/headers/jams.png" alt="JAMS"></img>
      <p>Some jams I host that you can participate in!</p>
      <p>These serve many purposes. To create a community bond, to help creatives find their way, and most importantly, <s>to make me popular</s>. X3</p>
      <p>Enjoy!</p>
      <ConditionalNull condition={existingUser == null}>
        <h2>Join abtmtr.link Jams</h2>
        <p>If you'd like to participate in any jam, you should join!</p>
        <p><small>To join with the Fediverse, enter your instance domain.<br />
        To join with GitHub, enter "github.com".<br />
        To join with Discord, enter "discord.com".</small></p>
        <form action="/jams/oauth/login">
          <input name="instance" placeholder="Domain (e.g. &quot;social.besties.house&quot; or &quot;woem.men&quot;)" type="text" />
          <input type="submit" />
        </form>
        <p><small>Tested on Discord, GitHub, Mastodon, GoToSocial, and Akkoma</small></p>
      </ConditionalNull>
      <ConditionalNull condition={existingUser != null}>
        <p>Logged in as <a href={`/jams/user/${existingUser?.id}`}>{existingUser?.username}@{existingUser?.instance}</a> (<a href="/jams/oauth/logout">Logout</a>)</p>
        <ConditionalNull condition={existingUser?.admin == true}><p><a href="/jams/new/jam">Create Jam</a></p></ConditionalNull>
        <ConditionalNull condition={existingUser?.admin == true}><p><a href="/jams/admin">Admin panel</a></p></ConditionalNull>
      </ConditionalNull>
      <h1>Jams</h1>
      {jams.map(async (jam:JSONJamTable) => {
        const started = Date.now() >= parseInt(jam.date_start);
        const ended = Date.now() >= parseInt(jam.date_end);
        
        let jamOwner = await db
          .selectFrom('users')
          .where('users.id', '=', jam.author_id)
          .selectAll()
          .executeTakeFirst();
        
        if (jamOwner == null) return <p>An error occured.</p>;

        return (<div style={{
          margin: "16px 0"
        }}>
          <h2><Link href={`/jams/jam/${jam.id}`}>{jam.name}</Link></h2>
          <p><small>Hosted by <a href={`/jams/user/${jamOwner.id}`}>{`${jamOwner.username}@${jamOwner.instance}`}</a> - {started ? "Started" : "Starts"} {new Date(parseInt(jam.date_start)).toDateString()} - {ended ? "Ended" : "Ends"} {new Date(parseInt(jam.date_end)).toDateString()}</small></p>
          <Markdown rehypePlugins={[rehypeRaw]}>{jam.description}</Markdown>
        </div>);
      })}
      <div className="navigation">
        <ConditionalNull condition={curPage < curDate}>
          <Link href={`?`}>Later</Link>
        </ConditionalNull>
        <ConditionalNull condition={jams.length > 20}>
          <Link href={`?until=${parseInt(jams.at(-1)?.created || curPage + "") - 1}`}>Earlier</Link>
        </ConditionalNull>
      </div>
    </MainLayout>
  )
}