import { AppShell } from "@/components/app-shell";
import { Avatar } from "@/components/avatar";
import { StatusBadge } from "@/components/status-badge";
import { acceptFriendRequest, declineFriendRequest, sendFriendRequest } from "@/lib/friend-actions";
import { prisma } from "@/lib/prisma";
import { requireCurrentUser, userIsAdmin } from "@/lib/session";
import { requireInitialSetup } from "@/lib/setup";
import Link from "next/link";

export const dynamic = "force-dynamic";

export default async function FriendsPage() {
  await requireInitialSetup();
  const user = await requireCurrentUser();
  const personalRoom = await prisma.room.findFirst({ where: { ownerId: user.id }, select: { slug: true } });
  const [users, friendships] = await Promise.all([
    prisma.user.findMany({
      where: { id: { not: user.id } },
      include: { ownedRooms: { select: { slug: true }, take: 1 } },
      orderBy: { username: "asc" }
    }),
    prisma.friendship.findMany({
      where: { OR: [{ requesterId: user.id }, { receiverId: user.id }] },
      include: { requester: true, receiver: true }
    })
  ]);

  const incoming = friendships.filter((item) => item.receiverId === user.id && item.status === "PENDING");
  const relationshipByUserId = new Map<string, (typeof friendships)[number]>();
  for (const friendship of friendships) {
    if (friendship.status === "DECLINED") continue;
    const otherId = friendship.requesterId === user.id ? friendship.receiverId : friendship.requesterId;
    relationshipByUserId.set(otherId, friendship);
  }

  return (
    <AppShell
      active="Friends"
      isAdmin={userIsAdmin(user)}
      roomHref={personalRoom ? `/rooms/${encodeURIComponent(personalRoom.slug)}` : "/dashboard"}
      userName={user.displayName || user.username}
    >
      <header className="topbar">
        <div className="title-block">
          <h1>Friends</h1>
          <p>Add users, accept requests, and enter persistent rooms.</p>
        </div>
        <StatusBadge>{users.length} users</StatusBadge>
      </header>

      {incoming.length > 0 ? (
        <section className="panel" style={{ marginBottom: 18 }}>
          <div className="panel-header">
            <h2>Incoming requests</h2>
            <StatusBadge tone="warn">{incoming.length} pending</StatusBadge>
          </div>
          <div className="panel-body">
            {incoming.map((request) => (
              <div className="row" key={request.id}>
                <div className="row-main">
                  <Avatar name={request.requester.displayName || request.requester.username} />
                  <div className="row-title">
                    <strong>{request.requester.displayName || request.requester.username}</strong>
                    <span>@{request.requester.username}</span>
                  </div>
                </div>
                <div className="status-row">
                  <form action={acceptFriendRequest}>
                    <input type="hidden" name="friendshipId" value={request.id} />
                    <button className="button primary" type="submit">Accept</button>
                  </form>
                  <form action={declineFriendRequest}>
                    <input type="hidden" name="friendshipId" value={request.id} />
                    <button className="button" type="submit">Decline</button>
                  </form>
                </div>
              </div>
            ))}
          </div>
        </section>
      ) : null}

      <section className="panel">
        <div className="panel-header">
          <h2>Users</h2>
          <StatusBadge>Account directory</StatusBadge>
        </div>
        <div className="panel-body">
          {users.map((listedUser) => {
            const relationship = relationshipByUserId.get(listedUser.id);
            const isFriend = relationship?.status === "ACCEPTED";
            const isOutgoing = relationship?.requesterId === user.id && relationship.status === "PENDING";
            const isIncoming = relationship?.receiverId === user.id && relationship.status === "PENDING";
            const roomSlug = listedUser.ownedRooms[0]?.slug;

            return (
              <div className="row" key={listedUser.id}>
                <div className="row-main">
                  <Avatar name={listedUser.displayName || listedUser.username} />
                  <div className="row-title">
                    <strong>{listedUser.displayName || listedUser.username}</strong>
                    <span>@{listedUser.username}</span>
                  </div>
                </div>
                <div className="status-row">
                  {isFriend ? <StatusBadge tone="good">Friend</StatusBadge> : null}
                  {isOutgoing ? <StatusBadge tone="warn">Requested</StatusBadge> : null}
                  {isIncoming ? <StatusBadge tone="warn">Waiting</StatusBadge> : null}
                  {roomSlug && isFriend ? (
                    <Link className="button" href={`/rooms/${encodeURIComponent(roomSlug)}`}>Enter room</Link>
                  ) : null}
                  {!relationship ? (
                    <form action={sendFriendRequest}>
                      <input type="hidden" name="receiverId" value={listedUser.id} />
                      <button className="button primary" type="submit">Add friend</button>
                    </form>
                  ) : null}
                </div>
              </div>
            );
          })}
          {users.length === 0 ? <div className="empty-state">No other users have registered yet.</div> : null}
        </div>
      </section>
    </AppShell>
  );
}
