import { AppShell } from "@/components/app-shell";
import { Avatar } from "@/components/avatar";
import { StatusBadge } from "@/components/status-badge";
import { DataTable, PageHeader, Panel, StatusDot } from "@/components/ui";
import { logoutUser } from "@/lib/user-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";

export default async function ProfilePage() {
  await requireInitialSetup();
  const user = await requireCurrentUser();
  const shell = await getShellContext(user);
  const [ownedRooms, friendships] = await Promise.all([
    prisma.room.findMany({ where: { ownerId: user.id }, orderBy: { updatedAt: "desc" } }),
    prisma.friendship.count({ where: { status: "ACCEPTED", OR: [{ requesterId: user.id }, { receiverId: user.id }] } })
  ]);

  return (
    <AppShell active="Overview" {...shell}>
      <PageHeader
        title="Profile"
        description="Account identity, room ownership, roles, and session controls."
        meta={
          <>
            <StatusDot tone="good" label="signed in" />
            <StatusDot tone="info" label={`${ownedRooms.length} rooms`} />
            <StatusDot tone="good" label={`${friendships} friends`} />
          </>
        }
        actions={
          <form action={logoutUser}>
            <button className="button" type="submit">Logout</button>
          </form>
        }
      />

      <section className="split-grid">
        <Panel title="Account" eyebrow="Identity">
          <div className="profile-block">
            <Avatar name={user.displayName || user.username} src={user.avatarUrl} size={64} />
            <div className="row-title">
              <strong>{user.displayName || user.username}</strong>
              <span>@{user.username}</span>
            </div>
          </div>
          <div className="settings-list">
            <div className="setting-row"><span><strong>Display name</strong><small>{user.displayName || user.username}</small></span></div>
            <div className="setting-row"><span><strong>Created</strong><small>{formatDate(user.createdAt)}</small></span></div>
            <div className="setting-row"><span><strong>Roles</strong><small>{user.roles.map((item) => item.role.name).join(", ") || "user"}</small></span></div>
          </div>
        </Panel>

        <Panel title="Owned Rooms" eyebrow="Persistent spaces">
          <DataTable>
            <table className="table">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Access</th>
                  <th>Updated</th>
                </tr>
              </thead>
              <tbody>
                {ownedRooms.map((room) => (
                  <tr key={room.id}>
                    <td>{room.name}</td>
                    <td><StatusBadge>{room.visibility.toLowerCase().replace("_", " ")}</StatusBadge></td>
                    <td>{formatDate(room.updatedAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </DataTable>
        </Panel>
      </section>
    </AppShell>
  );
}

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