import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { PLAN_LIMITS, Plan } from "@/lib/usage";
import Link from "next/link";
import { Bot, MessageSquare, TrendingUp, Plus, ArrowRight, Zap, Users, CheckCircle2, Circle, Sparkles } from "lucide-react";

export default async function DashboardPage() {
  const session = await getServerSession(authOptions);
  const userId = (session?.user as any)?.id as string;

  const [bots, subscription, totalMessages, totalLeads] = await Promise.all([
    prisma.bot.findMany({ where: { userId }, orderBy: { updatedAt: "desc" }, take: 5 }),
    prisma.subscription.findUnique({ where: { userId } }),
    prisma.message.count({ where: { conversation: { bot: { userId } } } }),
    prisma.lead.count({ where: { bot: { userId } } }),
  ]);

  const plan = (subscription?.plan ?? "FREE") as Plan;
  const limit = PLAN_LIMITS[plan].messages;
  const used = subscription?.messagesUsed ?? 0;
  const pct = limit === Infinity ? 0 : Math.min(100, Math.round((used / limit) * 100));
  const firstName = session?.user?.name?.split(" ")[0] ?? "acolo";

  const stats = [
    { label: "Chatboti activi", value: bots.filter(b => b.status === "ACTIVE").length, sub: `din ${bots.length} total`, icon: Bot, color: "indigo", glow: "rgba(99,102,241,0.2)" },
    { label: "Mesaje luna aceasta", value: used, sub: `din ${limit === Infinity ? "∞" : limit.toLocaleString()} incluse`, icon: MessageSquare, color: "violet", glow: "rgba(139,92,246,0.2)" },
    { label: "Total mesaje", value: totalMessages, sub: "toate timpurile", icon: TrendingUp, color: "cyan", glow: "rgba(34,211,238,0.2)" },
    { label: "Leaduri capturate", value: totalLeads, sub: "toate timpurile", icon: Users, color: "pink", glow: "rgba(236,72,153,0.2)" },
  ];

  return (
    <div className="p-8 min-h-full bg-dots">
      {/* Ambient glows */}
      <div className="fixed top-0 right-0 w-[500px] h-[400px] bg-indigo-600/5 rounded-full blur-3xl pointer-events-none" />
      <div className="fixed bottom-0 left-1/2 w-[400px] h-[300px] bg-violet-600/5 rounded-full blur-3xl pointer-events-none" />

      {/* Header */}
      <div className="relative mb-10 animate-fade-up flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2 mb-2">
            <Sparkles className="w-4 h-4 text-indigo-400" />
            <span className="text-xs text-indigo-400 font-semibold uppercase tracking-widest">Tablou de bord</span>
          </div>
          <h1 className="text-3xl font-black text-white tracking-tight">
            Buna, <span className="text-gradient">{firstName}</span>! 👋
          </h1>
          <p className="text-slate-500 mt-1.5 text-sm">Iata ce se intampla cu chatbotii tai astazi.</p>
        </div>
        <Link
          href="/bots/new"
          className="btn-glow flex items-center gap-2 bg-gradient-to-r from-indigo-600 to-violet-600 text-white px-5 py-2.5 rounded-xl text-sm font-bold shadow-lg shadow-indigo-500/25"
        >
          <Plus className="w-4 h-4" />
          Bot nou
        </Link>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        {stats.map(({ label, value, sub, icon: Icon, color, glow }, i) => (
          <div
            key={label}
            className="card-glow animate-fade-up scan-container group cursor-default"
            style={{ animationDelay: `${i * 80}ms` }}
          >
            <div
              className="relative rounded-2xl p-5 border border-white/[0.07] hover:border-white/[0.12] transition-all duration-300 overflow-hidden"
              style={{ background: "var(--bg-card)" }}
            >
              {/* Background glow */}
              <div
                className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500"
                style={{ background: `radial-gradient(circle at 30% 30%, ${glow}, transparent 60%)` }}
              />

              <div className={`relative w-10 h-10 rounded-xl mb-4 flex items-center justify-center bg-${color}-500/10 border border-${color}-500/20 group-hover:scale-110 transition-transform duration-300`}
                style={{ boxShadow: `0 0 20px ${glow}` }}>
                <Icon className={`w-4.5 h-4.5 text-${color}-400`} />
              </div>

              <p className="stat-value text-2xl font-black text-white tracking-tight"
                style={{ animationDelay: `${i * 80 + 200}ms` }}>
                {value.toLocaleString()}
              </p>
              <p className="text-xs font-medium text-slate-400 mt-1">{label}</p>
              <p className="text-[10px] text-slate-600 mt-0.5">{sub}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Usage bar */}
      {plan !== "ENTERPRISE" && (
        <div className="animate-fade-up delay-400 relative rounded-2xl p-5 mb-8 border border-white/[0.07] hover:border-white/[0.1] transition-all overflow-hidden"
          style={{ background: "var(--bg-card)" }}>
          <div className="absolute inset-0 bg-gradient-to-r from-indigo-600/5 to-violet-600/5 pointer-events-none" />
          <div className="relative flex items-center justify-between mb-4">
            <div>
              <div className="flex items-center gap-2">
                <span className="text-sm font-semibold text-white">Utilizare plan</span>
                <span className="text-xs bg-indigo-500/15 text-indigo-300 border border-indigo-500/25 px-2 py-0.5 rounded-full font-bold">{plan}</span>
              </div>
              <p className="text-xs text-slate-500 mt-0.5">{used.toLocaleString()} din {limit === Infinity ? "nelimitat" : limit.toLocaleString()} mesaje</p>
            </div>
            <Link href="/billing" className="text-xs font-semibold text-indigo-400 hover:text-white bg-indigo-500/10 hover:bg-indigo-500/20 border border-indigo-500/20 px-3 py-1.5 rounded-lg transition-all">
              Upgrade →
            </Link>
          </div>
          <div className="relative w-full bg-white/[0.05] rounded-full h-2 overflow-hidden">
            <div
              className="absolute inset-y-0 left-0 rounded-full transition-all duration-1000"
              style={{
                width: `${Math.max(pct, pct > 0 ? 2 : 0)}%`,
                background: pct > 80
                  ? "linear-gradient(90deg, #ef4444, #f97316)"
                  : "linear-gradient(90deg, #6366f1, #8b5cf6, #22d3ee)",
                boxShadow: `0 0 12px ${pct > 80 ? "rgba(239,68,68,0.5)" : "rgba(99,102,241,0.5)"}`,
              }}
            />
            {/* Shimmer on bar */}
            <div className="absolute inset-0 animate-shimmer opacity-30"
              style={{ background: "linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent)", backgroundSize: "200% 100%" }} />
          </div>
          {pct > 80 && (
            <p className="text-xs text-amber-400 mt-2.5 flex items-center gap-1.5">
              <Zap className="w-3 h-3" /> Aproape de limita — considera un upgrade
            </p>
          )}
        </div>
      )}

      {/* Onboarding checklist */}
      {bots.length === 0 && (
        <div className="animate-fade-up delay-300 relative rounded-2xl p-6 mb-8 border border-indigo-500/20 overflow-hidden"
          style={{ background: "linear-gradient(135deg, rgba(99,102,241,0.08), rgba(139,92,246,0.05))" }}>
          <div className="absolute inset-0 bg-grid opacity-30 pointer-events-none" />
          <div className="relative flex items-center gap-3 mb-5">
            <div className="w-10 h-10 bg-indigo-500/20 border border-indigo-500/30 rounded-xl flex items-center justify-center shadow-lg shadow-indigo-500/10">
              <Zap className="w-5 h-5 text-indigo-400" />
            </div>
            <div>
              <h2 className="font-black text-white text-base">Incepe in 4 pasi simpli</h2>
              <p className="text-xs text-slate-500">Configureaza primul tau chatbot AI in mai putin de 10 minute</p>
            </div>
          </div>
          <div className="relative space-y-2.5">
            {[
              { done: true,  label: "Cont creat",                desc: "Esti logat si gata de start",               href: null },
              { done: false, label: "Creeaza primul bot",        desc: "Alege un nume si tipul de business",        href: "/bots/new" },
              { done: false, label: "Adauga baza de cunostinte", desc: "Informatii despre firma, servicii, preturi", href: null },
              { done: false, label: "Instaleaza pe site",        desc: "Copy-paste un script si gata",              href: null },
            ].map((step, idx) => (
              <div key={idx}
                className={`flex items-center gap-3 p-3.5 rounded-xl border transition-all animate-fade-up ${step.done ? "bg-emerald-500/8 border-emerald-500/20" : "bg-white/[0.02] border-white/[0.06] hover:border-indigo-500/25"}`}
                style={{ animationDelay: `${500 + idx * 80}ms` }}>
                {step.done
                  ? <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
                  : <Circle className="w-5 h-5 text-slate-700 shrink-0" />
                }
                <div className="flex-1">
                  <p className={`text-sm font-semibold ${step.done ? "text-emerald-400 line-through decoration-emerald-600" : "text-white"}`}>{step.label}</p>
                  <p className="text-xs text-slate-500 mt-0.5">{step.desc}</p>
                </div>
                {step.href && !step.done && (
                  <Link href={step.href} className="btn-glow text-xs bg-gradient-to-r from-indigo-600 to-violet-600 text-white px-3 py-1.5 rounded-lg font-bold transition-all shrink-0">
                    Incepe →
                  </Link>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Bots list */}
      <div className="animate-fade-up delay-500 rounded-2xl border border-white/[0.07] overflow-hidden"
        style={{ background: "var(--bg-card)" }}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-white/[0.05]">
          <div className="flex items-center gap-2">
            <Bot className="w-4 h-4 text-indigo-400" />
            <h2 className="font-semibold text-white text-sm">Chatbotii tai recenti</h2>
          </div>
          <Link href="/bots" className="text-xs text-slate-500 hover:text-indigo-400 transition-colors font-medium">
            Vezi toti →
          </Link>
        </div>

        {bots.length === 0 ? (
          <div className="py-16 text-center">
            <div className="w-14 h-14 bg-indigo-500/10 border border-indigo-500/20 rounded-2xl flex items-center justify-center mx-auto mb-4 animate-float">
              <Bot className="w-7 h-7 text-indigo-400" />
            </div>
            <p className="text-white font-semibold mb-1">Niciun chatbot inca</p>
            <p className="text-slate-500 text-sm mb-6">Urmeaza pasii de mai sus pentru a incepe.</p>
            <Link href="/bots/new" className="btn-glow inline-flex items-center gap-2 bg-gradient-to-r from-indigo-600 to-violet-600 text-white px-5 py-2.5 rounded-xl text-sm font-bold shadow-lg shadow-indigo-500/20">
              <Plus className="w-4 h-4" /> Creeaza chatbot
            </Link>
          </div>
        ) : (
          <div className="divide-y divide-white/[0.04]">
            {bots.map((bot, i) => (
              <Link key={bot.id} href={`/bots/${bot.id}`}
                className="flex items-center justify-between px-5 py-3.5 hover:bg-white/[0.025] transition-all duration-200 group animate-fade-up"
                style={{ animationDelay: `${600 + i * 60}ms` }}>
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 bg-gradient-to-br from-indigo-500/15 to-violet-500/10 border border-indigo-500/20 rounded-xl flex items-center justify-center text-base group-hover:scale-110 transition-transform">
                    🤖
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-white group-hover:text-indigo-300 transition-colors">{bot.name}</p>
                    <p className="text-xs text-slate-500">{bot.description ?? "Fara descriere"}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <span className={`relative text-xs px-2.5 py-1 rounded-full font-semibold flex items-center gap-1.5 ${
                    bot.status === "ACTIVE"
                      ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"
                      : "bg-white/[0.04] text-slate-500 border border-white/[0.08]"
                  }`}>
                    {bot.status === "ACTIVE" && (
                      <span className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-pulse" />
                    )}
                    {bot.status === "ACTIVE" ? "Activ" : "Draft"}
                  </span>
                  <ArrowRight className="w-4 h-4 text-slate-600 group-hover:text-indigo-400 group-hover:translate-x-1 transition-all" />
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
