import { getAiUsageAggregates } from "@/lib/db/admin-queries"
import { StatsCard } from "@/components/dashboard/stats-card"
import { EmptyState } from "@/components/shared/empty-state"
import { Brain, BarChart3, Users } from "lucide-react"

export const dynamic = "force-dynamic"

export default async function AdminAiUsagePage() {
  const { byType, totalThisMonth, topUsers } = await getAiUsageAggregates()

  const sortedByType = [...byType].sort((a, b) => b.count - a.count)
  const maxTypeCount = sortedByType[0]?.count ?? 0

  return (
    <div className="min-h-full">
      {/* Heading */}
      <div className="mb-6">
        <h1 className="text-xl font-bold text-white">AI Usage</h1>
        <p className="text-sm text-white/40 mt-0.5">
          AI event volume across the platform
        </p>
      </div>

      {/* KPI */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4 mb-6">
        <StatsCard
          label="AI Calls This Month"
          value={totalThisMonth}
          sub="Across all accounts"
          icon={Brain}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-5">
        {/* ── Usage by type ───────────────────────────────────────────── */}
        <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
            <BarChart3 className="h-4 w-4 text-rose-400 shrink-0" />
            <h2 className="text-sm font-semibold text-white">Usage by type</h2>
          </div>

          {sortedByType.length === 0 ? (
            <EmptyState
              icon={BarChart3}
              title="No AI usage yet"
              description="AI event volume grouped by type will appear here once usage is recorded."
            />
          ) : (
            <div className="divide-y divide-white/[0.04]">
              {sortedByType.map((row) => (
                <div key={row.event_type} className="px-5 py-3.5">
                  <div className="flex items-center justify-between gap-3">
                    <span className="text-sm font-medium text-white truncate">
                      {row.event_type}
                    </span>
                    <span className="shrink-0 text-sm font-semibold tabular-nums text-white/70">
                      {row.count.toLocaleString()}
                    </span>
                  </div>
                  <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-white/[0.06]">
                    <div
                      className="h-full rounded-full bg-gradient-to-r from-rose-500 to-pink-500"
                      style={{
                        width: `${maxTypeCount ? Math.max(2, (row.count / maxTypeCount) * 100) : 0}%`,
                      }}
                    />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* ── Top consumers ───────────────────────────────────────────── */}
        <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
            <Users className="h-4 w-4 text-rose-400 shrink-0" />
            <h2 className="text-sm font-semibold text-white">Top consumers</h2>
            <span className="ml-auto text-xs text-white/30">This month</span>
          </div>

          {topUsers.length === 0 ? (
            <EmptyState
              icon={Users}
              title="No consumers yet"
              description="The accounts driving the most AI usage this month will be listed here."
            />
          ) : (
            <div className="divide-y divide-white/[0.04]">
              {topUsers.map((u, i) => (
                <div
                  key={u.user_id}
                  className="flex items-center gap-3 px-5 py-3.5 hover:bg-white/[0.02] transition-colors"
                >
                  <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-white/[0.04] text-[11px] font-semibold tabular-nums text-white/40">
                    {i + 1}
                  </span>
                  <span className="min-w-0 flex-1 truncate text-sm font-medium text-white">
                    {u.email}
                  </span>
                  <span className="shrink-0 text-sm font-semibold tabular-nums text-white/70">
                    {u.count.toLocaleString()}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
