"use client"

import { useState, useEffect } from "react"
import { useParams } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { MessageCircle, Share2, Heart, Users, Banknote, Gift, Loader2, QrCode, Calendar, MapPin } from "lucide-react"
// Badge is available via @/components/ui/badge if needed

interface EventData {
  id: string
  name: string
  description: string | null
  eventDate: string | null
  location: string | null
  goalAmount: number | null
  organizationName: string
  stats: {
    pledgeCount: number
    totalPledged: number
    totalPaid: number
    giftAidCount: number
    avgPledge: number
  }
  recentPledges: Array<{
    donorName: string | null
    amountPence: number
    createdAt: string
    giftAid: boolean
  }>
  qrCodes: Array<{
    code: string
    label: string
    volunteerName: string | null
  }>
}

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

export default function PublicEventPage() {
  const params = useParams()
  const slug = params.slug as string
  const [data, setData] = useState<EventData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")

  useEffect(() => {
    fetch(`/api/events/public/${slug}`)
      .then((r) => r.json())
      .then((d) => {
        if (d.error) setError(d.error)
        else setData(d)
      })
      .catch(() => setError("Failed to load"))
      .finally(() => setLoading(false))

    const interval = setInterval(() => {
      fetch(`/api/events/public/${slug}`)
        .then((r) => r.json())
        .then((d) => { if (!d.error) setData(d) })
        .catch(() => {})
    }, 15000)
    return () => clearInterval(interval)
  }, [slug])

  const handleWhatsAppShare = () => {
    if (!data) return
    const url = `${window.location.origin}/e/${slug}`
    const text = `🤲 ${data.name} is raising funds!\n\nPledge here — it takes 15 seconds:\n${url}`
    window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank")
  }

  const handleShare = async () => {
    if (!data) return
    const url = `${window.location.origin}/e/${slug}`
    if (navigator.share) {
      await navigator.share({ title: data.name, text: `Pledge to ${data.name}`, url })
    } else {
      handleWhatsAppShare()
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5">
        <Loader2 className="h-8 w-8 text-trust-blue animate-spin" />
      </div>
    )
  }

  if (error || !data) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5 p-4">
        <div className="text-center space-y-4">
          <Heart className="h-12 w-12 text-muted-foreground mx-auto" />
          <h1 className="text-xl font-bold">Event not found</h1>
          <p className="text-muted-foreground">{error}</p>
        </div>
      </div>
    )
  }

  const progressPercent = data.goalAmount
    ? Math.min(100, Math.round((data.stats.totalPledged / data.goalAmount) * 100))
    : null
  const giftAidBonus = Math.round(data.stats.totalPledged * 0.25 * (data.stats.giftAidCount / Math.max(1, data.stats.pledgeCount)))

  return (
    <div className="min-h-screen bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5">
      <div className="max-w-lg mx-auto px-4 py-8 space-y-6">
        {/* Header */}
        <div className="text-center space-y-3">
          <p className="text-sm text-muted-foreground">{data.organizationName}</p>
          <h1 className="text-3xl font-extrabold text-gray-900">{data.name}</h1>
          {data.description && <p className="text-muted-foreground">{data.description}</p>}
          <div className="flex items-center justify-center gap-4 text-xs text-muted-foreground">
            {data.eventDate && (
              <span className="inline-flex items-center gap-1">
                <Calendar className="h-3 w-3" />
                {new Date(data.eventDate).toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" })}
              </span>
            )}
            {data.location && (
              <span className="inline-flex items-center gap-1">
                <MapPin className="h-3 w-3" /> {data.location}
              </span>
            )}
          </div>
        </div>

        {/* Progress */}
        <Card className="overflow-hidden">
          <CardContent className="pt-6 space-y-4">
            <div className="text-center">
              <p className="text-4xl font-extrabold text-trust-blue">{formatPence(data.stats.totalPledged)}</p>
              <p className="text-sm text-muted-foreground">
                pledged by {data.stats.pledgeCount} {data.stats.pledgeCount === 1 ? "person" : "people"}
              </p>
            </div>

            {progressPercent !== null && data.goalAmount && (
              <div>
                <div className="flex justify-between text-xs text-muted-foreground mb-1">
                  <span>{progressPercent}% of goal</span>
                  <span>{formatPence(data.goalAmount)}</span>
                </div>
                <div className="h-4 rounded-full bg-gray-100 overflow-hidden">
                  <div
                    className="h-full rounded-full bg-gradient-to-r from-trust-blue to-success-green transition-all duration-1000"
                    style={{ width: `${progressPercent}%` }}
                  />
                </div>
              </div>
            )}

            <div className="grid grid-cols-3 gap-3 pt-2">
              <div className="text-center">
                <Users className="h-4 w-4 text-trust-blue mx-auto" />
                <p className="font-bold text-sm">{data.stats.pledgeCount}</p>
                <p className="text-xs text-muted-foreground">Pledges</p>
              </div>
              <div className="text-center">
                <Banknote className="h-4 w-4 text-success-green mx-auto" />
                <p className="font-bold text-sm">{formatPence(data.stats.totalPaid)}</p>
                <p className="text-xs text-muted-foreground">Collected</p>
              </div>
              <div className="text-center">
                <Gift className="h-4 w-4 text-warm-amber mx-auto" />
                <p className="font-bold text-sm">{formatPence(giftAidBonus)}</p>
                <p className="text-xs text-muted-foreground">Gift Aid</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Pledge CTA — link to first QR code */}
        {data.qrCodes.length > 0 && (
          <Button
            size="xl"
            className="w-full text-lg"
            onClick={() => window.location.href = `/p/${data.qrCodes[0].code}`}
          >
            <Heart className="h-5 w-5 mr-2" /> Pledge Now
          </Button>
        )}

        {/* Share */}
        <div className="flex gap-2">
          <Button onClick={handleWhatsAppShare} className="flex-1 bg-[#25D366] hover:bg-[#20BD5A] text-white">
            <MessageCircle className="h-4 w-4 mr-2" /> WhatsApp
          </Button>
          <Button onClick={handleShare} variant="outline" className="flex-1">
            <Share2 className="h-4 w-4 mr-2" /> Share
          </Button>
        </div>

        {/* Recent pledges — social proof */}
        {data.recentPledges.length > 0 && (
          <div className="space-y-2">
            <h2 className="font-bold text-sm text-muted-foreground uppercase tracking-wider">
              Recent Pledges
            </h2>
            {data.recentPledges.map((p, i) => {
              const name = p.donorName || "Anonymous"
              const ago = formatTimeAgo(p.createdAt)
              return (
                <div key={i} className="flex items-center gap-3 py-2 border-b last:border-0">
                  <div className="w-8 h-8 rounded-full bg-trust-blue/10 flex items-center justify-center text-xs font-bold text-trust-blue">
                    {name[0].toUpperCase()}
                  </div>
                  <div className="flex-1">
                    <span className="text-sm font-medium">{name}</span>
                    {p.giftAid && <span className="text-xs ml-1">🎁</span>}
                    <p className="text-xs text-muted-foreground">{ago}</p>
                  </div>
                  <span className="font-bold text-sm">{formatPence(p.amountPence)}</span>
                </div>
              )
            })}
          </div>
        )}

        {/* Volunteer QR codes */}
        {data.qrCodes.length > 1 && (
          <div className="space-y-2">
            <h2 className="font-bold text-sm text-muted-foreground uppercase tracking-wider">
              Pledge via a Fundraiser
            </h2>
            <div className="grid grid-cols-2 gap-2">
              {data.qrCodes.map((qr) => (
                <Button
                  key={qr.code}
                  variant="outline"
                  className="h-auto py-3 justify-start"
                  onClick={() => window.location.href = `/p/${qr.code}`}
                >
                  <QrCode className="h-4 w-4 mr-2 shrink-0" />
                  <span className="truncate text-xs">{qr.volunteerName || qr.label}</span>
                </Button>
              ))}
            </div>
          </div>
        )}

        <p className="text-center text-xs text-muted-foreground">
          Powered by <a href="/" className="text-trust-blue hover:underline">Pledge Now, Pay Later</a>
        </p>
      </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`
}
