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 { Settings, Code, BarChart2, MessageSquare, Users, BookOpen, FlaskConical, Zap, TrendingUp, CalendarCheck, ListChecks } from "lucide-react";
import { DeleteBotButton } from "@/components/dashboard/DeleteBotButton";
import { BotStatusToggle } from "@/components/dashboard/BotStatusToggle";
import { CloneBotButton } from "@/components/dashboard/CloneBotButton";

const ESCALATION = ["nu pot", "nu stiu", "nu am informatii", "nu am acces", "contactati", "sunati", "nu pot ajuta"];

function calcScore(msgs: { role: string; content: string }[]) {
  const assistantMsgs = msgs.filter(m => m.role === "ASSISTANT");
  if (assistantMsgs.length === 0) return null;
  const escalated = assistantMsgs.filter(m => ESCALATION.some(p => m.content.toLowerCase().includes(p))).length;
  return Math.round(((assistantMsgs.length - escalated) / assistantMsgs.length) * 100);
}

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

  const bot = await prisma.bot.findFirst({
    where: { id: botId, userId },
    include: {
      config: true, deployment: true, knowledgeBase: true,
      _count: { select: { conversations: true, leads: true, bookings: true } },
    },
  });
  if (!bot) notFound();

  const [recentMessages, last7Messages] = await Promise.all([
    prisma.message.findMany({
      where: { conversation: { botId }, createdAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } },
      select: { role: true, content: true },
    }),
    prisma.message.count({ where: { conversation: { botId }, createdAt: { gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) } } }),
  ]);

  const score = calcScore(recentMessages);
  const hasKnowledge = !!bot.knowledgeBase?.content?.trim();
  const color = bot.config?.primaryColor ?? "#6366f1";

  const actions = [
    { href: `/bots/${botId}/test`,          icon: FlaskConical,  label: "Testeaza",         desc: "Chat live in dashboard",         grad: "from-emerald-500/10 to-teal-500/10",     border: "border-emerald-500/20",  text: "text-emerald-400" },
    { href: `/bots/${botId}/configure`,     icon: Settings,      label: "Configurare",      desc: "Personalitate si aspect",        grad: "from-indigo-500/10 to-violet-500/10",    border: "border-indigo-500/20",   text: "text-indigo-400" },
    { href: `/bots/${botId}/knowledge`,     icon: BookOpen,      label: "Cunostinte",       desc: hasKnowledge ? `${bot.knowledgeBase!.content.length} car.` : "Adauga info firma", grad: hasKnowledge ? "from-indigo-500/10 to-violet-500/10" : "from-amber-500/10 to-orange-500/10", border: hasKnowledge ? "border-indigo-500/20" : "border-amber-500/20", text: hasKnowledge ? "text-indigo-400" : "text-amber-400" },
    { href: `/bots/${botId}/bookings`,      icon: CalendarCheck, label: "Rezervari",        desc: `${bot._count.bookings} rezervari`, grad: "from-violet-500/10 to-purple-500/10",   border: "border-violet-500/20",   text: "text-violet-400" },
    { href: `/bots/${botId}/conversations`, icon: MessageSquare, label: "Conversatii",      desc: `${bot._count.conversations} totale`, grad: "from-blue-500/10 to-cyan-500/10",    border: "border-blue-500/20",     text: "text-blue-400" },
    { href: `/bots/${botId}/leads`,         icon: Users,         label: "Leaduri",          desc: `${bot._count.leads} capturate`,  grad: "from-pink-500/10 to-rose-500/10",        border: "border-pink-500/20",     text: "text-pink-400" },
    { href: `/bots/${botId}/analytics`,     icon: BarChart2,     label: "Statistici",       desc: "Grafice si rapoarte",            grad: "from-orange-500/10 to-amber-500/10",     border: "border-orange-500/20",   text: "text-orange-400" },
    { href: `/bots/${botId}/responses`,      icon: ListChecks,    label: "Raspunsuri",       desc: "Raspunsuri predefinite",         grad: "from-teal-500/10 to-cyan-500/10",        border: "border-teal-500/20",     text: "text-teal-400" },
    { href: `/bots/${botId}/deploy`,        icon: Code,          label: "Instalare",        desc: "7 metode de integrare",          grad: "from-slate-500/10 to-slate-600/10",      border: "border-slate-500/20",    text: "text-slate-400" },
  ];

  return (
    <div className="p-8 bg-dots min-h-full">
      {/* Ambient glow */}
      <div className="fixed top-0 right-0 w-[500px] h-[400px] pointer-events-none" style={{ background: `radial-gradient(circle, ${color}10 0%, transparent 60%)` }} />

      {/* Header */}
      <div className="flex items-start justify-between mb-6 animate-fade-up">
        <div className="flex items-center gap-4">
          <div className="relative w-14 h-14 shrink-0">
            <div className="absolute inset-0 rounded-2xl blur-md opacity-50" style={{ backgroundColor: color }} />
            <div className="relative w-14 h-14 rounded-2xl flex items-center justify-center text-2xl border shadow-xl"
              style={{ backgroundColor: `${color}20`, borderColor: `${color}40`, boxShadow: `0 8px 30px ${color}20` }}>
              🤖
            </div>
            {bot.status === "ACTIVE" && (
              <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-emerald-400 rounded-full border-2 border-[#0b0f1a]">
                <div className="absolute inset-0 rounded-full bg-emerald-400 animate-ping opacity-60" />
              </div>
            )}
          </div>
          <div>
            <h1 className="text-2xl font-black text-white">{bot.name}</h1>
            <p className="text-slate-500 text-sm mt-0.5">{bot.description ?? "Nicio descriere"}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <CloneBotButton botId={botId} />
          <BotStatusToggle botId={botId} status={bot.status} />
          <DeleteBotButton botId={botId} />
        </div>
      </div>

      {/* Draft warning */}
      {bot.status === "DRAFT" && (
        <div className="animate-fade-up delay-100 bg-amber-500/8 border border-amber-500/25 rounded-2xl p-4 mb-5 scan-container">
          <p className="text-sm font-bold text-amber-300">⚠️ Botul nu este activ — clientii nu il pot folosi!</p>
          <p className="text-xs text-amber-500/80 mt-0.5">
            Dupa ce l-ai configurat si testat, apasa butonul "Draft — Activeaza" din dreapta sus.
          </p>
        </div>
      )}

      {/* Knowledge nudge */}
      {!hasKnowledge && (
        <Link href={`/bots/${botId}/knowledge`}
          className="animate-fade-up delay-100 flex items-center justify-between bg-indigo-500/8 border border-indigo-500/20 hover:border-indigo-500/40 rounded-2xl p-4 mb-5 transition-all group">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 bg-indigo-500/15 rounded-xl flex items-center justify-center group-hover:scale-110 transition-transform">
              <BookOpen className="w-4 h-4 text-indigo-400" />
            </div>
            <div>
              <p className="text-sm font-semibold text-indigo-300">Adauga baza de cunostinte</p>
              <p className="text-xs text-indigo-500/80">Fara informatii specifice, botul raspunde generic.</p>
            </div>
          </div>
          <span className="text-indigo-400 text-sm font-bold group-hover:translate-x-1 transition-transform shrink-0">Adauga →</span>
        </Link>
      )}

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
        {[
          { label: "Conversatii",     value: bot._count.conversations, icon: MessageSquare, color: "blue" },
          { label: "Mesaje (7 zile)", value: last7Messages,             icon: TrendingUp,   color: "violet" },
          { label: "Leaduri",         value: bot._count.leads,          icon: Users,        color: "pink" },
          { label: "Scor performanta",value: score !== null ? `${score}%` : "N/A", icon: Zap, scoreVal: score, color: "emerald" },
        ].map(({ label, value, icon: Icon, scoreVal, color: c }, i) => (
          <div key={label}
            className="card-glow animate-fade-up rounded-2xl p-4 border border-white/[0.07] hover:border-white/[0.12] transition-all group"
            style={{ background: "var(--bg-card)", animationDelay: `${200 + i * 60}ms` }}>
            <div className={`w-8 h-8 rounded-xl bg-${c}-500/10 border border-${c}-500/20 flex items-center justify-center mb-3 group-hover:scale-110 transition-transform`}>
              <Icon className={`w-3.5 h-3.5 text-${c}-400`} />
            </div>
            <p className={`text-2xl font-black ${
              scoreVal !== undefined && scoreVal !== null
                ? scoreVal > 80 ? "text-emerald-400" : scoreVal > 50 ? "text-amber-400" : "text-red-400"
                : "text-white"
            }`}>{value}</p>
            <p className="text-xs text-slate-500 mt-1">{label}</p>
          </div>
        ))}
      </div>

      {/* Action cards */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-5">
        {actions.map(({ href, icon: Icon, label, desc, grad, border, text }, i) => (
          <Link key={href} href={href}
            className={`group card-glow bg-gradient-to-br ${grad} border ${border} rounded-2xl p-4 transition-all duration-200 hover:scale-[1.02] hover:shadow-lg animate-fade-up`}
            style={{ animationDelay: `${400 + i * 50}ms` }}>
            <div className="w-8 h-8 rounded-xl flex items-center justify-center mb-3 bg-white/[0.05] group-hover:scale-110 transition-transform">
              <Icon className={`w-4 h-4 ${text}`} />
            </div>
            <p className="font-bold text-white text-sm">{label}</p>
            <p className="text-xs text-slate-500 mt-0.5">{desc}</p>
          </Link>
        ))}
      </div>

      {/* Embed code */}
      <div className="animate-fade-up delay-600 rounded-2xl p-5 border border-white/[0.06] hover:border-white/[0.1] transition-all"
        style={{ background: "var(--bg-base)" }}>
        <div className="flex items-center justify-between mb-3">
          <p className="text-sm font-semibold text-white">Cod de instalare rapid</p>
          <Link href={`/bots/${botId}/deploy`} className="text-xs text-indigo-400 hover:text-indigo-300 font-medium transition-colors">7 metode →</Link>
        </div>
        <code className="block text-emerald-400 text-xs font-mono overflow-x-auto bg-white/[0.03] border border-white/[0.05] rounded-xl p-3 select-all">
          {`<script src="${process.env.NEXTAUTH_URL ?? "https://dialpilot.com"}/widget/embed.js" data-bot-id="${botId}"></script>`}
        </code>
      </div>
    </div>
  );
}
