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";
import { notFound } from "next/navigation";

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;
  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 && !existingUser.admin) return notFound();
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let users = await db
    .selectFrom('users')
    .where('users.joined', '<=', curPage)
    .limit(20)
    .orderBy('users.admin', 'desc')
    .orderBy('users.joined', 'desc')
    .selectAll()
    .execute() as unknown[] as JSONUserTable[];
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let apps = await db
    .selectFrom('apps')
    .selectAll()
    .execute();

  return (
    <MainLayout currentPage="/jams/" title="Admin" subtitle="" backButton>
    <h2>cool admin panel !!! :3</h2>
    <p>contact me@abtmtr.link for help</p>
      <ConditionalNull condition={existingUser != null}>
        <p><small>Logged in as <b>{existingUser?.username}@{existingUser?.instance}</b></small></p>
        <ConditionalNull condition={existingUser?.admin == true}><p><a href="/jams/new/jam">Create Jam</a></p></ConditionalNull>
      </ConditionalNull>
      <h2>Users</h2>
      <p>use this to ban or promote users</p>
      <p>PLEASE DO NOT PROMOTE USERS WITHOUT MEOWCATHEORANGE'S PERMISSION</p>
      {users.map(async (user:JSONUserTable) => {
        let jams = await db
          .selectFrom('jams')
          .where('jams.author_id', '=', user.id)
          .select('id')
          .orderBy('jams.created', 'desc')
          .execute();
        let content = await db
          .selectFrom('content')
          .where('content.author_id', '=', user.id)
          .select('id')
          .orderBy('content.submitted', 'desc')
          .execute();
        let judgements = await db
          .selectFrom('judgements')
          .where('judgements.author_id', '=', user.id)
          .select('id')
          .orderBy('judgements.published', 'desc')
          .execute();
        let tokens = await db
          .selectFrom('tokens')
          .where('tokens.owner', '=', user.id)
          .select('id')
          .orderBy('tokens.created', 'desc')
          .execute();
        
        return (<div style={{
          margin: '16px 0'
        }}>
          <p><Link href={`/jams/user/${user.id}`}>{user.username}@{user.instance}</Link></p>
          <p><small><Link href={user.url} target="_blank">{user.url}</Link></small></p>
          <p><small>{user.banned ? <><b>BANNED</b> - </> : <></>}{user.admin ? <><b>ADMIN</b> - </> : <></>}Joined {new Date(parseInt(user.joined)).toDateString()}</small></p>
          <p><small>{jams.length} jam{jams.length != 1 && "s"}, {content.length} submission{content.length != 1 && "s"}, {judgements.length} judgement{judgements.length != 1 && "s"}, {tokens.length} token{tokens.length != 1 && "s"}</small></p>
          <p><Link href={`/jams/edit/user/${user.id}`}>Edit user</Link> - <Link href={`/jams/delete/user/${user.id}`}>Delete user</Link></p>
        </div>);
      })}
      <div className="navigation">
        <ConditionalNull condition={curPage < curDate}>
          <Link href={`?`}>Later</Link>
        </ConditionalNull>
        <ConditionalNull condition={users.length > 20}>
          <Link href={`?until=${parseInt(users.at(-1)?.joined || curPage + "") - 1}`}>Earlier</Link>
        </ConditionalNull>
      </div>
      <h2>Apps</h2>
      <p>apps stored in the database</p>
      <p>if sign-in breaks, it might be one of these</p>
      <p>contact me@abtmtr.link if sign-in breaks</p>
      {apps.map(async (app) => {
        
        return (<div style={{
          margin: '16px 0'
        }}>
          <p><Link href={`https://${app.instance_domain}/`}>{app.instance_domain}</Link></p>
          <p><small>Client ID: {app.client_id}</small></p>
          <p><small>Redirect URI: {app.redirect_uri}</small></p>
          <p><small>Scopes: read</small></p>
        </div>);
      })}
    </MainLayout>
  )
}