import { Users, MessageSquareText, Wrench, TrendingUp, Crown, CircleUser } from "lucide-react";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";

export const dynamic = "force-dynamic";

export const metadata = {
  title: "Phân tích vận hành — Admin",
};

async function getAnalytics() {
  const now = new Date();
  const dayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
  const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);

  // Plan distribution
  const planAgg = await prisma.user.groupBy({
    by: ["plan"],
    _count: { _all: true },
  });
  const planCounts: Record<string, number> = {};
  let totalUsers = 0;
  for (const p of planAgg) {
    const k = p.plan ?? "FREE";
    planCounts[k] = p._count._all;
    totalUsers += p._count._all;
  }
  const freeCount = planCounts["FREE"] ?? 0;
  const premiumCount = planCounts["PREMIUM"] ?? 0;
  const conversionRate = totalUsers > 0 ? (premiumCount / totalUsers) * 100 : 0;

  // Top 10 tools by use trong 24h
  const top24h = await prisma.toolHistory.groupBy({
    by: ["toolKey"],
    where: { createdAt: { gte: dayAgo } },
    _count: { _all: true },
    orderBy: { _count: { toolKey: "desc" } },
    take: 10,
  });

  // Top 10 tools 7d
  const top7d = await prisma.toolHistory.groupBy({
    by: ["toolKey"],
    where: { createdAt: { gte: weekAgo } },
    _count: { _all: true },
    orderBy: { _count: { toolKey: "desc" } },
    take: 10,
  });

  // AI conversation by tool 24h
  const aiByTool = await prisma.aIConversation.groupBy({
    by: ["toolKey"],
    where: { createdAt: { gte: dayAgo } },
    _count: { _all: true },
    orderBy: { _count: { toolKey: "desc" } },
    take: 10,
  });

  // Upgrade requests funnel
  const upgradeAgg = await prisma.upgradeRequest.groupBy({
    by: ["status"],
    _count: { _all: true },
  });
  const upgradeCounts: Record<string, number> = {};
  for (const u of upgradeAgg) upgradeCounts[u.status] = u._count._all;
  const pending = upgradeCounts["PENDING"] ?? 0;
  const approved = upgradeCounts["APPROVED"] ?? 0;
  const rejected = upgradeCounts["REJECTED"] ?? 0;

  // Activity counts
  const [aiMessages24h, aiMessages7d, toolUses24h, toolUses7d, signups24h, signups7d] =
    await Promise.all([
      prisma.aIMessage.count({ where: { createdAt: { gte: dayAgo }, role: "user" } }),
      prisma.aIMessage.count({ where: { createdAt: { gte: weekAgo }, role: "user" } }),
      prisma.toolHistory.count({ where: { createdAt: { gte: dayAgo } } }),
      prisma.toolHistory.count({ where: { createdAt: { gte: weekAgo } } }),
      prisma.user.count({ where: { createdAt: { gte: dayAgo } } }),
      prisma.user.count({ where: { createdAt: { gte: weekAgo } } }),
    ]);

  // Top 10 users theo tool use 7d (engagement)
  const topActiveUsers = await prisma.toolHistory.groupBy({
    by: ["userId"],
    where: { createdAt: { gte: weekAgo } },
    _count: { _all: true },
    orderBy: { _count: { userId: "desc" } },
    take: 10,
  });
  const userIds = topActiveUsers.map((u) => u.userId);
  const userInfos =
    userIds.length > 0
      ? await prisma.user.findMany({
          where: { id: { in: userIds } },
          select: { id: true, name: true, email: true, plan: true },
        })
      : [];
  const userMap = new Map(userInfos.map((u) => [u.id, u]));

  return {
    totalUsers,
    freeCount,
    premiumCount,
    conversionRate,
    top24h,
    top7d,
    aiByTool,
    pending,
    approved,
    rejected,
    aiMessages24h,
    aiMessages7d,
    toolUses24h,
    toolUses7d,
    signups24h,
    signups7d,
    topActiveUsers: topActiveUsers.map((u) => ({
      ...u,
      info: userMap.get(u.userId),
    })),
  };
}

const TOOL_LABELS: Record<string, string> = {
  "tu-vi-tron-doi": "Tử Vi Trọn Đời",
  "tu-tru": "Tứ Trụ",
  "than-so-hoc": "Thần Số Học",
  "cung-hoang-dao": "Cung Hoàng Đạo",
  "12-con-giap": "12 Con Giáp",
  "phong-thuy-nha": "Phong Thuỷ Nhà",
  "lich-am-duong": "Lịch Âm Dương",
  "xem-ngay-tot": "Ngày Tốt",
  "tuoi-ket-hon": "Tuổi Kết Hôn",
  "hop-tuoi-lam-an": "Hợp Tuổi Làm Ăn",
  "so-dien-thoai": "Số Điện Thoại",
  "so-mang-60-tuoi": "60 Hoa Giáp",
  "mau-sac-phong-thuy": "Màu Phong Thuỷ",
  "nam-xay-nha": "Năm Xây Nhà",
  "ban-tay-hinh-long": "Tướng Lòng Bàn Tay",
  "dat-ten-con": "Đặt Tên Con",
  "ten-cong-ty": "Tên Công Ty",
  "giai-mong": "Giải Mộng",
  "kinh-dich-ai": "Kinh Dịch",
  "van-menh": "Vận Mệnh",
  "tu-vi-ngay": "Tử Vi Ngày",
  "tu-vi-nam": "Tử Vi Năm",
  "thu-vien-ai": "Thư Viện",
  "palmistry-vision": "Tướng Tay (vision)",
  "tu-vi-qa": "Q&A Lá Số",
  "kinh-dich": "Kinh Dịch",
};

function toolLabel(key: string): string {
  return TOOL_LABELS[key] ?? key;
}

function StatCard({
  label,
  value,
  hint,
  Icon,
  accent,
}: {
  label: string;
  value: string | number;
  hint?: string;
  Icon: typeof Users;
  accent?: "gold" | "emerald" | "rose";
}) {
  return (
    <div className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
      <div className="flex items-center justify-between">
        <span className="text-ink-muted text-[11px] tracking-[0.18em] uppercase">{label}</span>
        <Icon
          className={
            accent === "emerald"
              ? "h-4 w-4 text-emerald-400/70"
              : accent === "rose"
                ? "h-4 w-4 text-rose-400/70"
                : "text-brand-gold/60 h-4 w-4"
          }
        />
      </div>
      <div className="font-display text-ink-primary mt-2 text-3xl font-semibold">{value}</div>
      {hint ? <div className="text-ink-muted mt-1 text-xs">{hint}</div> : null}
    </div>
  );
}

function BarRow({ label, count, max }: { label: string; count: number; max: number }) {
  const pct = max > 0 ? (count / max) * 100 : 0;
  return (
    <div className="flex items-center gap-3">
      <div className="text-ink-secondary w-32 shrink-0 truncate text-xs lg:w-48 lg:text-sm">
        {label}
      </div>
      <div className="bg-bg-inset h-2 flex-1 overflow-hidden rounded-full">
        <div className="bg-brand-gold h-full" style={{ width: `${Math.max(pct, 2)}%` }} />
      </div>
      <div className="text-ink-primary font-display w-10 text-right text-sm font-semibold">
        {count}
      </div>
    </div>
  );
}

export default async function AdminAnalyticsPage() {
  await requireAdmin();
  const a = await getAnalytics();

  const max24h = a.top24h.length > 0 ? a.top24h[0]._count._all : 1;
  const max7d = a.top7d.length > 0 ? a.top7d[0]._count._all : 1;
  const maxAi = a.aiByTool.length > 0 ? a.aiByTool[0]._count._all : 1;

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-ink-primary text-2xl font-semibold lg:text-3xl">
          Phân tích vận hành
        </h1>
        <p className="text-ink-secondary mt-1 text-sm">
          Bức tranh tổng thể: phễu chuyển đổi, tool nào hot, AI dùng nhiều ở đâu.
        </p>
      </div>

      {/* Plan distribution + Conversion funnel */}
      <section className="mb-8">
        <h2 className="font-display text-ink-primary mb-3 text-lg font-semibold">
          Phễu chuyển đổi
        </h2>
        <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
          <StatCard label="Tổng user" value={a.totalUsers} Icon={Users} />
          <StatCard
            label="Free"
            value={a.freeCount}
            hint={`${((a.freeCount / Math.max(a.totalUsers, 1)) * 100).toFixed(1)}%`}
            Icon={CircleUser}
          />
          <StatCard
            label="Premium"
            value={a.premiumCount}
            hint={`${a.conversionRate.toFixed(1)}% conversion`}
            Icon={Crown}
            accent="emerald"
          />
          <StatCard
            label="Đang chờ duyệt"
            value={a.pending}
            hint={`${a.approved} duyệt · ${a.rejected} từ chối`}
            Icon={TrendingUp}
            accent={a.pending > 0 ? "rose" : "gold"}
          />
        </div>
      </section>

      {/* Activity */}
      <section className="mb-8">
        <h2 className="font-display text-ink-primary mb-3 text-lg font-semibold">
          Hoạt động gần đây
        </h2>
        <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
          <StatCard
            label="Đăng ký 24h"
            value={a.signups24h}
            hint={`${a.signups7d} trong 7 ngày`}
            Icon={Users}
          />
          <StatCard
            label="Tool use 24h"
            value={a.toolUses24h}
            hint={`${a.toolUses7d} trong 7 ngày`}
            Icon={Wrench}
          />
          <StatCard
            label="AI message 24h"
            value={a.aiMessages24h}
            hint={`${a.aiMessages7d} trong 7 ngày`}
            Icon={MessageSquareText}
          />
        </div>
      </section>

      {/* Top tools 24h + 7d */}
      <section className="mb-8 grid gap-4 lg:grid-cols-2">
        <div className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
          <h3 className="font-display text-ink-primary mb-4 text-base font-semibold">
            Top 10 tool — 24h
          </h3>
          {a.top24h.length === 0 ? (
            <p className="text-ink-muted text-sm">Chưa có hoạt động.</p>
          ) : (
            <div className="space-y-2.5">
              {a.top24h.map((t) => (
                <BarRow
                  key={t.toolKey}
                  label={toolLabel(t.toolKey)}
                  count={t._count._all}
                  max={max24h}
                />
              ))}
            </div>
          )}
        </div>

        <div className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
          <h3 className="font-display text-ink-primary mb-4 text-base font-semibold">
            Top 10 tool — 7 ngày
          </h3>
          {a.top7d.length === 0 ? (
            <p className="text-ink-muted text-sm">Chưa có hoạt động.</p>
          ) : (
            <div className="space-y-2.5">
              {a.top7d.map((t) => (
                <BarRow
                  key={t.toolKey}
                  label={toolLabel(t.toolKey)}
                  count={t._count._all}
                  max={max7d}
                />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* AI by tool */}
      <section className="mb-8">
        <div className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
          <h3 className="font-display text-ink-primary mb-4 text-base font-semibold">
            Hội thoại AI theo tool — 24h
          </h3>
          {a.aiByTool.length === 0 ? (
            <p className="text-ink-muted text-sm">Chưa có hội thoại nào trong 24h.</p>
          ) : (
            <div className="space-y-2.5">
              {a.aiByTool.map((t) => (
                <BarRow
                  key={t.toolKey}
                  label={toolLabel(t.toolKey)}
                  count={t._count._all}
                  max={maxAi}
                />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* Top active users */}
      <section className="mb-8">
        <div className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
          <h3 className="font-display text-ink-primary mb-4 text-base font-semibold">
            Top 10 user dùng nhiều nhất — 7 ngày
          </h3>
          {a.topActiveUsers.length === 0 ? (
            <p className="text-ink-muted text-sm">Chưa có dữ liệu.</p>
          ) : (
            <div className="divide-stroke-subtle/50 divide-y">
              {a.topActiveUsers.map((u, i) => (
                <div key={u.userId} className="flex items-center gap-3 py-2.5">
                  <div className="text-brand-gold/60 font-display w-6 text-sm font-bold">
                    #{i + 1}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="text-ink-primary truncate text-sm font-medium">
                      {u.info?.name ?? u.info?.email ?? u.userId.slice(0, 8)}
                    </div>
                    <div className="text-ink-muted truncate text-xs">{u.info?.email}</div>
                  </div>
                  {u.info?.plan === "PREMIUM" ? (
                    <span className="rounded-full border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-300">
                      Premium
                    </span>
                  ) : (
                    <span className="text-ink-muted text-[10px]">Free</span>
                  )}
                  <div className="text-ink-primary font-display w-12 text-right text-sm font-semibold">
                    {u._count._all}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
