import Link from "next/link";
import { ArrowRight, Bell, Clock3, MonitorPlay, Plus, UsersRound } from "lucide-react";
import { AppShell } from "@/components/app-shell";
import { Avatar } from "@/components/avatar";
import { StatusBadge } from "@/components/status-badge";
import { DataTable, EmptyState, MetricTile, PageHeader, Panel, StatusDot } from "@/components/ui";
import { prisma } from "@/lib/prisma";
import { getShellContext } from "@/lib/shell";
import { requireCurrentUser } from "@/lib/session";
import { requireInitialSetup } from "@/lib/setup";

export const dynamic = "force-dynamic";

export default async function DashboardPage() {
  await requireInitialSetup();
  const user = await requireCurrentUser();
  const shell = await getShellContext(user);

  const [userCount, roomCount, pendingRequests, acceptedFriends, rooms, recentMedia] = await Promise.all([
    prisma.user.count(),
    prisma.room.count(),
    prisma.friendship.count({ where: { receiverId: user.id, status: "PENDING" } }),
    prisma.friendship.count({
      where: {
        status: "ACCEPTED",
        OR: [{ requesterId: user.id }, { receiverId: user.id }]
      }
    }),
    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: 7
    }),
    prisma.mediaSource.findMany({
      where: {
        room: {
          OR: [{ visibility: "PUBLIC" }, { ownerId: user.id }, { members: { some: { userId: user.id } } }]
        }
      },
      include: { room: true, submitter: true },
      orderBy: { createdAt: "desc" },
      take: 6
    })
  ]);

  return (
    <AppShell active="Overview" {...shell}>
      <PageHeader
        title="Overview"
        description={`Instance dashboard for ${shell.userName}. Rooms, requests, and recent media are separated from playback.`}
        meta={
          <>
            <StatusDot tone="good" label="App rendered" />
            <StatusDot tone="good" label="Database queried" />
            <StatusDot tone={shell.activeRoomCount > 0 ? "info" : "neutral"} label={`${shell.activeRoomCount} rooms with queue`} />
          </>
        }
        actions={
          <>
            <Link className="button" href="/people">
              <UsersRound size={16} /> People
            </Link>
            <Link className="button primary" href="/rooms">
              <Plus size={16} /> New room
            </Link>
          </>
        }
      />

      <section className="metrics-grid" aria-label="Instance summary">
        <MetricTile label="Accounts" value={userCount} detail="registered local users" tone="info" />
        <MetricTile label="Rooms" value={roomCount} detail="persistent rooms" tone="good" />
        <MetricTile label="Friends" value={acceptedFriends} detail="accepted relationships" />
        <MetricTile label="Requests" value={pendingRequests} detail="waiting for your action" tone={pendingRequests > 0 ? "warn" : "neutral"} />
      </section>

      <section className="overview-grid">
        <Panel
          title="Accessible Rooms"
          eyebrow="Watch surfaces"
          actions={<Link className="text-link" href="/rooms">Manage all <ArrowRight size={14} /></Link>}
        >
          {rooms.length === 0 ? (
            <EmptyState title="No rooms are available" description="Create a room or add friends to see shared rooms here." />
          ) : (
            <DataTable>
              <table className="table">
                <thead>
                  <tr>
                    <th>Room</th>
                    <th>Owner</th>
                    <th>Access</th>
                    <th>Queue</th>
                    <th />
                  </tr>
                </thead>
                <tbody>
                  {rooms.map((room) => (
                    <tr key={room.id}>
                      <td>
                        <div className="row-title">
                          <strong>{room.name}</strong>
                          <span>/{room.slug}</span>
                        </div>
                      </td>
                      <td>{room.owner?.displayName || room.owner?.username || "Unassigned"}</td>
                      <td><StatusBadge>{formatVisibility(room.visibility)}</StatusBadge></td>
                      <td>{room._count.mediaSources} sources</td>
                      <td>
                        <Link className="icon-button compact" href={`/rooms/${encodeURIComponent(room.slug)}`} aria-label={`Open ${room.name}`}>
                          <MonitorPlay size={15} />
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </DataTable>
          )}
        </Panel>

        <div className="stack">
          <Panel title="Quick Actions" eyebrow="Common work">
            <div className="action-list">
              <Link className="action-row" href="/rooms">
                <MonitorPlay size={17} />
                <span>
                  <strong>Create or open a room</strong>
                  <small>Manage persistent rooms and access</small>
                </span>
              </Link>
              <Link className="action-row" href="/people">
                <UsersRound size={17} />
                <span>
                  <strong>Review people</strong>
                  <small>{pendingRequests} incoming request{pendingRequests === 1 ? "" : "s"}</small>
                </span>
              </Link>
              <Link className="action-row" href="/activity">
                <Bell size={17} />
                <span>
                  <strong>Audit recent activity</strong>
                  <small>Media, rooms, and social changes</small>
                </span>
              </Link>
            </div>
          </Panel>

          <Panel title="Recent Media" eyebrow="Last additions">
            {recentMedia.length === 0 ? (
              <EmptyState title="No media activity yet" description="Queued YouTube, Twitch, and direct videos will appear here." />
            ) : (
              recentMedia.map((item) => (
                <div className="row" key={item.id}>
                  <div className="row-main">
                    <Avatar name={item.submitter?.displayName || item.submitter?.username || "WL"} src={item.submitter?.avatarUrl} size={34} />
                    <div className="row-title">
                      <strong>{item.title || item.originalUrl}</strong>
                      <span>{item.room.name} by {item.submitter?.displayName || item.submitter?.username || "Unknown"}</span>
                    </div>
                  </div>
                  <StatusBadge>{item.provider}</StatusBadge>
                </div>
              ))
            )}
          </Panel>
        </div>
      </section>

      <Panel title="Instance Timeline" eyebrow="Operational events">
        {recentMedia.length === 0 && rooms.length === 0 ? (
          <EmptyState title="No timeline events" description="Room and media events are shown after the instance is used." />
        ) : (
          <div className="timeline-list">
            {recentMedia.map((item) => (
              <div className="timeline-item" key={`timeline-${item.id}`}>
                <Clock3 size={15} />
                <div className="row-title">
                  <strong>{item.submitter?.displayName || item.submitter?.username || "Someone"} added {item.provider.toLowerCase()} media</strong>
                  <span>{item.room.name} - {formatDate(item.createdAt)}</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </Panel>
    </AppShell>
  );
}

function formatVisibility(value: string) {
  return value.toLowerCase().replace("_", " ");
}

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