"use client"

import { useEffect, useState } from "react"
import { Activity, PhoneCall, Timer, UserPlus, Users2 } from "lucide-react"
import { createClient } from "@/lib/supabase/client"

type Metrics = {
  totalUsers: number
  newUsersToday: number
  activeCalls: number
  waiting: number
  sessionsToday: number
  avgDurationSec: number
}

export function DashboardMetrics({ initial }: { initial: Metrics }) {
  const [metrics, setMetrics] = useState<Metrics>(initial)
  // Live site-wide presence count (same channel as the header badge)
  const [livePresence, setLivePresence] = useState(0)

  // Subscribe to the global presence channel as a read-only observer so the
  // admin dashboard always reflects the same number users see in the header.
  useEffect(() => {
    const supabase = createClient()
    const channel = supabase.channel("presence:lobby", {
      config: { presence: { key: `admin-${crypto.randomUUID()}` } },
    })
    const update = () => {
      const state = channel.presenceState() as Record<string, unknown[]>
      setLivePresence(Object.keys(state).length)
    }
    channel
      .on("presence", { event: "sync" }, update)
      .on("presence", { event: "join" }, update)
      .on("presence", { event: "leave" }, update)
      .subscribe(async (status) => {
        if (status === "SUBSCRIBED") {
          try {
            // Track as an admin observer so we're counted too.
            await channel.track({ role: "admin", at: Date.now() })
          } catch {}
        }
      })
    return () => {
      try {
        void channel.untrack()
      } catch {}
      void supabase.removeChannel(channel)
    }
  }, [])

  // Poll fresh DB metrics every 10s so live values don't go stale.
  useEffect(() => {
    let cancelled = false
    const poll = async () => {
      try {
        const res = await fetch("/api/admin/metrics", { cache: "no-store" })
        if (!res.ok) return
        const json = (await res.json()) as Partial<Metrics>
        if (cancelled) return
        setMetrics((prev) => ({ ...prev, ...json }))
      } catch {}
    }
    const iv = setInterval(poll, 10_000)
    return () => {
      cancelled = true
      clearInterval(iv)
    }
  }, [])

  const cards: Array<{
    label: string
    value: string | number
    sub: string
    icon: React.ComponentType<{ className?: string; "aria-hidden"?: boolean }>
    accent: string
  }> = [
    {
      label: "Live now",
      value: livePresence,
      sub: "Connected browsers",
      icon: Activity,
      accent: "text-emerald-600 bg-emerald-500/10",
    },
    {
      label: "Active calls",
      value: metrics.activeCalls,
      sub: `${metrics.waiting} waiting in queue`,
      icon: PhoneCall,
      accent: "text-sky-600 bg-sky-500/10",
    },
    {
      label: "Total users",
      value: metrics.totalUsers.toLocaleString(),
      sub: `${metrics.newUsersToday} joined today`,
      icon: Users2,
      accent: "text-primary bg-primary/10",
    },
    {
      label: "New today",
      value: metrics.newUsersToday,
      sub: "Registrations in last 24h",
      icon: UserPlus,
      accent: "text-violet-600 bg-violet-500/10",
    },
    {
      label: "Sessions today",
      value: metrics.sessionsToday,
      sub: `Avg ${formatDuration(metrics.avgDurationSec)}`,
      icon: Activity,
      accent: "text-amber-600 bg-amber-500/10",
    },
    {
      label: "Avg call length",
      value: formatDuration(metrics.avgDurationSec),
      sub: "Today",
      icon: Timer,
      accent: "text-rose-600 bg-rose-500/10",
    },
  ]

  return (
    <div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-6">
      {cards.map((c) => {
        const Icon = c.icon
        return (
          <div
            key={c.label}
            className="rounded-xl border border-border bg-background p-4 shadow-sm"
          >
            <div className="flex items-center justify-between gap-2">
              <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                {c.label}
              </p>
              <span
                aria-hidden="true"
                className={`flex h-7 w-7 items-center justify-center rounded-md ${c.accent}`}
              >
                <Icon className="h-3.5 w-3.5" />
              </span>
            </div>
            <p className="mt-2 text-2xl font-semibold tabular-nums tracking-tight text-foreground">
              {c.value}
            </p>
            <p className="mt-0.5 truncate text-xs text-muted-foreground">{c.sub}</p>
          </div>
        )
      })}
    </div>
  )
}

function formatDuration(sec: number) {
  if (!sec || !Number.isFinite(sec)) return "0s"
  const s = Math.max(0, Math.round(sec))
  if (s < 60) return `${s}s`
  const m = Math.floor(s / 60)
  const r = s % 60
  if (m < 60) return r ? `${m}m ${r}s` : `${m}m`
  const h = Math.floor(m / 60)
  const rm = m % 60
  return rm ? `${h}h ${rm}m` : `${h}h`
}
