import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { sendChatMessageAction } from "@/server/actions/chat";

export default async function ChatPage({
  searchParams,
}: {
  searchParams: Promise<{ key?: string; title?: string; error?: string }>;
}) {
  const session = await auth();
  if (!session?.user?.email) redirect("/login");
  const sp = await searchParams;
  const key = sp.key || "";
  const title = sp.title || "Chat";
  if (!key) {
    return (
      <div>
        <h1 className="text-2xl font-semibold">Chat</h1>
        <p className="mt-2 text-white/60">
          Abre un chat desde un perfil de contratista o una orden.
        </p>
      </div>
    );
  }

  const thread = await prisma.chatThread.findUnique({
    where: { key },
    include: { messages: { orderBy: { createdAt: "asc" } } },
  });

  return (
    <div className="mx-auto max-w-xl">
      <h1 className="text-2xl font-semibold">{title}</h1>
      {sp.error && (
        <p className="mt-2 text-sm text-red-300">{sp.error}</p>
      )}
      <div className="card mt-4 max-h-96 space-y-3 overflow-y-auto">
        {(thread?.messages || []).map((m) => (
          <div
            key={m.id}
            className={`rounded-xl px-3 py-2 text-sm ${
              m.fromEmail === session.user.email
                ? "ml-8 bg-[var(--lime)]/20"
                : "mr-8 bg-white/5"
            }`}
          >
            <p className="text-xs text-white/50">{m.fromName}</p>
            <p>{m.text}</p>
          </div>
        ))}
        {!thread?.messages?.length && (
          <p className="text-sm text-white/50">Sin mensajes. Di hola.</p>
        )}
      </div>
      <form action={sendChatMessageAction} className="mt-3 flex gap-2">
        <input type="hidden" name="key" value={key} />
        <input type="hidden" name="title" value={title} />
        <input className="input" name="text" placeholder="Mensaje…" required />
        <button className="btn-primary" type="submit">
          Enviar
        </button>
      </form>
      <p className="mt-2 text-xs text-white/40">
        Filtro activo: no telefonos, emails ni enlaces externos.
      </p>
    </div>
  );
}
