import { SnapshotContent } from "revolt-api";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../ui/card";
import { fetchUsersById } from "@/lib/db";
import { CompactMessage } from "./CompactMessage";

export async function MessageContextCard({
  snapshot,
}: {
  snapshot: SnapshotContent & { _type: "Message" };
}) {
  const userIds = [
    ...new Set(
      [
        ...(snapshot._leading_context ?? []),
        ...(snapshot._prior_context ?? []),
        snapshot,
      ].map((x) => x.author)
    ),
  ];

  const users = await fetchUsersById(userIds).then((users) =>
    users.reduce((prev, next) => {
      prev[next._id] = next;
      return prev;
    }, {} as Record<string, any>)
  );

  return (
    <Card>
      <CardHeader>
        <CardTitle>Message(s)</CardTitle>
        <CardDescription>Reported Content</CardDescription>
      </CardHeader>
      <CardContent>
        <div className="opacity-40">
          {[...(snapshot._prior_context ?? [])].reverse()?.map((message) => (
            <CompactMessage key={message._id} message={message} users={users} />
          ))}
        </div>
        <CompactMessage message={snapshot} users={users} />
        <div className="opacity-40">
          {snapshot._leading_context?.map((message) => (
            <CompactMessage key={message._id} message={message} users={users} />
          ))}
        </div>
      </CardContent>
    </Card>
  );
}
