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 { JSONContentTable, JSONJamTable, JSONUserTable } from "@/lib/mastoauth/realtypes";
import { notFound } from "next/navigation";

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

  const cookieStore = cookies();
  const token = cookieStore.get('token')?.value;
  let existingUser;
  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();
    }
  }

  const curJam = params.jam;

  if (curJam == null) return notFound();
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let jam = await db
    .selectFrom('jams')
    .where('jams.id', '=', curJam)
    .selectAll()
    .executeTakeFirst() as unknown as JSONJamTable;

    if (jam == null) return notFound();
  
  const started = Date.now() >= parseInt(jam.date_start);
  const ended = Date.now() >= parseInt(jam.date_end);
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let jamOwner = await db
    .selectFrom('users')
    .where('users.id', '=', jam.author_id)
    .selectAll()
    .executeTakeFirst() as unknown as JSONUserTable;

  if (!started && !existingUser?.admin && jam.author_id != existingUser?.id) {
    jam.theme = "";
    jam.theme_description = "";
  }
  
  let contentWinners = await db
    .selectFrom('content')
    .where('content.jam_id', '=', jam.id)
    .where('content.winner', '=', true)
    .orderBy('content.submitted', 'desc')
    .selectAll()
    .execute() as unknown[] as JSONContentTable[];
  
  let content = await db
    .selectFrom('content')
    .where('content.jam_id', '=', jam.id)
    .where('content.submitted', '<=', curPage)
    .limit(20)
    .orderBy('content.submitted', 'desc')
    .selectAll()
    .execute() as unknown[] as JSONContentTable[];

  console.log(jam, jamOwner)

  return (
    <MainLayout currentPage="/jams/" title={jam.name} subtitle="Jams" backButton>
      <h1>{jam.name}</h1>
      <p><small>{started ? "Started" : "Starts"} {new Date(parseInt(jam.date_start)).toDateString()} - {ended ? "Ended" : "Ends"} {new Date(parseInt(jam.date_end)).toDateString()}</small></p>
      <p>Hosted by <a href={`/jams/user/${jamOwner.id}`}>{`${jamOwner.username}@${jamOwner.instance}`}</a></p>
      <p>{jam.description}</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}>
        <div>
          <ConditionalNull condition={existingUser?.admin || jam.author_id == jam.id}><p><b>You have the ability to modify this Jam.</b></p></ConditionalNull>
          <ConditionalNull condition={existingUser?.admin || jam.author_id == jam.id}><p><a href={`/jams/edit/jam/${jam.id}`}>Edit jam</a></p></ConditionalNull>
          <ConditionalNull condition={existingUser?.admin || jam.author_id == jam.id}><p><a href={`/jams/delete/jam/${jam.id}`}>Delete jam</a></p></ConditionalNull>
        </div>
      </ConditionalNull>
      <br />
      <div style={{textAlign: 'center'}}>
        <p>The theme is:</p>
        <h1>{jam.theme || "To be announced"}</h1>
        <p>{jam.theme_description || "Something exciting, maybe?"}</p>
        <ConditionalNull condition={existingUser != null && started && !ended}><p><a href={`/jams/new/content/${jam.id}`}>Submit something</a></p></ConditionalNull>
      </div>
      <br />
      <ConditionalNull condition={contentWinners.length > 0}>
        <h1>Winners</h1>
        {contentWinners.map(async (content:JSONContentTable) => {
          let contentOwner = await db
            .selectFrom('users')
            .where('users.id', '=', content.author_id)
            .selectAll()
            .executeTakeFirst();
          
          if (contentOwner == null) return <p>An error occured.</p>;

          let allAdmins = await db
            .selectFrom('users')
            .where('users.admin', '=', true)
            .selectAll()
            .execute();

          let judgementWinner = await db
            .selectFrom('judgements')
            .where('judgements.author_id', 'in', allAdmins.map(x=>x.id))
            .where('judgements.content_id', '=', content.id)
            .selectAll()
            .executeTakeFirst();

          let adminWhoSaid = allAdmins.find(x=> judgementWinner?.author_id == x.id);

          return (<div style={{
            margin: "16px 0"
          }}>
            <h2><Link href={`/jams/content/${content.id}`}>{content.name}</Link></h2>
            <p><small>by <a href={`/jams/user/${contentOwner.id}`}>{`${contentOwner.username}@${contentOwner.instance}`}</a></small></p>
            <ConditionalNull condition={judgementWinner != null && adminWhoSaid != null}>
              <p><b>ADMIN</b> <a href={`/jams/user/${adminWhoSaid?.id}`}>{adminWhoSaid?.username}@{adminWhoSaid?.instance}</a> - <i>"{judgementWinner?.content}"</i></p>
            </ConditionalNull>
            <p></p>
          </div>);
        })}
      </ConditionalNull>
      <ConditionalNull condition={started || content.length > 0}>
      <h1>Submissions</h1>
      {content.map(async (content:JSONContentTable) => {
        let contentOwner = await db
          .selectFrom('users')
          .where('users.id', '=', content.author_id)
          .selectAll()
          .executeTakeFirst();
        
        if (contentOwner == null) return <p>An error occured.</p>;

        return (<div style={{
          margin: "16px 0"
        }}>
          <h2><Link href={`/jams/content/${content.id}`}>{content.name}</Link></h2>
          <p><small>Submitted by <a href={`/jams/user/${contentOwner.id}`}>{`${contentOwner.username}@${contentOwner.instance}`}</a> - {new Date(parseInt(content.submitted)).toDateString()}</small></p>
          <p>{content.description}</p>
        </div>);
      })}
      </ConditionalNull>
      <div className="navigation">
        <ConditionalNull condition={curPage < curDate}>
          <Link href={`?`}>Later</Link>
        </ConditionalNull>
        <ConditionalNull condition={content.length > 20}>
          <Link href={`?until=${parseInt(content.at(-1)?.submitted || curPage + "") - 1}`}>Earlier</Link>
        </ConditionalNull>
      </div>
    </MainLayout>
  )
}