import { useState, useEffect } from "react"
import { CheckCircle2, MapPin } from "lucide-react"
import { trpc } from "@/providers/trpc"

function timeAgo(date: Date): string {
  const mins = Math.floor((Date.now() - new Date(date).getTime()) / 60000)
  if (mins < 1) return "just now"
  if (mins < 60) return `${mins}m ago`
  return `${Math.floor(mins / 60)}h ago`
}

export function LiveSalesNotifications() {
  const [notification, setNotification] = useState<{name:string;location:string;product:string;time:string}|null>(null)
  const { data: sales } = trpc.activity.getRecentSales.useQuery({ limit: 20 }, { refetchInterval: 30000 })

  useEffect(() => {
    if (!sales?.length) return
    const interval = setInterval(() => {
      const s = sales[Math.floor(Math.random() * sales.length)]
      if (s) {
        setNotification({ name: s.customerName || "Customer", location: s.location || "Global", product: s.productName || "Premium", time: timeAgo(s.createdAt || new Date()) })
        setTimeout(() => setNotification(null), 5000)
      }
    }, 18000)
    return () => clearInterval(interval)
  }, [sales])

  if (!notification) return null

  return (
    <div className="fixed bottom-24 left-4 z-[55] animate-slide-in-right">
      <div className="glass-card px-4 py-3 flex items-center gap-3 max-w-xs">
        <div className="w-10 h-10 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0">
          <CheckCircle2 className="w-5 h-5 text-green-400" />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-white truncate">{notification.name}</p>
          <p className="text-xs text-slate-400 flex items-center gap-1"><MapPin className="w-3 h-3" />{notification.location}</p>
          <p className="text-xs text-green-400">Purchased {notification.product} <span className="text-slate-500">{notification.time}</span></p>
        </div>
      </div>
    </div>
  )
}
