import Link from "next/link";
import { Clock3, MonitorPlay, Radio, UsersRound } from "lucide-react";
import { AppShell } from "@/components/app-shell";
import { Avatar } from "@/components/avatar";
import { StatusBadge } from "@/components/status-badge";
import { EmptyState, 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 ActivityPage() {
  await requireInitialSetup();
  const user = await requireCurrentUser();
  const shell = await getShellContext(user);

  const [recentMedia, recentRooms, requests] = await Promise.all([
    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: 12
    }),
    prisma.room.findMany({
      where: { OR: [{ visibility: "PUBLIC" }, { ownerId: user.id }, { members: { some: { userId: user.id } } }] },
      include: { owner: true },
      orderBy: { updatedAt: "desc" },
      take: 8
    }),
    prisma.friendship.findMany({
      where: { OR: [{ requesterId: user.id }, { receiverId: user.id }] },
      include: { requester: true, receiver: true },
      orderBy: { updatedAt: "desc" },
      take: 8
    })
  ]);

  const events = [
    ...recentMedia.map((item) => ({
      id: `media-${item.id}`,
      icon: <Radio size={15} />,
      title: `${item.submitter?.displayName || item.submitter?.username || "Someone"} added ${item.provider.toLowerCase()} media`,
      detail: item.room.name,
      href: `/rooms/${encodeURIComponent(item.room.slug)}`,
      at: item.createdAt
    })),
    ...recentRooms.map((room) => ({
      id: `room-${room.id}`,
      icon: <MonitorPlay size={15} />,
      title: `${room.name} was updated`,
      detail: room.owner ? `Owner ${room.owner.displayName || room.owner.username}` : "Unassigned room",
      href: `/rooms/${encodeURIComponent(room.slug)}`,
      at: room.updatedAt
    })),
    ...requests.map((request) => {
      const person = request.requesterId === user.id ? request.receiver : request.requester;
      return {
        id: `friend-${request.id}`,
        icon: <UsersRound size={15} />,
        title: `Friend request ${request.status.toLowerCase()}`,
        detail: person.displayName || person.username,
        href: "/people",
        at: request.updatedAt
      };
    })
  ].sort((a, b) => b.at.getTime() - a.at.getTime()).slice(0, 20);

  return (
    <AppShell active="Activity" {...shell}>
      <PageHeader
        title="Activity"
        description="Instance event view for room, media, and people changes visible to your account."
        meta={
          <>
            <StatusDot tone="good" label={`${recentMedia.length} media events`} />
            <StatusDot tone="info" label={`${recentRooms.length} room updates`} />
            <StatusDot tone={requests.length > 0 ? "warn" : "neutral"} label={`${requests.length} relationship events`} />
          </>
        }
      />

      <Panel title="Event Stream" eyebrow="Latest first">
        {events.length === 0 ? (
          <EmptyState title="No activity yet" description="Create rooms, add media, or connect with people to populate this stream." />
        ) : (
          <div className="timeline-list">
            {events.map((event) => (
              <Link className="timeline-item interactive" href={event.href} key={event.id}>
                {event.icon}
                <div className="row-title">
                  <strong>{event.title}</strong>
                  <span>{event.detail} - {formatDate(event.at)}</span>
                </div>
                <StatusBadge>{relativeDate(event.at)}</StatusBadge>
              </Link>
            ))}
          </div>
        )}
      </Panel>

      <section className="split-grid">
        <Panel title="Most Recent Media" eyebrow="Queue inputs">
          {recentMedia.length === 0 ? (
            <EmptyState title="No media additions" />
          ) : (
            recentMedia.slice(0, 5).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}</span>
                  </div>
                </div>
                <StatusBadge>{item.provider}</StatusBadge>
              </div>
            ))
          )}
        </Panel>
        <Panel title="Recent Rooms" eyebrow="Accessible">
          {recentRooms.map((room) => (
            <div className="row" key={room.id}>
              <div className="row-title">
                <strong>{room.name}</strong>
                <span>{room.owner?.displayName || room.owner?.username || "Unassigned"} - {formatDate(room.updatedAt)}</span>
              </div>
              <Link className="button compact-button" href={`/rooms/${encodeURIComponent(room.slug)}`}>Open</Link>
            </div>
          ))}
        </Panel>
      </section>
    </AppShell>
  );
}

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

function relativeDate(date: Date) {
  const minutes = Math.max(1, Math.round((Date.now() - date.getTime()) / 60000));
  if (minutes < 60) return `${minutes}m`;
  const hours = Math.round(minutes / 60);
  if (hours < 24) return `${hours}h`;
  return `${Math.round(hours / 24)}d`;
}
