import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { PLAN_LIMITS } from "@/lib/usage";
import Link from "next/link";
import { Users, Bot, MessageSquare, TrendingUp, CreditCard, Activity, Crown, Zap, ArrowRight } from "lucide-react";

const PLAN_PRICES: Record<string, number> = { FREE: 0, STARTER: 29, PRO: 79, ENTERPRISE: 299 };

// Anthropic claude-haiku-4-5 pricing (USD)
const COST_PER_MESSAGE_USD = 0.001; // ~550 input tok + ~150 output tok
const USD_TO_EUR = 0.92;

export default async function AdminPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string; search?: string }>;
}) {
  const sp = await searchParams;
  const page = Math.max(0, parseInt(sp.page ?? "0"));
  const search = sp.search?.trim() ?? "";
  const PER_PAGE = 30;

  // Aggregate stats
  const [
    totalUsers,
    totalBots,
    totalConversations,
    totalMessages,
    subscriptions,
    recentUsers,
  ] = await Promise.all([
    prisma.user.count(),
    prisma.bot.count(),
    prisma.conversation.count(),
    prisma.message.count(),
    prisma.subscription.findMany({ select: { plan: true, messagesUsed: true } }),
    prisma.user.findMany({
      orderBy: { createdAt: "desc" },
      take: 5,
      select: { email: true, createdAt: true },
    }),
  ]);

  const usersWithSearch = await prisma.user.findMany({
    where: search ? { OR: [
      { email: { contains: search } },
      { name: { contains: search } },
    ]} : undefined,
    orderBy: { createdAt: "desc" },
    skip: page * PER_PAGE,
    take: PER_PAGE,
    include: {
      subscription: true,
      _count: { select: { bots: true } },
      bots: {
        select: {
          id: true,
          name: true,
          status: true,
          _count: { select: { conversations: true } },
        },
        orderBy: { updatedAt: "desc" },
        take: 3,
      },
    },
  });

  const totalUsersCount = await prisma.user.count({
    where: search ? { OR: [
      { email: { contains: search } },
      { name: { contains: search } },
    ]} : undefined,
  });

  const planCounts: Record<string, number> = {};
  const planMessagesUsed: Record<string, number> = {};
  let mrr = 0;
  let totalMessagesUsed = 0;
  for (const s of subscriptions) {
    planCounts[s.plan] = (planCounts[s.plan] ?? 0) + 1;
    planMessagesUsed[s.plan] = (planMessagesUsed[s.plan] ?? 0) + s.messagesUsed;
    mrr += PLAN_PRICES[s.plan] ?? 0;
    totalMessagesUsed += s.messagesUsed;
  }

  const anthropicCostUSD = totalMessagesUsed * COST_PER_MESSAGE_USD;
  const anthropicCostEUR = anthropicCostUSD * USD_TO_EUR;
  const profitEUR = mrr - anthropicCostEUR;
  const marginPct = mrr > 0 ? Math.round((profitEUR / mrr) * 100) : 0;

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

  const statCards = [
    { label: "Utilizatori totali", value: totalUsers,         icon: Users,          color: "indigo" },
    { label: "Chatboti activi",    value: totalBots,          icon: Bot,            color: "violet" },
    { label: "Conversatii",        value: totalConversations, icon: MessageSquare,  color: "blue" },
    { label: "Mesaje totale",      value: totalMessages,      icon: Activity,       color: "cyan" },
    { label: "MRR estimat (€)",    value: `${mrr}€`,          icon: TrendingUp,     color: "emerald" },
    { label: "Mesaje folosite/luna", value: totalMessagesUsed, icon: Zap,           color: "amber" },
  ];

  return (
    <div className="p-8 max-w-7xl mx-auto">
      <div className="mb-8 animate-fade-up">
        <h1 className="text-3xl font-black text-white">Admin Dashboard</h1>
        <p className="text-slate-500 mt-1">Overview complet al platformei Dialpilot</p>
      </div>

      {/* Stats grid */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mb-8">
        {statCards.map(({ label, value, icon: Icon, color }, i) => (
          <div key={label} className="rounded-2xl border border-white/[0.07] p-4 animate-fade-up"
            style={{ background: "var(--bg-card)", animationDelay: `${i * 50}ms` }}>
            <div className={`w-8 h-8 rounded-xl bg-${color}-500/10 flex items-center justify-center mb-3`}>
              <Icon className={`w-4 h-4 text-${color}-400`} />
            </div>
            <p className="text-xl font-black text-white">{typeof value === "number" ? value.toLocaleString() : value}</p>
            <p className="text-xs text-slate-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      {/* Cost Tracker */}
      <div className="rounded-2xl border border-amber-500/20 p-5 mb-8 animate-fade-up" style={{ background: "linear-gradient(135deg, rgba(245,158,11,0.06) 0%, rgba(99,102,241,0.06) 100%)", animationDelay: "150ms" }}>
        <div className="flex items-center justify-between mb-4">
          <div>
            <p className="text-xs font-bold text-amber-400 uppercase tracking-wider">Cost Tracker — Anthropic</p>
            <p className="text-[11px] text-slate-500 mt-0.5">claude-haiku-4-5 · ~$0.001/mesaj · reset lunar</p>
          </div>
          <span className={`text-xs font-bold px-3 py-1 rounded-xl ${marginPct >= 80 ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" : marginPct >= 60 ? "bg-amber-500/10 text-amber-400 border border-amber-500/20" : "bg-red-500/10 text-red-400 border border-red-500/20"}`}>
            Marja: {marginPct}%
          </span>
        </div>

        <div className="grid grid-cols-4 gap-4 mb-4">
          {[
            { label: "Mesaje folosite luna asta", value: totalMessagesUsed.toLocaleString(), sub: "toate planurile", color: "slate" },
            { label: "Cost Anthropic estimat", value: `$${anthropicCostUSD.toFixed(2)}`, sub: `≈ ${anthropicCostEUR.toFixed(2)}€`, color: "amber" },
            { label: "Venituri MRR", value: `${mrr}€`, sub: "abonamente active", color: "emerald" },
            { label: "Profit estimat", value: `${profitEUR.toFixed(2)}€`, sub: `marja ${marginPct}%`, color: profitEUR >= 0 ? "emerald" : "red" },
          ].map(({ label, value, sub, color }) => (
            <div key={label} className="rounded-xl border border-white/[0.06] p-3.5" style={{ background: "var(--bg-panel)" }}>
              <p className={`text-xl font-black text-${color}-400`}>{value}</p>
              <p className="text-xs text-white mt-0.5 font-medium">{label}</p>
              <p className="text-[10px] text-slate-600 mt-0.5">{sub}</p>
            </div>
          ))}
        </div>

        {/* Per-plan cost breakdown */}
        <div className="border-t border-white/[0.05] pt-4">
          <p className="text-[10px] text-slate-600 uppercase tracking-wider font-bold mb-3">Cost pe plan</p>
          <div className="grid grid-cols-4 gap-3">
            {(["FREE","STARTER","PRO","ENTERPRISE"] as const).map(plan => {
              const msgs = planMessagesUsed[plan] ?? 0;
              const costEur = msgs * COST_PER_MESSAGE_USD * USD_TO_EUR;
              const rev = (planCounts[plan] ?? 0) * PLAN_PRICES[plan];
              const profit = rev - costEur;
              const colors: Record<string, string> = { FREE:"slate", STARTER:"indigo", PRO:"violet", ENTERPRISE:"amber" };
              const c = colors[plan];
              return (
                <div key={plan} className="rounded-xl p-3 border border-white/[0.04]" style={{ background: "rgba(255,255,255,0.02)" }}>
                  <p className={`text-[10px] font-black text-${c}-400 uppercase tracking-wider mb-2`}>{plan}</p>
                  <div className="space-y-1 text-[11px]">
                    <div className="flex justify-between"><span className="text-slate-600">Mesaje</span><span className="text-slate-400">{msgs.toLocaleString()}</span></div>
                    <div className="flex justify-between"><span className="text-slate-600">Cost AI</span><span className="text-amber-400">{costEur.toFixed(3)}€</span></div>
                    <div className="flex justify-between"><span className="text-slate-600">Venit</span><span className="text-emerald-400">{rev}€</span></div>
                    <div className="flex justify-between border-t border-white/[0.05] pt-1 mt-1"><span className="text-slate-500 font-bold">Profit</span><span className={`font-bold ${profit >= 0 ? "text-emerald-400" : "text-red-400"}`}>{profit.toFixed(2)}€</span></div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Plan distribution + recent signups */}
      <div className="grid grid-cols-3 gap-4 mb-8">
        <div className="col-span-2 rounded-2xl border border-white/[0.07] p-5" style={{ background: "var(--bg-card)" }}>
          <p className="text-xs font-bold text-white uppercase tracking-wider mb-4">Distributie planuri</p>
          <div className="space-y-2.5">
            {(["FREE","STARTER","PRO","ENTERPRISE"] as const).map(plan => {
              const count = planCounts[plan] ?? 0;
              const pct = totalUsers > 0 ? Math.round((count / totalUsers) * 100) : 0;
              const colors: Record<string, string> = { FREE: "slate", STARTER: "indigo", PRO: "violet", ENTERPRISE: "amber" };
              const c = colors[plan];
              return (
                <div key={plan} className="flex items-center gap-3">
                  <span className={`text-xs font-bold text-${c}-400 w-20 shrink-0`}>{plan}</span>
                  <div className="flex-1 h-2 bg-white/[0.05] rounded-full overflow-hidden">
                    <div className={`h-2 bg-${c}-500 rounded-full transition-all`} style={{ width: `${pct}%` }} />
                  </div>
                  <span className="text-xs text-slate-400 w-10 text-right shrink-0">{count}</span>
                  <span className="text-xs text-slate-600 w-8 text-right shrink-0">{pct}%</span>
                </div>
              );
            })}
          </div>
          <div className="mt-4 pt-4 border-t border-white/[0.05]">
            <p className="text-xs text-slate-500">
              MRR: <span className="text-emerald-400 font-bold">{mrr}€</span>
              {" "}&bull;{" "}
              Platitori: <span className="text-white font-bold">{(planCounts.STARTER ?? 0) + (planCounts.PRO ?? 0) + (planCounts.ENTERPRISE ?? 0)}</span>
            </p>
          </div>
        </div>

        <div className="rounded-2xl border border-white/[0.07] p-5" style={{ background: "var(--bg-card)" }}>
          <p className="text-xs font-bold text-white uppercase tracking-wider mb-4">Inregistrari recente</p>
          <div className="space-y-3">
            {recentUsers.map(u => (
              <div key={u.email} className="flex items-center gap-2">
                <div className="w-6 h-6 rounded-full bg-indigo-500/15 flex items-center justify-center text-xs font-bold text-indigo-400 shrink-0">
                  {u.email[0].toUpperCase()}
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-white truncate">{u.email}</p>
                  <p className="text-[10px] text-slate-600">{new Date(u.createdAt).toLocaleDateString("ro-RO")}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Users table */}
      <div className="rounded-2xl border border-white/[0.07] overflow-hidden" style={{ background: "var(--bg-card)" }}>
        <div className="px-5 py-4 border-b border-white/[0.05] flex items-center justify-between">
          <p className="text-sm font-bold text-white">Utilizatori ({totalUsersCount})</p>
          <form method="GET">
            <input
              name="search"
              defaultValue={search}
              placeholder="Cauta email / nume..."
              className="text-xs rounded-xl px-3 py-2 border border-white/[0.08] text-white placeholder-slate-600 focus:outline-none focus:border-indigo-500/50"
              style={{ background: "var(--bg-panel)" }}
            />
          </form>
        </div>

        {/* Header */}
        <div className="grid grid-cols-[2fr_1fr_80px_80px_100px_120px_40px] px-5 py-3 text-xs font-semibold text-slate-600 uppercase tracking-wider border-b border-white/[0.04]"
          style={{ background: "rgba(255,255,255,0.01)" }}>
          <div>Utilizator</div>
          <div>Plan</div>
          <div>Boti</div>
          <div>Mesaje</div>
          <div>Inregistrat</div>
          <div>Boti activi</div>
          <div />
        </div>

        <div className="divide-y divide-white/[0.03]">
          {usersWithSearch.map((user, i) => {
            const plan = user.subscription?.plan ?? "FREE";
            const used = user.subscription?.messagesUsed ?? 0;
            const limit = PLAN_LIMITS[plan as keyof typeof PLAN_LIMITS]?.messages ?? 100;
            const pct = limit === Infinity ? 0 : Math.min(100, Math.round((used / limit) * 100));
            const planColors: Record<string, string> = { FREE:"slate", STARTER:"indigo", PRO:"violet", ENTERPRISE:"amber" };
            const pc = planColors[plan] ?? "slate";

            return (
              <div key={user.id ?? i}
                className="grid grid-cols-[2fr_1fr_80px_80px_100px_120px_40px] px-5 py-3.5 items-center hover:bg-white/[0.015] transition-colors group">
                {/* User */}
                <div className="flex items-center gap-2.5 min-w-0">
                  <div className="w-7 h-7 rounded-full bg-indigo-500/15 flex items-center justify-center text-xs font-bold text-indigo-400 shrink-0">
                    {(user.name ?? user.email)[0].toUpperCase()}
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-white truncate">{user.name ?? "—"}</p>
                    <p className="text-xs text-slate-500 truncate">{user.email}</p>
                  </div>
                </div>

                {/* Plan */}
                <div>
                  <span className={`text-xs font-bold px-2 py-1 rounded-lg bg-${pc}-500/10 text-${pc}-400 border border-${pc}-500/20`}>
                    {plan}
                  </span>
                </div>

                {/* Bot count */}
                <div className="text-sm text-slate-400">{user._count.bots}</div>

                {/* Messages */}
                <div>
                  <p className="text-xs text-white">{used.toLocaleString()}</p>
                  {limit !== Infinity && (
                    <div className="w-12 h-1 bg-white/[0.06] rounded-full mt-1">
                      <div className={`h-1 rounded-full ${pct > 80 ? "bg-amber-500" : "bg-indigo-500"}`} style={{ width: `${pct}%` }} />
                    </div>
                  )}
                </div>

                {/* Registered */}
                <div className="text-xs text-slate-500">
                  {new Date(user.createdAt).toLocaleDateString("ro-RO")}
                </div>

                {/* Bot names */}
                <div className="space-y-0.5">
                  {user.bots.map(b => (
                    <p key={b.id} className="text-[10px] text-slate-500 truncate">
                      <span className={`inline-block w-1.5 h-1.5 rounded-full mr-1 ${b.status === "ACTIVE" ? "bg-emerald-400" : "bg-slate-600"}`} />
                      {b.name}
                    </p>
                  ))}
                </div>

                {/* View link */}
                <div>
                  <Link href={`/admin/users/${user.id}`}
                    className="text-slate-700 hover:text-indigo-400 transition-colors opacity-0 group-hover:opacity-100">
                    <ArrowRight className="w-4 h-4" />
                  </Link>
                </div>
              </div>
            );
          })}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-5 py-4 border-t border-white/[0.05]">
            <p className="text-xs text-slate-500">{page * PER_PAGE + 1}–{Math.min((page + 1) * PER_PAGE, totalUsersCount)} din {totalUsersCount}</p>
            <div className="flex gap-2">
              {page > 0 && (
                <Link href={`?page=${page - 1}${search ? `&search=${search}` : ""}`}
                  className="text-xs px-3 py-1.5 border border-white/[0.08] rounded-lg text-slate-400 hover:text-white transition-all">
                  ← Anterior
                </Link>
              )}
              {page < totalPages - 1 && (
                <Link href={`?page=${page + 1}${search ? `&search=${search}` : ""}`}
                  className="text-xs px-3 py-1.5 border border-white/[0.08] rounded-lg text-slate-400 hover:text-white transition-all">
                  Urmator →
                </Link>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
