// @ts-nocheck

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

export default async function Home({
  params,
  searchParams
}: {
  params: {
    content: 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:JSONUserTable;
  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;
    }
  }

  const curContent = params.content;

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

    console.log(curContent, content)

  if (content == null) return notFound();
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let contentOwner = await db
    .selectFrom('users')
    .where('users.id', '=', content.author_id)
    .selectAll()
    .executeTakeFirst() as unknown as JSONUserTable;
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let submittedJam = await db
    .selectFrom('jams')
    .where('jams.id', '=', content.jam_id)
    .selectAll()
    .executeTakeFirst() as unknown as JSONJamTable;
  
  let judgements = await db
    .selectFrom('judgements')
    .where('judgements.content_id', '=', content.id)
    .where('judgements.published', '<=', curPage)
    .limit(20)
    .orderBy('judgements.published', 'desc')
    .selectAll()
    .execute() as unknown[] as JSONJudgementTable[];
    
  let allAdmins = await db
    .selectFrom('users')
    .where('users.admin', '=', true)
    .selectAll()
    .execute();

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

  let adminsWhoSaid = judgementWinners?.map((judgement:JSONJudgementTable) => 
    allAdmins.find(x => x.id == judgement.author_id)
  );

  return (
    <MainLayout currentPage="/jams/" title={content.name} subtitle="Jams" backButton>
      <h1>{content.name}</h1>
      <p><a href={content.url} target="_blank">{content.url}</a></p>
      <ConditionalNull condition={submittedJam != null}> 
      <p><small>Submitted by <a href={`/jams/user/${contentOwner.id}`}>{`${contentOwner.username}@${contentOwner.instance}`}</a> to <a href={`/jams/jam/${submittedJam?.id}?until=${content.submitted}`}>{submittedJam?.name}</a> - {new Date(parseInt(content.submitted)).toDateString()}</small></p>
      </ConditionalNull>
      <ConditionalNull condition={submittedJam == null}>
      <p><small>Submitted by <a href={`/jams/user/${contentOwner.id}`}>{`${contentOwner.username}@${contentOwner.instance}`}</a> {new Date(parseInt(content.submitted)).toDateString()}</small></p>
      </ConditionalNull>
      <ConditionalNull condition={content.winner && submittedJam != null}>
      <p><small><b>WINNER!</b></small></p>
      </ConditionalNull>
      <p>{content.description}</p>
      <ConditionalNull condition={existingUser != null}>
        <div>
          <ConditionalNull condition={existingUser?.admin || content.author_id == existingUser?.id}><p><b>You have the ability to modify this submission.</b></p></ConditionalNull>
          <ConditionalNull condition={existingUser?.admin || content.author_id == existingUser?.id}><p><a href={`/jams/edit/content/${content.id}`}>Edit submission</a></p></ConditionalNull>
          <ConditionalNull condition={existingUser?.admin || content.author_id == existingUser?.id}><p><a href={`/jams/delete/content/${content.id}`}>Delete submission</a></p></ConditionalNull>
          <p><a href={`/jams/new/judgement/${content.id}`}>Judge this submission</a></p>
        </div>
      </ConditionalNull>
      <ConditionalNull condition={judgementWinners.length > 0}>
        <h1>Admin Judgements</h1>
        {judgementWinners.map(async (judgement:JSONJudgementTable, index:number) => {
          const judgementOwner = adminsWhoSaid[index];

          return (<div style={{
            margin: "16px 0"
          }}>
            <h2><a href={`/jams/user/${judgementOwner.id}`}>{`${judgementOwner.username}@${judgementOwner.instance}`}</a></h2>
            <ConditionalNull condition={existingUser != null}>
              <div>
                <ConditionalNull condition={existingUser?.admin || judgementOwner.id == existingUser?.id}><p><a href={`/jams/edit/judgement/${judgement.id}`}>Edit judgement</a> - <a href={`/jams/delete/judgement/${judgement.id}`}>Delete judgement</a></p></ConditionalNull>
              </div>
            </ConditionalNull>
            <p><small>Published {new Date(parseInt(judgement.published)).toDateString()}</small></p>
            <p>{judgement.content}</p>
          </div>);
        })}
      </ConditionalNull>
      <h1>Judgements</h1>
      {judgements.map(async (judgement:JSONJudgementTable) => {
        let judgementOwner = await db
          .selectFrom('users')
          .where('users.id', '=', judgement.author_id)
          .selectAll()
          .executeTakeFirst();
        
        if (judgementOwner == null) return <p>An error occured.</p>;

        return (<div style={{
          margin: "16px 0"
        }}>
          <h2><a href={`/jams/user/${judgementOwner.id}`}>{`${judgementOwner.username}@${judgementOwner.instance}`}</a></h2>
          <ConditionalNull condition={existingUser != null}>
            <div>
              <ConditionalNull condition={existingUser?.admin || judgementOwner.id == existingUser?.id}><p><a href={`/jams/edit/judgement/${judgement.id}`}>Edit judgement</a> - <a href={`/jams/delete/judgement/${judgement.id}`}>Delete judgement</a></p></ConditionalNull>
            </div>
          </ConditionalNull>
          <p><small>Published {new Date(parseInt(judgement.published)).toDateString()}</small></p>
          <p>{judgement.content}</p>
        </div>);
      })}
      <div className="navigation">
        <ConditionalNull condition={curPage < curDate}>
          <Link href={`?`}>Later</Link>
        </ConditionalNull>
        <ConditionalNull condition={judgements.length > 20}>
          <Link href={`?until=${parseInt(judgements.at(-1)?.published || curPage + "") - 1}`}>Earlier</Link>
        </ConditionalNull>
      </div>
    </MainLayout>
  )
}