import Link from "next/link";
import { FloorCard } from "@/components/cards";
import { Composer } from "@/components/composer";
import { PageShell } from "@/components/page";
import { prisma } from "@/lib/prisma";
import { isAdmin, profileTypeLabel } from "@/lib/roles";
import { readSession } from "@/lib/session";

const TABS = [
  { value: "all", label: "All" },
  { value: "discussion", label: "Questions" },
  { value: "update", label: "Updates" },
  { value: "announcement", label: "Notices" },
  { value: "event", label: "Events" },
] as const;

const KIND_LABEL: Record<string, string> = {
  discussion: "Question",
  update: "Update",
  announcement: "Notice",
  event: "Event",
};

function formatWhen(date: Date) {
  return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}

export default async function FeedPage({
  searchParams,
}: {
  searchParams: Promise<{ kind?: string; error?: string }>;
}) {
  const { kind = "all", error } = await searchParams;
  const session = await readSession();
  const filter = TABS.some((tab) => tab.value === kind) ? kind : "all";

  const [posts, events, grouped] = await Promise.all([
    prisma.post.findMany({
      where: {
        hidden: false,
        ...(filter === "all" ? {} : { kind: filter }),
      },
      include: {
        author: { include: { profile: true } },
        _count: { select: { replies: true } },
      },
      orderBy: { createdAt: "desc" },
      take: 40,
    }),
    prisma.post.findMany({
      where: { hidden: false, kind: "event", eventAt: { gte: new Date() } },
      orderBy: { eventAt: "asc" },
      take: 4,
    }),
    prisma.post.groupBy({
      by: ["kind"],
      where: { hidden: false },
      _count: { _all: true },
    }),
  ]);

  const byKind = Object.fromEntries(grouped.map((row) => [row.kind, row._count._all]));
  const total = grouped.reduce((sum, row) => sum + row._count._all, 0);
  const counts: Record<string, number> = {
    all: total,
    discussion: byKind.discussion || 0,
    update: byKind.update || 0,
    announcement: byKind.announcement || 0,
    event: byKind.event || 0,
  };

  return (
    <PageShell
      wide
      eyebrow="Floor"
      title="The floor"
      lede="Questions, updates, and notices. Private deals stay in rooms. Events with a date also appear on the calendar."
    >
      <div className="dir-toolbar">
        <nav className="floor-tabs dir-tabs" aria-label="Filter posts">
          {TABS.map((tab) => (
            <Link
              key={tab.value}
              href={tab.value === "all" ? "/feed" : `/feed?kind=${tab.value}`}
              className={filter === tab.value ? "is-on" : undefined}
            >
              {tab.label}
              <small>{counts[tab.value]}</small>
            </Link>
          ))}
        </nav>
      </div>

      <div className="floor">
        <section>
          <div className="dir-count">
            <h2>{filter === "all" ? "Latest on the floor" : TABS.find((tab) => tab.value === filter)?.label}</h2>
            <p>
              {posts.length} {posts.length === 1 ? "post" : "posts"}
            </p>
          </div>

          {posts.length === 0 ? (
            <p className="dir-empty">Nothing in this column yet.</p>
          ) : (
            <div className="floor-grid">
              {posts.map((post) => (
                <FloorCard
                  key={post.id}
                  href={`/feed/${post.id}`}
                  title={post.title}
                  body={post.body}
                  kind={post.kind}
                  kindLabel={KIND_LABEL[post.kind] || post.kind}
                  authorName={post.author.name}
                  photoUrl={post.author.profile?.photoUrl}
                  craft={post.author.profile?.type ? profileTypeLabel(post.author.profile.type) : null}
                  when={
                    post.eventAt
                      ? `${formatWhen(post.eventAt)}${post.location ? ` · ${post.location}` : ""}`
                      : formatWhen(post.createdAt)
                  }
                  replyCount={post._count.replies}
                />
              ))}
            </div>
          )}
        </section>

        <aside className="floor-aside">
          {session ? (
            <Composer isSteward={isAdmin(session)} error={error === "1"} />
          ) : (
            <div className="composer">
              <p className="eg-eyebrow">Post to the floor</p>
              <p className="text-sm text-muted">
                <Link href="/login?next=/feed" className="text-primary">
                  Sign in
                </Link>{" "}
                to ask a question or post an update.
              </p>
            </div>
          )}

          <div className="composer">
            <div className="portal-col__head">
              <div>
                <p className="eg-eyebrow">Calendar</p>
                <h2>Upcoming</h2>
              </div>
              <Link href="/events">All events</Link>
            </div>
            {events.length === 0 ? (
              <p className="text-sm text-muted">No dated events yet.</p>
            ) : (
              <ul className="floor-upcoming">
                {events.map((event) => (
                  <li key={event.id}>
                    <Link href={`/feed/${event.id}`}>
                      <p>{event.title}</p>
                      <span>
                        {event.eventAt ? formatWhen(event.eventAt) : ""}
                        {event.location ? ` · ${event.location}` : ""}
                      </span>
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </aside>
      </div>
    </PageShell>
  );
}
