import { JsonCard } from "@/components/cards/JsonCard";
import SafetyNotesCard from "@/components/cards/SafetyNotesCard";
import { UserCard } from "@/components/cards/UserCard";
import { NavigationToolbar } from "@/components/common/NavigationToolbar";
import { RecentMessages } from "@/components/pages/inspector/RecentMessages";
import { RelevantModerationNotices } from "@/components/pages/inspector/RelevantModerationNotices";
import { RelevantObjects } from "@/components/pages/inspector/RelevantObjects";
import { RelevantReports } from "@/components/pages/inspector/RelevantReports";
import { UserActions } from "@/components/pages/inspector/UserActions";
import { Card, CardHeader } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import {
  fetchBotById,
  fetchBotsByUser,
  fetchMembershipsByUser,
  fetchNoticesByUser,
  fetchReports,
  fetchReportsAgainstUser,
  fetchReportsByUser,
  fetchServers,
  fetchSnapshots,
  fetchStrikesByUser,
  fetchUserById,
  fetchUsersById,
  findDM,
} from "@/lib/db";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Bot } from "revolt-api";

export default async function User({
  params,
}: {
  params: { id: string; type: string };
}) {
  const user = await fetchUserById(params.id);
  if (!user) return notFound();

  const bot = user.bot ? await fetchBotById(user._id) : undefined;
  const botOwner = user.bot ? await fetchUserById(user.bot.owner) : undefined;

  // Fetch strikes and moderation alerts
  const strikes = await fetchStrikesByUser(user._id);
  const notices = await fetchNoticesByUser(user._id);

  // Fetch friends and bots
  const botIds = await fetchBotsByUser(user._id)
    .then((bots) => bots.map((bot) => bot._id))
    .catch(() => []);

  const relevantUsers = await fetchUsersById([
    ...botIds,
    ...(
      user.relations?.filter((relation) => relation.status === "Friend") ?? []
    ).map((relation) => relation._id),
  ]);

  relevantUsers.sort((a) => (a.bot ? -1 : 0));

  // Fetch server memberships
  const serverMemberships = await fetchMembershipsByUser(user._id).catch(
    () => []
  );
  const servers = await fetchServers({
    _id: {
      $in: serverMemberships.map((member) => member._id.server),
    },
  }).catch(() => []);

  // Fetch reports
  const reportsByUser = await fetchReportsByUser(user._id);
  const reportsAgainstUser = await fetchReportsAgainstUser(user._id);

  return (
    <div className="flex flex-col gap-2">
      <NavigationToolbar>Inspecting User</NavigationToolbar>

      <UserCard user={user} subtitle={user.status?.text ?? "No status set"} />
      <UserActions user={user} bot={bot as Bot} />
      <SafetyNotesCard objectId={user._id} type="user" />

      {user.profile?.content && (
        <Card>
          <CardHeader>
            <p>{user.profile?.content}</p>
          </CardHeader>
        </Card>
      )}

      {botOwner && (
        <Link href={`/panel/inspect/user/${botOwner!._id}`}>
          <UserCard user={botOwner} subtitle="Bot Owner" />
        </Link>
      )}

      <Separator />
      <RelevantModerationNotices
        userId={user._id}
        strikes={strikes}
        notices={notices}
      />

      <Separator />
      <RelevantObjects
        users={relevantUsers}
        servers={servers}
        userId={user._id}
      />

      <Separator />
      <RelevantReports byUser={reportsByUser} forUser={reportsAgainstUser} />

      <Separator />
      <RecentMessages userId={user._id} />

      <Separator />
      <JsonCard obj={user} />
    </div>
  );
}
