import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { notFound } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, MessageSquare, ArrowRight, Clock, User } from "lucide-react";

export default async function ConversationsPage({ params, searchParams }: {
  params: Promise<{ botId: string }>;
  searchParams: Promise<{ page?: string }>;
}) {
  const session = await getServerSession(authOptions);
  const userId = (session?.user as any)?.id as string;
  const { botId } = await params;
  const { page: pageStr } = await searchParams;
  const page = Math.max(0, parseInt(pageStr ?? "0"));
  const PER_PAGE = 25;

  const bot = await prisma.bot.findFirst({ where: { id: botId, userId } });
  if (!bot) notFound();

  const [conversations, total] = await Promise.all([
    prisma.conversation.findMany({
      where: { botId },
      orderBy: { lastMessageAt: "desc" },
      take: PER_PAGE,
      skip: page * PER_PAGE,
      include: {
        messages: { take: 1, orderBy: { createdAt: "desc" } },
        lead: true,
        _count: { select: { messages: true } },
      },
    }),
    prisma.conversation.count({ where: { botId } }),
  ]);

  const totalPages = Math.ceil(total / PER_PAGE);

  return (
    <div className="p-8 bg-dots min-h-full">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6 animate-fade-up">
        <Link href={`/bots/${botId}`} className="text-slate-600 hover:text-slate-300 transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div className="flex-1">
          <h1 className="text-2xl font-black text-white">Conversatii</h1>
          <p className="text-slate-500 text-sm mt-0.5">{bot.name} — {total} conversatii totale</p>
        </div>
        <div className="flex items-center gap-2 text-xs text-slate-500">
          <MessageSquare className="w-4 h-4" />
          <span>{total} total</span>
        </div>
      </div>

      <div className="rounded-2xl border border-white/[0.07] overflow-hidden animate-fade-up" style={{ animationDelay: "80ms", background: "var(--bg-card)" }}>
        {conversations.length === 0 ? (
          <div className="py-20 text-center">
            <div className="w-14 h-14 bg-blue-500/10 border border-blue-500/20 rounded-2xl flex items-center justify-center mx-auto mb-4 animate-float">
              <MessageSquare className="w-7 h-7 text-blue-400" />
            </div>
            <p className="text-white font-semibold mb-1">Nicio conversatie inca</p>
            <p className="text-slate-500 text-sm">Odata ce clientii folosesc chatbotul, conversatiile apar aici.</p>
          </div>
        ) : (
          <>
            {/* Table header */}
            <div className="grid grid-cols-[2fr_1fr_80px_100px_40px] px-5 py-3 border-b border-white/[0.05] text-xs font-semibold text-slate-600 uppercase tracking-wider"
              style={{ background: "rgba(255,255,255,0.01)" }}>
              <div>Vizitator</div>
              <div>Canal</div>
              <div>Mesaje</div>
              <div>Data</div>
              <div />
            </div>

            <div className="divide-y divide-white/[0.04]">
              {conversations.map((conv, i) => {
                const lastMsg = conv.messages[0];
                const visitorName = conv.lead?.name ?? conv.lead?.email ?? `Anonim #${conv.sessionId.slice(0, 6)}`;
                const hasLead = !!(conv.lead?.name || conv.lead?.email);
                return (
                  <Link key={conv.id} href={`/bots/${botId}/conversations/${conv.id}`}
                    className="grid grid-cols-[2fr_1fr_80px_100px_40px] px-5 py-3.5 hover:bg-white/[0.025] transition-all items-center group animate-fade-up"
                    style={{ animationDelay: `${120 + i * 30}ms` }}>
                    <div>
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded-full bg-indigo-500/15 border border-indigo-500/20 flex items-center justify-center shrink-0">
                          <User className="w-3 h-3 text-indigo-400" />
                        </div>
                        <p className="text-sm font-medium text-white group-hover:text-indigo-300 transition-colors">{visitorName}</p>
                        {hasLead && (
                          <span className="text-[9px] bg-pink-500/15 text-pink-400 border border-pink-500/20 px-1.5 py-0.5 rounded-full font-semibold">LEAD</span>
                        )}
                      </div>
                      {lastMsg && (
                        <p className="text-xs text-slate-600 truncate mt-0.5 ml-8 max-w-64">
                          <span className={lastMsg.role === "USER" ? "text-slate-600" : "text-indigo-600"}>
                            {lastMsg.role === "USER" ? "Vizitator: " : "Bot: "}
                          </span>
                          {lastMsg.content.slice(0, 70)}{lastMsg.content.length > 70 ? "..." : ""}
                        </p>
                      )}
                    </div>

                    <div>
                      <span className={`text-xs px-2.5 py-1 rounded-full font-semibold ${
                        conv.channel === "WIDGET"
                          ? "bg-blue-500/10 text-blue-400 border border-blue-500/20"
                          : "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"
                      }`}>
                        {conv.channel === "WIDGET" ? "Widget" : "WhatsApp"}
                      </span>
                    </div>

                    <div className="text-sm text-slate-500">
                      {conv._count.messages}
                    </div>

                    <div className="flex items-center gap-1 text-xs text-slate-600">
                      <Clock className="w-3 h-3 shrink-0" />
                      {new Date(conv.lastMessageAt).toLocaleDateString("ro-RO", { day: "numeric", month: "short" })}
                    </div>

                    <div>
                      <ArrowRight className="w-4 h-4 text-slate-700 group-hover:text-indigo-400 group-hover:translate-x-0.5 transition-all" />
                    </div>
                  </Link>
                );
              })}
            </div>
          </>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-5">
          <p className="text-sm text-slate-500">
            {page * PER_PAGE + 1}–{Math.min((page + 1) * PER_PAGE, total)} din {total} conversatii
          </p>
          <div className="flex gap-2">
            {page > 0 && (
              <Link href={`?page=${page - 1}`}
                className="text-sm px-4 py-2 border border-white/[0.08] hover:border-indigo-500/30 text-slate-400 hover:text-white rounded-xl transition-all"
                style={{ background: "var(--bg-card)" }}>
                ← Anterior
              </Link>
            )}
            {page < totalPages - 1 && (
              <Link href={`?page=${page + 1}`}
                className="text-sm px-4 py-2 border border-white/[0.08] hover:border-indigo-500/30 text-slate-400 hover:text-white rounded-xl transition-all"
                style={{ background: "var(--bg-card)" }}>
                Urmator →
              </Link>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
