import type { Filter, WithId } from "mongodb";
import { Message, User } from "revolt-api";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../../ui/card";
import { fetchMessages, fetchMessagesByUser, fetchUsersById } from "@/lib/db";
import { CompactMessage } from "../../cards/CompactMessage";

type Props = { users?: boolean | User[] } & (
  | {
      query: Filter<Message>;
    }
  | {
      userId: string;
    }
);

export async function RecentMessages(props: Props) {
  let recentMessages = (
    await ((props as { query: {} }).query
      ? fetchMessages((props as { query: Filter<Message> }).query)
      : fetchMessagesByUser((props as { userId: string }).userId)
    ).catch(() => [])
  ).reverse();

  const userList = (
    props.users === true
      ? await fetchUsersById([...new Set(recentMessages.map((x) => x.author))])
      : Array.isArray(props.users)
      ? props.users
      : []
  ).reduce((prev, next) => {
    prev[next._id] = next;
    return prev;
  }, {} as Record<string, any>);

  return (
    <Card>
      <CardHeader>
        <CardTitle>Recent Messages</CardTitle>
        <CardDescription>Overview of recent messages</CardDescription>
      </CardHeader>
      <CardContent>
        {/* enter reason for fetching */}
        {!recentMessages.length && (
          <>
            <h2 className="text-sm text-center pb-2 text-gray-400">
              No messages found
            </h2>
            <h3 className="text-xs text-center pb-2 text-gray-400">
              You may be lacking permissions.
            </h3>
          </>
        )}
        {recentMessages.map((message) => (
          <CompactMessage
            key={message._id}
            message={message}
            hideUser={Object.keys(userList).length === 0}
            users={userList}
          />
        ))}
      </CardContent>
    </Card>
  );
}
