import Image from "next/image";
import Link from "next/link";
import { redirect } from "next/navigation";

import { auth, signOut } from "@/auth";
import { APP_URL } from "@/lib/app-url";
import { getProfile } from "@/lib/profile";

import { ProfilePanel } from "./profile-panel";

export const dynamic = "force-dynamic";

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

function single(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

/**
 * What to say about a link attempt that just came back.
 *
 * The linking itself happens in /api/plex/callback, which redirects here with
 * an outcome code; this page only renders it. Reading a code rather than a
 * ready-made sentence keeps somebody else's error text out of a URL that a
 * person might paste to ask for help.
 */
function linkMessage(params: Record<string, string | string[] | undefined>) {
  const outcome = single(params.plex);
  if (!outcome) return null;

  const who = single(params.who);
  const reason = single(params.reason);
  const named = who ? `Linked as ${who}` : "Linked";

  switch (outcome) {
    case "linked":
      return `${named}. The Plex libraries have been shared with you — check your email for the invitation.`;
    case "owner":
      return `${named}. You own this Plex server, so you already have every library — nothing needed sharing.`;
    case "already-shared":
      return `${named}. You already had access to the libraries.`;
    case "share-failed":
      return `${named}, but the libraries could not be shared${reason ? `: ${reason}` : "."} You can try linking again.`;
    case "not-completed":
      return "That sign-in was not completed. Try linking again.";
    case "taken":
      return "That Plex account is already linked to another Ampelos user.";
    case "error":
      return `Plex could not confirm the sign-in${reason ? `: ${reason}` : "."}`;
    default:
      return null;
  }
}

export default async function ProfilePage({ searchParams }: PageProps) {
  const session = await auth();
  if (!session?.user?.id) redirect("/login");

  const resolved = (await searchParams) ?? {};
  const message = linkMessage(resolved);

  const profile = await getProfile(session.user.id, APP_URL);
  if (!profile) redirect("/login");

  return (
    <main className="ampelos-app pb-24 text-ampelos-parchment">
      <header className="ampelos-topbar">
        <div className="mx-auto flex max-w-3xl flex-col gap-4 px-4 py-5 md:flex-row md:items-center md:justify-between md:px-6">
          <div className="flex items-center gap-4">
            <Image
              src="/ampelos.png"
              alt="Ampelos"
              width={64}
              height={64}
              priority
              className="h-14 w-14 shrink-0 rounded-full border border-ampelos-gold/35 bg-ampelos-ink/45 object-cover p-0.5 shadow-[0_8px_24px_rgba(0,0,0,0.45)]"
            />
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.32em] text-ampelos-gold">
                Profile
              </p>
              <h1 className="font-serif text-3xl font-semibold text-ampelos-parchment">
                {profile.user.displayName}
              </h1>
              <p className="text-sm text-ampelos-muted">{profile.user.email}</p>
            </div>
          </div>
          <div className="flex flex-wrap items-center gap-2 text-sm">
            <Link href="/" className="ampelos-ghost-button px-3 py-2 font-medium">
              Catalog
            </Link>
            {session.user.isAdmin && (
              <Link href="/admin" className="ampelos-ghost-button px-3 py-2 font-medium">
                Admin
              </Link>
            )}
            <form action={async () => { "use server"; await signOut({ redirectTo: "/login" }); }}>
              <button type="submit" className="ampelos-ghost-button px-3 py-2 font-medium">
                Sign out
              </button>
            </form>
          </div>
        </div>
      </header>

      <section className="mx-auto max-w-3xl px-4 py-8 md:px-6">
        {message && (
          <p className="mb-6 rounded border border-ampelos-gold/50 bg-ampelos-ink/40 px-4 py-3 text-sm">
            {message}
          </p>
        )}

        <div className="ampelos-panel rounded-lg p-6">
          <ProfilePanel profile={profile} />
        </div>
      </section>
    </main>
  );
}
