import { eq } from "drizzle-orm";

import { auth } from "@/auth";
import { db } from "@/db/client";
import { plexAccounts } from "@/db/schema";

import { startPlexLinkAction, unlinkPlexAction, completePlexLink } from "./actions";

export const dynamic = "force-dynamic";

type PageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

export default async function AccountPage({ searchParams }: PageProps) {
  const session = await auth();
  if (!session?.user?.id) {
    return (
      <main className="mx-auto max-w-2xl px-6 py-12">
        <p className="text-sm">Sign in to manage your account.</p>
      </main>
    );
  }

  // Plex sends the user back here when they are done. Completing on GET rather
  // than asking them to press another button: they have already consented, and
  // a second click to finish something they thought was finished is just a way
  // to lose people half way through.
  const resolved = (await searchParams) ?? {};
  const returning = resolved.linking === "1";
  const message = returning ? await completePlexLink() : null;

  const [link] = await db
    .select()
    .from(plexAccounts)
    .where(eq(plexAccounts.userId, session.user.id))
    .limit(1);

  return (
    <main className="mx-auto max-w-2xl space-y-8 px-6 py-12">
      <header>
        <h1 className="font-serif text-3xl font-semibold">Your account</h1>
        <p className="mt-2 text-sm text-admin-muted">{session.user.email}</p>
      </header>

      {message && (
        <p className="rounded border border-admin-accent px-4 py-3 text-sm">{message}</p>
      )}

      <section className="space-y-3">
        <h2 className="font-serif text-xl font-semibold">Plex</h2>

        {link ? (
          <>
            <p className="text-sm">
              Linked as <strong>{link.plexUsername}</strong>.
            </p>
            <p className="text-sm text-admin-muted">
              {link.librariesSharedAt
                ? "The Movies, TV Shows and Music libraries are shared with you. Check your email for the invitation if you have not accepted it yet."
                : "The libraries have not been shared yet — link again to retry."}
            </p>
            <p className="text-sm text-admin-muted">
              Anything you add to your Plex watchlist is treated as a request: if we already
              have it you will find it in the library, and if we do not, we will go and get it.
            </p>
            <form action={unlinkPlexAction}>
              <button type="submit" className="admin-nav-button px-3 py-2 text-sm font-medium">
                Unlink
              </button>
            </form>
          </>
        ) : (
          <>
            <p className="text-sm text-admin-muted">
              Link your Plex account to get access to the Movies, TV Shows and Music libraries.
              Once linked, your Plex watchlist becomes your request list — add something there
              and it will be found for you.
            </p>
            <p className="text-xs text-admin-muted">
              You sign in at plex.tv, not here. Ampelos never sees your Plex password, and the
              sign-in token is discarded as soon as Plex confirms who you are.
            </p>
            <form action={startPlexLinkAction}>
              <button type="submit" className="admin-nav-button px-4 py-2 text-sm font-medium">
                Link my Plex account
              </button>
            </form>
          </>
        )}
      </section>
    </main>
  );
}
