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, User, Bot, Mail, Phone, Clock, MessageSquare } from "lucide-react";

export default async function ConversationDetailPage({ params }: {
  params: Promise<{ botId: string; conversationId: string }>;
}) {
  const session = await getServerSession(authOptions);
  const userId = (session?.user as any)?.id as string;
  const { botId, conversationId } = await params;

  const conversation = await prisma.conversation.findFirst({
    where: { id: conversationId, bot: { userId } },
    include: {
      bot: { include: { config: true } },
      messages: { orderBy: { createdAt: "asc" } },
      lead: true,
    },
  });
  if (!conversation) notFound();

  const primaryColor = conversation.bot.config?.primaryColor ?? "#6366f1";
  const botName = conversation.bot.config?.botDisplayName ?? conversation.bot.name;
  const durationMin = Math.round(
    (new Date(conversation.lastMessageAt).getTime() - new Date(conversation.startedAt).getTime()) / 60000
  );

  return (
    <div className="p-8 max-w-3xl mx-auto">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6 animate-fade-up">
        <Link href={`/bots/${botId}/conversations`} className="text-slate-600 hover:text-slate-300 transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div className="flex-1">
          <h1 className="text-xl font-black text-white">Transcript conversatie</h1>
          <p className="text-slate-500 text-sm mt-0.5">
            {new Date(conversation.startedAt).toLocaleDateString("ro-RO", {
              weekday: "long", day: "numeric", month: "long", year: "numeric",
              hour: "2-digit", minute: "2-digit",
            })}
          </p>
        </div>
      </div>

      {/* Lead info */}
      {conversation.lead && (
        <div className="rounded-2xl border border-emerald-500/20 p-4 mb-5 flex items-center gap-4 animate-fade-up"
          style={{ background: "rgba(34,197,94,0.05)", animationDelay: "40ms" }}>
          <div className="w-10 h-10 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center shrink-0">
            <User className="w-5 h-5 text-emerald-400" />
          </div>
          <div className="flex-1">
            <p className="text-sm font-semibold text-emerald-300 mb-1">Lead capturat</p>
            <div className="flex flex-wrap gap-3 text-xs">
              {conversation.lead.name && (
                <span className="text-slate-300 font-medium">{conversation.lead.name}</span>
              )}
              {conversation.lead.email && (
                <a href={`mailto:${conversation.lead.email}`} className="flex items-center gap-1 text-indigo-400 hover:text-indigo-300">
                  <Mail className="w-3 h-3" />{conversation.lead.email}
                </a>
              )}
              {conversation.lead.phone && (
                <a href={`tel:${conversation.lead.phone}`} className="flex items-center gap-1 text-violet-400 hover:text-violet-300">
                  <Phone className="w-3 h-3" />{conversation.lead.phone}
                </a>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Stats bar */}
      <div className="grid grid-cols-3 gap-3 mb-5 animate-fade-up" style={{ animationDelay: "60ms" }}>
        {[
          { label: "Mesaje total", value: conversation.messages.length, icon: MessageSquare },
          { label: "Canal", value: conversation.channel === "WIDGET" ? "Site web" : "WhatsApp", icon: Bot },
          { label: "Durata", value: durationMin > 0 ? `${durationMin} min` : "< 1 min", icon: Clock },
        ].map(({ label, value, icon: Icon }) => (
          <div key={label} className="rounded-2xl border border-white/[0.07] p-4 text-center" style={{ background: "var(--bg-card)" }}>
            <p className="text-lg font-black text-white">{value}</p>
            <p className="text-xs text-slate-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      {/* Messages */}
      <div className="rounded-2xl border border-white/[0.07] overflow-hidden animate-fade-up" style={{ animationDelay: "80ms", background: "var(--bg-card)" }}>
        {/* Chat header */}
        <div className="flex items-center gap-3 px-5 py-3.5 border-b border-white/[0.06]"
          style={{ background: `linear-gradient(135deg, ${primaryColor}18, ${primaryColor}08)` }}>
          <div className="w-8 h-8 rounded-xl flex items-center justify-center text-sm border border-white/10"
            style={{ backgroundColor: primaryColor + "25" }}>🤖</div>
          <div>
            <span className="text-sm font-semibold text-white">{botName}</span>
            <p className="text-xs text-slate-500">{conversation.messages.length} mesaje</p>
          </div>
        </div>

        <div className="p-5 space-y-4 max-h-[65vh] overflow-y-auto">
          {conversation.messages.length === 0 ? (
            <p className="text-center text-slate-600 text-sm py-8">Niciun mesaj in aceasta conversatie.</p>
          ) : (
            conversation.messages.map((msg) => (
              <div key={msg.id} className={`flex items-end gap-2.5 ${msg.role === "USER" ? "justify-end" : "justify-start"}`}>
                {msg.role === "ASSISTANT" && (
                  <div className="w-7 h-7 rounded-xl shrink-0 flex items-center justify-center text-xs border border-white/10"
                    style={{ backgroundColor: primaryColor + "30" }}>🤖</div>
                )}
                <div>
                  <div className={`max-w-sm px-4 py-2.5 rounded-2xl text-sm leading-relaxed ${
                    msg.role === "USER"
                      ? "text-white rounded-br-sm"
                      : "border border-white/[0.07] text-slate-200 rounded-bl-sm"
                  }`} style={
                    msg.role === "USER"
                      ? { backgroundColor: primaryColor }
                      : { background: "rgba(255,255,255,0.04)" }
                  }>
                    <p style={{ whiteSpace: "pre-wrap" }}>{msg.content}</p>
                  </div>
                  <p className={`text-[10px] text-slate-600 mt-1 ${msg.role === "USER" ? "text-right" : "text-left"}`}>
                    {new Date(msg.createdAt).toLocaleTimeString("ro-RO", { hour: "2-digit", minute: "2-digit" })}
                  </p>
                </div>
                {msg.role === "USER" && (
                  <div className="w-7 h-7 rounded-xl shrink-0 bg-slate-700 border border-white/10 flex items-center justify-center">
                    <User className="w-3.5 h-3.5 text-slate-400" />
                  </div>
                )}
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
