import { ChannelCard } from "@/components/cards/ChannelCard";
import { JsonCard } from "@/components/cards/JsonCard";
import SafetyNotesCard from "@/components/cards/SafetyNotesCard";
import { ServerCard } from "@/components/cards/ServerCard";
import { UserCard } from "@/components/cards/UserCard";
import { NavigationToolbar } from "@/components/common/NavigationToolbar";
import { RecentMessages } from "@/components/pages/inspector/RecentMessages";
import { Separator } from "@/components/ui/separator";
import { fetchChannelById, fetchServerById, fetchUsersById } from "@/lib/db";
import Link from "next/link";
import { notFound } from "next/navigation";

export default async function Message({ params }: { params: { id: string } }) {
  const channel = await fetchChannelById(params.id);
  if (!channel) return notFound();

  const server =
    channel.channel_type === "TextChannel"
      ? await fetchServerById(channel.server)
      : undefined;

  const participants =
    channel.channel_type === "DirectMessage" || channel.channel_type === "Group"
      ? await fetchUsersById(channel.recipients)
      : [];

  return (
    <div className="flex flex-col gap-2">
      <NavigationToolbar>Inspecting Channel</NavigationToolbar>
      <ChannelCard channel={channel!} subtitle="Channel" />

      {server && (
        <Link href={`/panel/inspect/server/${server._id}`}>
          <ServerCard server={server} subtitle="Server" />
        </Link>
      )}

      <SafetyNotesCard objectId={channel._id} type="channel" />

      {participants.length ? (
        <>
          <Separator />
          {participants.map((user) => (
            <Link key={user._id} href={`/panel/inspect/user/${user._id}`}>
              <UserCard user={user} subtitle="Member" />
            </Link>
          ))}
        </>
      ) : undefined}

      <Separator />
      <RecentMessages
        query={{ channel: channel._id }}
        users={participants.length ? participants : true}
      />

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