
import { Conditional, ConditionalNull } from "@/components/utility/Conditional";
import { MainLayout } from "@/layout/MainLayout/MainLayout";
import { db } from "@/lib/mastoauth/kysely";
import { JSONJamTable } from "@/lib/mastoauth/realtypes";
import { cookies } from "next/headers";
import { notFound, redirect } from "next/navigation";
import { Form } from "./components/form";

export default async function Home({
  params
}: {
  params: {
    jamid: string
  }
}) {
  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();
    }
  }

  if (existingUser == null) return redirect("/jams/");

  const jamid = params.jamid;

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

  if (parentJam == null) return notFound();
  
  const started = Date.now() >= parseInt(parentJam.date_start);
  const ended = Date.now() >= parseInt(parentJam.date_end);

  if (!started || ended) return (
    <MainLayout currentPage="/jams/" title="New Submission" subtitle="Jams" backButton>
      <h1>Can't submit to this Jam</h1>
      <ConditionalNull condition={!started}>
        <p>The jam starts at {new Date(parseInt(parentJam.date_start)).toLocaleString('en-us', {
          timeZoneName: "long"
        })}</p>
      </ConditionalNull>
      <ConditionalNull condition={ended}>
        <p>The jam ended at {new Date(parseInt(parentJam.date_start)).toLocaleString('en-us', {
          timeZoneName: "long"
        })}</p>
      </ConditionalNull>
    </MainLayout>
  );

  return (
    <MainLayout currentPage="/jams/" title="New Submission" subtitle="Jams" backButton>
      <p>Submit something to <a href={`/jams/jam/${parentJam.id}`}>{parentJam.name}</a></p>
      <ConditionalNull condition={existingUser != null}>
        <p><small>Logged in as <b>{existingUser?.username}@{existingUser?.instance}</b></small></p>
      </ConditionalNull>
      <Form jamID={parentJam.id} />
    </MainLayout>
  )
}