import Link from "next/link";
import { isOrganizer, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { logoutAction } from "@/app/(auth)/actions";
import { Avatar, Logo } from "@/components/ui";

const TABS = [
  ["", "My tickets"],
  ["schedule", "My schedule"],
  ["submissions", "My submissions"],
  ["reviews", "Reviews"],
  ["notifications", "Notifications"],
] as const;

export default async function MeLayout({ children }: { children: React.ReactNode }) {
  const user = await requireUser();
  const [unread, teamMemberships] = await Promise.all([
    db.notification.count({ where: { userId: user.id, readAt: null } }),
    db.confMember.count({ where: { userId: user.id } }),
  ]);
  const showOrganizerView = isOrganizer(user) || teamMemberships > 0;

  return (
    <div className="min-h-screen bg-zinc-950">
      <header className="fx-header sticky top-0 z-30 border-b border-zinc-800/70 bg-zinc-950/85 backdrop-blur">
        <div className="mx-auto flex h-14 max-w-5xl items-center justify-between px-4">
          <div className="flex items-center gap-6">
            <Logo />
            <span className="hidden text-sm text-zinc-500 sm:block">Attendee portal</span>
          </div>
          <div className="flex items-center gap-3">
            {showOrganizerView && (
              <Link href="/dashboard" className="text-sm text-zinc-400 hover:text-zinc-200">Organizer view</Link>
            )}
            <Avatar name={user.name} src={user.avatarUrl} size={8} />
            <form action={logoutAction}>
              <button className="rounded-lg px-2.5 py-1.5 text-xs text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-200">Sign out</button>
            </form>
          </div>
        </div>
        <nav className="mx-auto flex max-w-5xl gap-1 overflow-x-auto px-4 pb-2 text-sm">
          {TABS.map(([path, name]) => (
            <Link
              key={path}
              href={`/me${path ? `/${path}` : ""}`}
              className="whitespace-nowrap rounded-lg px-3 py-1.5 text-zinc-400 transition hover:bg-zinc-800/70 hover:text-zinc-100"
            >
              {name}
              {path === "notifications" && unread > 0 && (
                <span className="ml-1.5 rounded-full bg-indigo-500 px-1.5 text-[10px] font-semibold text-white">{unread}</span>
              )}
            </Link>
          ))}
        </nav>
      </header>
      <main className="fx-in mx-auto max-w-5xl px-4 py-8">{children}</main>
    </div>
  );
}
