import { getPlatformActivity, getAdminAuditLog } from "@/lib/db/admin-queries"
import { EmptyState } from "@/components/shared/empty-state"
import { formatDate } from "@/lib/utils"
import {
  Activity, Shield, Ban, CreditCard, UserCog, Trash2, History,
} from "lucide-react"

export const dynamic = "force-dynamic"

// Type → small accent dot color for the platform activity list.
const typeDotColor: Record<string, string> = {
  rent_paid: "bg-emerald-400",
  rent_overdue: "bg-red-400",
  tenant_added: "bg-blue-400",
  tenant_removed: "bg-orange-400",
  maintenance_opened: "bg-yellow-400",
  maintenance_resolved: "bg-emerald-400",
  lease_created: "bg-indigo-400",
  lease_expiring: "bg-amber-400",
  expense_added: "bg-purple-400",
  property_added: "bg-cyan-400",
  inspection_completed: "bg-teal-400",
  vendor_added: "bg-pink-400",
  ai_action: "bg-violet-400",
}

// Audit action → colored pill classes.
const actionPill: Record<string, string> = {
  ban: "border-red-500/20 bg-red-500/10 text-red-400",
  plan_change: "border-indigo-500/20 bg-indigo-500/10 text-indigo-400",
  impersonate: "border-amber-500/20 bg-amber-500/10 text-amber-400",
  delete_user: "border-red-500/20 bg-red-500/10 text-red-400",
}
const DEFAULT_PILL = "border-white/[0.08] bg-white/[0.04] text-white/40"

// Audit action → icon.
const actionIcon: Record<string, React.ElementType> = {
  ban: Ban,
  plan_change: CreditCard,
  impersonate: UserCog,
  delete_user: Trash2,
}

function compactJson(value: unknown): string {
  if (value === null || value === undefined) return ""
  try {
    return typeof value === "string" ? value : JSON.stringify(value)
  } catch {
    return ""
  }
}

export default async function AdminActivityPage() {
  const [activity, audit] = await Promise.all([
    getPlatformActivity({ limit: 60 }),
    getAdminAuditLog({ limit: 40 }),
  ])

  return (
    <div className="min-h-full">
      {/* Heading */}
      <div className="mb-6">
        <h1 className="text-xl font-bold text-white">Activity & Audit</h1>
        <p className="text-sm text-white/40 mt-0.5">
          Platform-wide events and administrative actions
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-5">
        {/* ── Platform Activity ───────────────────────────────────────── */}
        <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">
            <Activity className="h-4 w-4 text-rose-400 shrink-0" />
            <h2 className="text-sm font-semibold text-white">Platform Activity</h2>
            <span className="ml-auto text-xs text-white/30">{activity.length} events</span>
          </div>

          {activity.length === 0 ? (
            <EmptyState
              icon={Activity}
              title="No activity yet"
              description="Platform-wide events from all accounts will appear here as users take actions."
            />
          ) : (
            <div className="divide-y divide-white/[0.04]">
              {activity.map((a) => (
                <div
                  key={a.id}
                  className="flex items-start gap-3 px-5 py-3.5 hover:bg-white/[0.02] transition-colors"
                >
                  <span
                    className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${
                      typeDotColor[a.type] ?? "bg-white/30"
                    }`}
                  />
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium text-white truncate">{a.title}</p>
                    <p className="text-xs text-white/40 truncate mt-0.5">
                      {a.user_email ?? "Unknown user"}
                    </p>
                  </div>
                  <p className="shrink-0 text-xs text-white/25 mt-0.5">
                    {formatDate(a.created_at)}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* ── Admin Audit Log ─────────────────────────────────────────── */}
        <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">
            <Shield className="h-4 w-4 text-rose-400 shrink-0" />
            <h2 className="text-sm font-semibold text-white">Admin Audit Log</h2>
            <span className="ml-auto text-xs text-white/30">{audit.length} entries</span>
          </div>

          {audit.length === 0 ? (
            <EmptyState
              icon={History}
              title="No audit entries"
              description="Sensitive admin actions like bans, plan changes, and impersonation are recorded here."
            />
          ) : (
            <div className="divide-y divide-white/[0.04]">
              {audit.map((entry) => {
                const Icon = actionIcon[entry.action] ?? Shield
                const meta = compactJson(entry.metadata)
                return (
                  <div
                    key={entry.id}
                    className="px-5 py-3.5 hover:bg-white/[0.02] transition-colors"
                  >
                    <div className="flex items-center gap-2">
                      <span
                        className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[10px] font-semibold ${
                          actionPill[entry.action] ?? DEFAULT_PILL
                        }`}
                      >
                        <Icon className="h-3 w-3" />
                        {entry.action}
                      </span>
                      {entry.target_user_id && (
                        <span className="font-mono text-[11px] text-white/40 truncate">
                          {entry.target_user_id}
                        </span>
                      )}
                      <span className="ml-auto shrink-0 text-xs text-white/25">
                        {formatDate(entry.created_at)}
                      </span>
                    </div>
                    {meta && (
                      <p className="mt-1.5 font-mono text-[11px] text-white/40 break-all line-clamp-2">
                        {meta}
                      </p>
                    )}
                    {entry.ip_address && (
                      <p className="mt-1 font-mono text-[11px] text-white/30">
                        {entry.ip_address}
                      </p>
                    )}
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
