import type { Metadata } from "next";
import Link from "next/link";
import { requireUser } from "@/lib/auth/dal";
import { listConversations } from "@/lib/messages/queries";
import { STATUS_SHARE_PREFIX } from "@/lib/messages/constants";

export const metadata: Metadata = {
  title: "Mesajlar",
  robots: { index: false, follow: false },
};

function previewText(body: string | undefined) {
  if (!body) return "Henüz mesaj yok";
  if (body.startsWith(STATUS_SHARE_PREFIX)) return "📸 Bir durum paylaştı";
  return body;
}

export default async function ConversationsPage() {
  const user = await requireUser();
  const conversations = await listConversations(user.id);

  return (
    <div className="mx-auto max-w-2xl px-6 py-14">
      <h1 className="mb-6 text-[26px]">Mesajlar</h1>

      {conversations.length === 0 ? (
        <p className="text-[13.5px] text-text-muted">
          Henüz bir konuşman yok. Bir üyenin profiline gidip &quot;Mesaj Gönder&quot;e basarak başlayabilirsin.
        </p>
      ) : (
        <div className="flex flex-col gap-2">
          {conversations.map(({ id, other, lastMessage, unreadCount }) => {
            const initials = (other.profile?.fullName ?? other.email).slice(0, 2).toUpperCase();
            return (
              <Link
                key={id}
                href={`/mesajlar/${id}`}
                className="flex items-center gap-3 rounded-xl border border-border bg-surface p-4 hover:border-accent"
              >
                <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-accent to-accent-2 text-[13px] font-bold text-white">
                  {initials}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center justify-between">
                    <span className="font-semibold text-[14.5px]">{other.profile?.fullName ?? other.email}</span>
                    {unreadCount > 0 && (
                      <span className="rounded-full bg-accent px-2 py-0.5 text-[10.5px] font-bold text-white">{unreadCount}</span>
                    )}
                  </div>
                  <p className="truncate text-[13px] text-text-muted">{previewText(lastMessage?.body)}</p>
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
