import { AppShell } from "@/components/app-shell";
import { Avatar } from "@/components/avatar";
import { RoomConsole } from "@/components/room-console";
import { StatusBadge } from "@/components/status-badge";
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 DashboardPage() {
  await requireInitialSetup();
  const user = await requireCurrentUser();
  const isAdmin = userIsAdmin(user);

  const [personalRoom, userCount, roomCount, pendingRequests, friendships, rooms] = await Promise.all([
    prisma.room.findFirst({
      where: { ownerId: user.id },
      include: {
        owner: true,
        members: { include: { user: true } },
        mediaSources: { include: { submitter: true }, orderBy: { createdAt: "desc" }, take: 8 }
      }
    }),
    prisma.user.count(),
    prisma.room.count(),
    prisma.friendship.count({ where: { receiverId: user.id, status: "PENDING" } }),
    prisma.friendship.findMany({
      where: {
        status: "ACCEPTED",
        OR: [{ requesterId: user.id }, { receiverId: user.id }]
      },
      include: { requester: true, receiver: true },
      take: 6,
      orderBy: { updatedAt: "desc" }
    }),
    prisma.room.findMany({
      where: {
        OR: [{ visibility: "PUBLIC" }, { ownerId: user.id }, { members: { some: { userId: user.id } } }]
      },
      include: { owner: true, _count: { select: { members: true, mediaSources: true } } },
      orderBy: { updatedAt: "desc" },
      take: 8
    })
  ]);

  const acceptedFriends = friendships.length;
  const roomHref = personalRoom ? `/rooms/${encodeURIComponent(personalRoom.slug)}` : "/dashboard";
  const stats = [
    { label: "Users", value: userCount },
    { label: "Rooms", value: roomCount },
    { label: "Friends", value: acceptedFriends },
    { label: "Requests", value: pendingRequests }
  ];

  return (
    <AppShell active="Dashboard" isAdmin={isAdmin} roomHref={roomHref} userName={user.displayName || user.username}>
      <header className="topbar">
        <div className="title-block">
          <h1>Dashboard</h1>
          <p>{`Signed in as ${user.displayName || user.username}`}</p>
        </div>
        <div className="status-row">
          <StatusBadge tone="good">Online</StatusBadge>
          <StatusBadge>System theme</StatusBadge>
        </div>
      </header>

      <section className="stats-grid" aria-label="System overview">
        {stats.map((stat) => (
          <div className="stat" key={stat.label}>
            <span>{stat.label}</span>
            <strong>{stat.value}</strong>
          </div>
        ))}
      </section>

      {personalRoom ? (
        <RoomConsole
          roomId={personalRoom.id}
          roomSlug={personalRoom.slug}
          currentUser={user.displayName || user.username}
          queue={personalRoom.mediaSources.map((item) => ({
            id: item.id,
            title: item.title || item.originalUrl,
            provider: item.provider,
            originalUrl: item.originalUrl,
            playbackUrl: item.playbackUrl,
            by: item.submitter?.displayName || item.submitter?.username || "Unknown",
            createdAt: formatDate(item.createdAt)
          }))}
          participants={[
            {
              id: user.id,
              name: user.displayName || user.username,
              role: "Owner",
              status: "Online"
            },
            ...personalRoom.members.map((member) => ({
              id: member.userId,
              name: member.user.displayName || member.user.username,
              role: member.canManage ? "Manager" : "Member",
              status: "Invited"
            }))
          ]}
        />
      ) : (
        <section className="panel">
          <div className="panel-body">
            <div className="empty-state">No personal room exists for this account yet.</div>
          </div>
        </section>
      )}

      <section className="room-layout" style={{ marginTop: 18 }}>
        <section className="panel">
          <div className="panel-header">
            <h2>Rooms</h2>
            <StatusBadge>Persistent</StatusBadge>
          </div>
          <div className="panel-body">
            <table className="table">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Owner</th>
                  <th>Access</th>
                  <th>Status</th>
                  <th>Source</th>
                </tr>
              </thead>
              <tbody>
                {rooms.map((room) => (
                  <tr key={room.id}>
                    <td>
                      <Link href={`/rooms/${encodeURIComponent(room.slug)}`}>{room.name}</Link>
                    </td>
                    <td>{room.owner?.displayName || room.owner?.username || "Unassigned"}</td>
                    <td>{room.visibility}</td>
                    <td>{room._count.members + 1} users</td>
                    <td>{room._count.mediaSources} queued</td>
                  </tr>
                ))}
              </tbody>
            </table>
            {rooms.length === 0 ? <div className="empty-state">No accessible rooms found.</div> : null}
          </div>
        </section>
        <section className="panel">
          <div className="panel-header">
            <h2>Friends</h2>
            <StatusBadge tone={acceptedFriends > 0 ? "good" : undefined}>{acceptedFriends} linked</StatusBadge>
          </div>
          <div className="panel-body">
            {friendships.map((friendship) => {
              const friend = friendship.requesterId === user.id ? friendship.receiver : friendship.requester;
              return (
                <div className="row" key={friend.id}>
                  <div className="row-main">
                    <Avatar name={friend.displayName || friend.username} />
                    <div className="row-title">
                      <strong>{friend.displayName || friend.username}</strong>
                      <span>@{friend.username}</span>
                    </div>
                  </div>
                  <StatusBadge tone="good">Friend</StatusBadge>
                </div>
              );
            })}
            {friendships.length === 0 ? <div className="empty-state">No friends yet. Add users from Friends.</div> : null}
          </div>
        </section>
      </section>
    </AppShell>
  );
}

function formatDate(date: Date) {
  return new Intl.DateTimeFormat("en", { month: "short", day: "numeric" }).format(date);
}
