"use client"

import { useState, useEffect } from "react"
import { useParams } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Trophy, ArrowLeft, Loader2 } from "lucide-react"
import Link from "next/link"

interface LeaderEntry {
  label: string
  volunteerName: string | null
  pledgeCount: number
  totalPledged: number
  totalPaid: number
  scanCount: number
  conversionRate: number
}

export default function LeaderboardPage() {
  const params = useParams()
  const eventId = params.id as string
  const [entries, setEntries] = useState<LeaderEntry[]>([])
  const [loading, setLoading] = useState(true)

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

  useEffect(() => {
    const load = () => {
      fetch(`/api/events/${eventId}/qr`)
        .then((r) => r.json())
        .then((data) => {
          if (Array.isArray(data)) {
            const sorted = [...data].sort((a, b) => b.totalPledged - a.totalPledged)
            setEntries(sorted.map((d) => ({
              label: d.label,
              volunteerName: d.volunteerName,
              pledgeCount: d.pledgeCount,
              totalPledged: d.totalPledged,
              totalPaid: d.totalCollected || 0,
              scanCount: d.scanCount,
              conversionRate: d.scanCount > 0 ? Math.round((d.pledgeCount / d.scanCount) * 100) : 0,
            })))
          }
        })
        .catch(() => {})
        .finally(() => setLoading(false))
    }
    load()
    const interval = setInterval(load, 10000)
    return () => clearInterval(interval)
  }, [eventId])

  const medals = ["🥇", "🥈", "🥉"]

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-8 w-8 text-trust-blue animate-spin" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <Link href={`/dashboard/events/${eventId}`} className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1 mb-2">
          <ArrowLeft className="h-3 w-3" /> Back to Event
        </Link>
        <h1 className="text-3xl font-extrabold text-gray-900 flex items-center gap-3">
          <Trophy className="h-8 w-8 text-warm-amber" /> Fundraiser Leaderboard
        </h1>
        <p className="text-muted-foreground mt-1">Auto-refreshes every 10 seconds — perfect for live events</p>
      </div>

      <div className="space-y-3">
        {entries.map((entry, i) => (
          <Card key={i} className={`${i < 3 ? "border-warm-amber/30 bg-warm-amber/5" : ""}`}>
            <CardContent className="py-4 px-5">
              <div className="flex items-center gap-4">
                <div className="text-3xl w-12 text-center">
                  {i < 3 ? medals[i] : <span className="text-lg font-bold text-muted-foreground">#{i + 1}</span>}
                </div>
                <div className="flex-1">
                  <p className="font-bold text-lg">{entry.volunteerName || entry.label}</p>
                  <div className="flex items-center gap-3 text-xs text-muted-foreground mt-1">
                    <span>{entry.pledgeCount} pledges</span>
                    <span>{entry.scanCount} scans</span>
                    <Badge variant={entry.conversionRate >= 50 ? "success" : "secondary"} className="text-xs">
                      {entry.conversionRate}% conversion
                    </Badge>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-2xl font-extrabold text-trust-blue">{formatPence(entry.totalPledged)}</p>
                  <p className="text-xs text-muted-foreground">{formatPence(entry.totalPaid)} collected</p>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {entries.length === 0 && (
        <Card>
          <CardContent className="py-12 text-center">
            <Trophy className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
            <p className="text-muted-foreground">No QR codes created yet. Create QR codes to see the leaderboard.</p>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
