import Link from "next/link";
import { Lock, Plus, Search, UsersRound } from "lucide-react";
import { AppShell } from "@/components/app-shell";
import { StatusBadge } from "@/components/status-badge";
import { DataTable, EmptyState, PageHeader, Panel, StatusDot, Tabs } from "@/components/ui";
import { createRoom } from "@/lib/room-actions";
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";

const roomTabs = ["My Rooms", "Shared", "Public", "Recent", "Invites"];

export default async function RoomsPage({ searchParams }: { searchParams: Promise<{ view?: string; error?: string; q?: string }> }) {
  await requireInitialSetup();
  const user = await requireCurrentUser();
  const shell = await getShellContext(user);
  const { view = "My Rooms", error, q = "" } = await searchParams;
  const activeView = roomTabs.includes(view) ? view : "My Rooms";
  const query = q.trim().toLowerCase();

  const [owned, shared, publicRooms, recent] = await Promise.all([
    prisma.room.findMany({
      where: { ownerId: user.id },
      include: { owner: true, _count: { select: { members: true, mediaSources: true } } },
      orderBy: { updatedAt: "desc" }
    }),
    prisma.room.findMany({
      where: { members: { some: { userId: user.id } }, ownerId: { not: user.id } },
      include: { owner: true, _count: { select: { members: true, mediaSources: true } } },
      orderBy: { updatedAt: "desc" }
    }),
    prisma.room.findMany({
      where: { visibility: "PUBLIC" },
      include: { owner: true, _count: { select: { members: true, mediaSources: true } } },
      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: 12
    })
  ]);

  const roomGroups = {
    "My Rooms": owned,
    Shared: shared,
    Public: publicRooms,
    Recent: recent,
    Invites: []
  };
  const rows = roomGroups[activeView as keyof typeof roomGroups] || owned;
  const filteredRows = query
    ? rows.filter((room) =>
        [room.name, room.slug, room.owner?.displayName || "", room.owner?.username || "", room.visibility]
          .join(" ")
          .toLowerCase()
          .includes(query)
      )
    : rows;
  const tabCounts: Record<string, number> = {
    "My Rooms": owned.length,
    Shared: shared.length,
    Public: publicRooms.length,
    Recent: recent.length,
    Invites: 0
  };

  return (
    <AppShell active="Rooms" {...shell}>
      <PageHeader
        title="Rooms"
        description="Persistent watch rooms with stable routes, clear access state, and operational controls."
        meta={
          <>
            <StatusDot tone="good" label={`${owned.length} owned`} />
            <StatusDot tone={shared.length > 0 ? "good" : "neutral"} label={`${shared.length} shared`} />
            <StatusDot tone="info" label={`${publicRooms.length} public`} />
          </>
        }
      />

      <section className="rooms-layout">
        <Panel title="Create Room" eyebrow="Persistent route">
          {error ? <p className="form-error">Use a room name with at least one letter or number.</p> : null}
          <form className="form compact-form" action={createRoom}>
            <label>
              Name
              <input className="input" name="name" placeholder="Friday stream room" required />
            </label>
            <label>
              Visibility
              <select className="input" name="visibility" defaultValue="FRIENDS">
                <option value="FRIENDS">Friends-only</option>
                <option value="PUBLIC">Public</option>
                <option value="EXPLICIT">Explicit members</option>
                <option value="ROLE_RESTRICTED">Role restricted</option>
              </select>
            </label>
            <button className="button primary" type="submit">
              <Plus size={16} /> Create room
            </button>
          </form>
        </Panel>

        <Panel
          title="Room Directory"
          eyebrow="Index"
          actions={
            <form className="toolbar" action="/rooms">
              <input type="hidden" name="view" value={activeView} />
              <label className="search-field">
                <Search size={15} />
                <input name="q" placeholder="Filter rooms" defaultValue={q} />
              </label>
            </form>
          }
        >
            <Tabs
            active={activeView}
            items={roomTabs.map((tab) => ({
              label: tab,
              href: `/rooms?view=${encodeURIComponent(tab)}`,
              count: tabCounts[tab]
            }))}
          />

          {filteredRows.length === 0 ? (
            <EmptyState
              title={`No ${activeView.toLowerCase()} rooms`}
              description={
                activeView === "Invites"
                  ? "Invite codes grant access during registration; accepted shared rooms appear in the Shared tab."
                  : "Rooms appear here when ownership, membership, or visibility matches this tab."
              }
            />
          ) : (
            <DataTable>
              <table className="table">
                <thead>
                  <tr>
                    <th>Room</th>
                    <th>Owner</th>
                    <th>Access</th>
                    <th>State</th>
                    <th>Updated</th>
                    <th />
                  </tr>
                </thead>
                <tbody>
                  {filteredRows.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>
                        <span className="inline-meta">
                          <UsersRound size={14} /> {room._count.members + 1}
                          <Lock size={14} /> {room._count.mediaSources}
                        </span>
                      </td>
                      <td>{formatDate(room.updatedAt)}</td>
                      <td>
                        <Link className="button compact-button" href={`/rooms/${encodeURIComponent(room.slug)}`}>
                          Open
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </DataTable>
          )}
        </Panel>
      </section>
    </AppShell>
  );
}

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

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