import Link from "next/link";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { Avatar, Card, EmptyState, PageHeader, btn } from "@/components/ui";
import { fmtDateTime } from "@/lib/utils";
import { sendMessageAction } from "../actions";

export const metadata = { title: "Messages" };

export default async function MessagesPage({
  searchParams,
}: {
  searchParams: Promise<{ with?: string }>;
}) {
  const user = await requireUser();
  const { with: withUserId } = await searchParams;

  // conversation partners: accepted connections + anyone with message history
  const [connections, allMessages] = await Promise.all([
    db.connection.findMany({
      where: { status: "ACCEPTED", OR: [{ fromUserId: user.id }, { toUserId: user.id }] },
      include: {
        fromUser: { select: { id: true, name: true, organization: true, avatarUrl: true } },
        toUser: { select: { id: true, name: true, organization: true, avatarUrl: true } },
      },
    }),
    db.directMessage.findMany({
      where: { OR: [{ fromUserId: user.id }, { toUserId: user.id }] },
      orderBy: { createdAt: "desc" },
    }),
  ]);

  type Peer = { id: string; name: string; organization: string | null; avatarUrl: string | null };
  const peers = new Map<string, Peer>();
  for (const c of connections) {
    const p = c.fromUserId === user.id ? c.toUser : c.fromUser;
    peers.set(p.id, p);
  }
  const lastByPeer = new Map<string, (typeof allMessages)[number]>();
  const unreadByPeer = new Map<string, number>();
  for (const m of allMessages) {
    const peerId = m.fromUserId === user.id ? m.toUserId : m.fromUserId;
    if (!lastByPeer.has(peerId)) lastByPeer.set(peerId, m);
    if (m.toUserId === user.id && !m.readAt) unreadByPeer.set(peerId, (unreadByPeer.get(peerId) ?? 0) + 1);
  }
  const conversationList = [...peers.values()].sort((a, b) => {
    const la = lastByPeer.get(a.id)?.createdAt.getTime() ?? 0;
    const lb = lastByPeer.get(b.id)?.createdAt.getTime() ?? 0;
    return lb - la;
  });

  const activePeer = withUserId ? peers.get(withUserId) : conversationList[0];
  let thread: typeof allMessages = [];
  if (activePeer) {
    thread = allMessages
      .filter((m) => m.fromUserId === activePeer.id || m.toUserId === activePeer.id)
      .reverse();
    // opening the thread marks their messages read
    await db.directMessage.updateMany({
      where: { fromUserId: activePeer.id, toUserId: user.id, readAt: null },
      data: { readAt: new Date() },
    });
  }

  return (
    <div>
      <PageHeader
        title="Messages"
        sub="1:1 conversations with your accepted connections."
        action={<Link href="/me/networking" className={btn.secondary}>🤝 Find people</Link>}
      />

      {conversationList.length === 0 ? (
        <EmptyState
          title="No conversations yet"
          body="Connect with fellow attendees in Networking — once they accept, you can message here."
          action={<Link href="/me/networking" className={btn.primary}>Open networking</Link>}
        />
      ) : (
        <div className="grid gap-4 lg:grid-cols-[300px_1fr]">
          <Card className="h-fit p-3">
            {conversationList.map((p) => {
              const last = lastByPeer.get(p.id);
              const unread = unreadByPeer.get(p.id) ?? 0;
              const active = activePeer?.id === p.id;
              return (
                <Link
                  key={p.id}
                  href={`/me/messages?with=${p.id}`}
                  className={`flex items-center gap-3 rounded-xl px-3 py-2.5 transition ${active ? "bg-indigo-500/10" : "hover:bg-white/60"}`}
                >
                  <Avatar name={p.name} src={p.avatarUrl} size={10} />
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center justify-between gap-2">
                      <span className={`truncate text-sm ${unread ? "font-bold text-zinc-100" : "font-semibold text-zinc-200"}`}>{p.name}</span>
                      {unread > 0 && <span className="rounded-full bg-indigo-500 px-1.5 text-[10px] font-bold text-white">{unread}</span>}
                    </div>
                    <div className="truncate text-xs text-zinc-500">{last ? last.body : p.organization ?? "Say hello 👋"}</div>
                  </div>
                </Link>
              );
            })}
          </Card>

          {activePeer ? (
            <Card className="flex min-h-[28rem] flex-col p-0">
              <div className="flex items-center gap-3 border-b border-zinc-800/60 px-5 py-3">
                <Avatar name={activePeer.name} src={activePeer.avatarUrl} size={9} />
                <div>
                  <div className="text-sm font-bold text-zinc-100">{activePeer.name}</div>
                  <div className="text-xs text-zinc-500">{activePeer.organization ?? ""}</div>
                </div>
              </div>
              <div className="flex-1 space-y-2.5 overflow-y-auto px-5 py-4">
                {thread.length === 0 && <p className="text-sm text-zinc-500">No messages yet — break the ice below.</p>}
                {thread.map((m) => (
                  <div key={m.id} className={`max-w-[75%] ${m.fromUserId === user.id ? "ml-auto" : ""}`}>
                    <div className={`rounded-2xl px-3.5 py-2 text-sm ${m.fromUserId === user.id ? "bg-gradient-to-r from-indigo-500 to-violet-500 text-white" : "border border-zinc-800/60 bg-white/60 text-zinc-200"}`}>
                      {m.body}
                    </div>
                    <div className={`mt-0.5 text-[10px] text-zinc-600 ${m.fromUserId === user.id ? "text-right" : ""}`}>{fmtDateTime(m.createdAt)}</div>
                  </div>
                ))}
              </div>
              <form action={sendMessageAction.bind(null, activePeer.id)} className="flex gap-2 border-t border-zinc-800/60 p-3">
                <input
                  name="body"
                  required
                  autoComplete="off"
                  placeholder={`Message ${activePeer.name.split(" ")[0]}…`}
                  className="flex-1 rounded-xl border border-white/80 bg-white/70 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-600 shadow-sm outline-none focus:border-indigo-400"
                />
                <button className={btn.primary}>Send</button>
              </form>
            </Card>
          ) : (
            <EmptyState title="Pick a conversation" body="Choose someone from the list." />
          )}
        </div>
      )}
    </div>
  );
}
