"use client"

import { useState, useEffect } from "react"
import { Badge } from "@/components/ui/badge"
import { Banknote, TrendingUp, Radio } from "lucide-react"

interface TickerPledge {
  id: string
  donorName: string | null
  amountPence: number
  status: string
  rail: string
  createdAt: string
  qrSourceLabel: string | null
  giftAid: boolean
}

interface LiveTickerProps {
  eventId: string
}

const formatPence = (p: number) => `£${(p / 100).toLocaleString("en-GB", { minimumFractionDigits: 0 })}`

export function LiveTicker({ eventId }: LiveTickerProps) {
  const [pledges, setPledges] = useState<TickerPledge[]>([])
  const [isLive, setIsLive] = useState(false)

  useEffect(() => {
    const load = async () => {
      try {
        const res = await fetch(`/api/pledges?eventId=${eventId}&limit=10`)
        const data = await res.json()
        if (data.pledges) {
          setPledges(data.pledges.map((p: Record<string, unknown>) => ({
            id: p.id,
            donorName: p.donorName,
            amountPence: p.amountPence,
            status: p.status,
            rail: p.rail,
            createdAt: p.createdAt,
            qrSourceLabel: p.qrSourceLabel,
            giftAid: p.giftAid,
          })))
          setIsLive(true)
        }
      } catch {
        setIsLive(false)
      }
    }
    load()
    const interval = setInterval(load, 8000)
    return () => clearInterval(interval)
  }, [eventId])

  if (pledges.length === 0) return null

  const totalToday = pledges.reduce((s, p) => s + p.amountPence, 0)

  return (
    <div className="rounded-lg border bg-white p-4 space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="font-bold text-sm flex items-center gap-2">
          <TrendingUp className="h-4 w-4 text-trust-blue" /> Live Feed
        </h3>
        <div className="flex items-center gap-2">
          <span className="text-xs font-semibold text-muted-foreground">
            {formatPence(totalToday)} recent
          </span>
          {isLive && (
            <Badge variant="success" className="gap-1">
              <Radio className="h-3 w-3 animate-pulse" /> Live
            </Badge>
          )}
        </div>
      </div>

      <div className="space-y-2 max-h-64 overflow-y-auto">
        {pledges.map((p, i) => {
          const name = p.donorName || "Anonymous"
          const initials = name.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase()
          const ago = formatTimeAgo(p.createdAt)

          return (
            <div
              key={p.id}
              className={`flex items-center gap-3 py-2 ${i === 0 ? "animate-slide-in" : ""}`}
            >
              <div className="w-8 h-8 rounded-full bg-trust-blue/10 flex items-center justify-center text-xs font-bold text-trust-blue shrink-0">
                {initials}
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-1.5">
                  <span className="text-sm font-medium truncate">{name}</span>
                  {p.giftAid && <span className="text-xs">🎁</span>}
                </div>
                <p className="text-xs text-muted-foreground">
                  {p.qrSourceLabel && `${p.qrSourceLabel} · `}{ago}
                </p>
              </div>
              <div className="flex items-center gap-2">
                <Banknote className="h-3.5 w-3.5 text-success-green" />
                <span className="font-bold text-sm">{formatPence(p.amountPence)}</span>
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

function formatTimeAgo(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime()
  const mins = Math.floor(diff / 60000)
  if (mins < 1) return "Just now"
  if (mins < 60) return `${mins}m ago`
  const hrs = Math.floor(mins / 60)
  if (hrs < 24) return `${hrs}h ago`
  return `${Math.floor(hrs / 24)}d ago`
}
