import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { EmptyState, PageHeader } from "@/components/ui";
import { dayKey, fmtDay, fmtTime } from "@/lib/utils";
import { SESSION_TYPE_COLORS } from "@/lib/constants";
import { toggleScheduleItem } from "../actions";

export const metadata = { title: "My schedule" };

export default async function MySchedulePage() {
  const user = await requireUser();
  const regs = await db.registration.findMany({
    where: { OR: [{ userId: user.id }, { email: user.email }], status: { not: "CANCELLED" } },
    select: { conferenceId: true },
  });
  const confIds = [...new Set(regs.map((r) => r.conferenceId))];
  const [sessions, bookmarks] = await Promise.all([
    db.session.findMany({
      where: { conferenceId: { in: confIds } },
      orderBy: { startAt: "asc" },
      include: { conference: true, track: true, room: true, speakers: { include: { speaker: true } } },
    }),
    db.scheduleItem.findMany({ where: { userId: user.id }, select: { sessionId: true } }),
  ]);
  const bookmarked = new Set(bookmarks.map((b) => b.sessionId));

  const days = new Map<string, typeof sessions>();
  for (const s of sessions) {
    const k = dayKey(s.startAt);
    if (!days.has(k)) days.set(k, []);
    days.get(k)!.push(s);
  }

  return (
    <div>
      <PageHeader
        title="My schedule"
        sub={`Star sessions to build your personal agenda — ${bookmarked.size} starred across ${confIds.length} conference${confIds.length === 1 ? "" : "s"}.`}
      />
      {sessions.length === 0 && <EmptyState title="Nothing scheduled" body="Register for a conference to see its sessions here." />}

      <div className="space-y-8">
        {[...days.entries()].map(([k, list]) => (
          <section key={k}>
            <h2 className="text-sm font-semibold uppercase tracking-wider text-zinc-400">{fmtDay(list[0].startAt)}</h2>
            <div className="mt-3 space-y-2">
              {list.map((s) => (
                <div
                  key={s.id}
                  className={`flex items-start justify-between gap-3 rounded-xl border p-4 transition ${
                    bookmarked.has(s.id) ? "border-indigo-500/40 bg-indigo-500/5" : "border-zinc-800 bg-zinc-900/50"
                  }`}
                >
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2 text-xs">
                      <span className="tabular-nums font-medium text-zinc-300">{fmtTime(s.startAt)}–{fmtTime(s.endAt)}</span>
                      <span className={`rounded-md border px-1.5 py-0.5 text-[10px] font-semibold ${SESSION_TYPE_COLORS[s.type] ?? ""}`}>{s.type}</span>
                      <span className="text-zinc-500">{s.conference.name}</span>
                      {s.room && <span className="text-zinc-600">· {s.room.name}</span>}
                    </div>
                    <div className="mt-1 font-medium text-zinc-100">{s.title}</div>
                    {s.speakers.length > 0 && (
                      <div className="mt-0.5 text-xs text-zinc-500">{s.speakers.map(({ speaker }) => speaker.name).join(", ")}</div>
                    )}
                  </div>
                  <form action={toggleScheduleItem.bind(null, s.id)}>
                    <button
                      className={`rounded-lg px-2.5 py-1.5 text-lg leading-none transition ${bookmarked.has(s.id) ? "text-amber-600" : "text-zinc-600 hover:text-zinc-300"}`}
                      title={bookmarked.has(s.id) ? "Remove from my schedule" : "Add to my schedule"}
                    >
                      {bookmarked.has(s.id) ? "★" : "☆"}
                    </button>
                  </form>
                </div>
              ))}
            </div>
          </section>
        ))}
      </div>
    </div>
  );
}
