import { getLocale, getTranslations, setRequestLocale } from "next-intl/server";
import { Link } from "@/i18n/navigation";
import { listAdminThreads, localeName } from "@/lib/chat";
import { formatMoney } from "@/lib/money";
import { requireAdmin } from "@/lib/session";

export default async function AdminChatInboxPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  setRequestLocale(locale);
  await requireAdmin();
  const t = await getTranslations("chat");
  const loc = await getLocale();
  const threads = await listAdminThreads();

  return (
    <div className="space-y-4">
      <h1 className="page-title">{t("inbox")}</h1>
      <p className="text-muted">{t("inboxHint")}</p>
      <div className="card divide-y divide-line">
        {threads.length === 0 ? <p className="p-5 text-sm text-muted">{t("inboxEmpty")}</p> : null}
        {threads.map((thread) => (
          <Link
            key={thread.userId}
            href={`/admin/chat/${thread.userId}`}
            className="block p-4 hover:bg-background"
          >
            <div className="flex items-start justify-between gap-3">
              <div>
                <p className="font-semibold">
                  {thread.name}{" "}
                  {thread.adminUnread > 0 ? (
                    <span className="ms-2 rounded-full bg-brand px-2 py-0.5 text-xs text-white">
                      {thread.adminUnread}
                    </span>
                  ) : null}
                </p>
                <p className="text-sm text-muted">
                  {thread.email} · {localeName(thread.userLocale)}
                </p>
                <p className="mt-1 line-clamp-2 text-sm">{thread.lastBody ?? t("empty")}</p>
              </div>
              <p className="shrink-0 text-xs text-muted">{formatMoney(thread.balanceMicro, loc)}</p>
            </div>
          </Link>
        ))}
      </div>
      <Link href="/admin" className="text-brand">
        {t("back")}
      </Link>
    </div>
  );
}
