"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 { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Dialog, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { formatPence } from "@/lib/utils"
import { Plus, Download, ExternalLink, Copy, Check, Loader2, ArrowLeft, Trophy, Users, MessageCircle, Mail, Share2, Link2 } from "lucide-react"
import Link from "next/link"
import { QRCodeCanvas } from "@/components/qr-code"

interface SourceInfo {
  id: string
  label: string
  code: string
  volunteerName: string | null
  tableName: string | null
  scanCount: number
  pledgeCount: number
  totalPledged: number
}

export default function CampaignLinksPage() {
  const params = useParams()
  const eventId = params.id as string
  const [sources, setSources] = useState<SourceInfo[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [copiedCode, setCopiedCode] = useState<string | null>(null)
  const [form, setForm] = useState({ label: "", volunteerName: "", tableName: "" })
  const [creating, setCreating] = useState(false)

  const baseUrl = typeof window !== "undefined" ? window.location.origin : ""

  useEffect(() => {
    fetch(`/api/events/${eventId}/qr`)
      .then((r) => r.json())
      .then((data) => { if (Array.isArray(data)) setSources(data) })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [eventId])

  const copyLink = async (code: string) => {
    await navigator.clipboard.writeText(`${baseUrl}/p/${code}`)
    setCopiedCode(code)
    if (navigator.vibrate) navigator.vibrate(10)
    setTimeout(() => setCopiedCode(null), 2000)
  }

  const shareLink = (code: string, label: string) => {
    const url = `${baseUrl}/p/${code}`
    if (navigator.share) {
      navigator.share({ title: label, text: `Pledge here: ${url}`, url })
    } else {
      copyLink(code)
    }
  }

  const shareWhatsApp = (code: string, label: string) => {
    const url = `${baseUrl}/p/${code}`
    window.open(`https://wa.me/?text=${encodeURIComponent(`Assalamu Alaikum! Please pledge here 🤲\n\n${label}\n${url}`)}`, "_blank")
  }

  const shareEmail = (code: string, label: string) => {
    const url = `${baseUrl}/p/${code}`
    window.open(`mailto:?subject=${encodeURIComponent(`Pledge: ${label}`)}&body=${encodeURIComponent(`Please pledge here:\n\n${url}`)}`)
  }

  const handleCreate = async () => {
    setCreating(true)
    try {
      const res = await fetch(`/api/events/${eventId}/qr`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      })
      if (res.ok) {
        const src = await res.json()
        setSources((prev) => [{ ...src, scanCount: 0, pledgeCount: 0, totalPledged: 0 }, ...prev])
        setShowCreate(false)
        setForm({ label: "", volunteerName: "", tableName: "" })
      }
    } catch {}
    setCreating(false)
  }

  useEffect(() => {
    if (form.volunteerName || form.tableName) {
      const parts = [form.tableName, form.volunteerName].filter(Boolean)
      setForm((f) => ({ ...f, label: parts.join(" - ") }))
    }
  }, [form.volunteerName, form.tableName])

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

  const totalClicks = sources.reduce((s, q) => s + q.scanCount, 0)
  const totalPledges = sources.reduce((s, q) => s + q.pledgeCount, 0)
  const totalAmount = sources.reduce((s, q) => s + q.totalPledged, 0)

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <Link href="/dashboard/events" className="text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1 mb-2">
            <ArrowLeft className="h-3 w-3" /> Back to Campaigns
          </Link>
          <h1 className="text-3xl font-extrabold text-gray-900">Pledge Links</h1>
          <p className="text-muted-foreground mt-1">
            {sources.length} link{sources.length !== 1 ? "s" : ""} · {totalClicks} clicks · {totalPledges} pledges · {formatPence(totalAmount)}
          </p>
        </div>
        <div className="flex gap-2">
          <Link href={`/dashboard/events/${eventId}/leaderboard`}>
            <Button variant="outline"><Trophy className="h-4 w-4 mr-2" /> Leaderboard</Button>
          </Link>
          <Button onClick={() => setShowCreate(true)}>
            <Plus className="h-4 w-4 mr-2" /> New Link
          </Button>
        </div>
      </div>

      {sources.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center space-y-4">
            <Link2 className="h-12 w-12 text-muted-foreground mx-auto" />
            <h3 className="font-bold text-lg">Create your first pledge link</h3>
            <p className="text-muted-foreground text-sm max-w-md mx-auto">
              Each link is unique and trackable. Create one per volunteer, table, WhatsApp group, social post, or email campaign — so you know where pledges come from.
            </p>
            <Button onClick={() => setShowCreate(true)}>
              <Plus className="h-4 w-4 mr-2" /> Create Pledge Link
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {sources.map((src) => (
            <Card key={src.id} className="hover:shadow-md transition-shadow">
              <CardContent className="pt-6 space-y-4">
                {/* QR Code — compact */}
                <div className="max-w-[140px] mx-auto bg-white rounded-lg flex items-center justify-center p-1.5">
                  <QRCodeCanvas url={`${baseUrl}/p/${src.code}`} size={128} />
                </div>

                <div className="text-center">
                  <h3 className="font-bold">{src.label}</h3>
                  {src.volunteerName && <p className="text-xs text-muted-foreground">By: {src.volunteerName}</p>}
                  <p className="text-[10px] text-muted-foreground font-mono mt-1">{baseUrl}/p/{src.code}</p>
                </div>

                {/* Stats */}
                <div className="grid grid-cols-3 gap-2 text-center text-xs">
                  <div className="rounded-lg bg-gray-50 p-2">
                    <p className="font-bold text-sm">{src.scanCount}</p>
                    <p className="text-muted-foreground">Clicks</p>
                  </div>
                  <div className="rounded-lg bg-gray-50 p-2">
                    <p className="font-bold text-sm">{src.pledgeCount}</p>
                    <p className="text-muted-foreground">Pledges</p>
                  </div>
                  <div className="rounded-lg bg-gray-50 p-2">
                    <p className="font-bold text-sm">{formatPence(src.totalPledged)}</p>
                    <p className="text-muted-foreground">Raised</p>
                  </div>
                </div>

                {src.scanCount > 0 && (
                  <div className="text-center">
                    <span className="text-xs text-muted-foreground">
                      Conversion: <span className="font-semibold text-foreground">{Math.round((src.pledgeCount / src.scanCount) * 100)}%</span>
                    </span>
                  </div>
                )}

                {/* Share options — the main CTA, not an afterthought */}
                <div className="grid grid-cols-4 gap-1.5">
                  <Button variant="outline" size="sm" onClick={() => copyLink(src.code)} className="text-[10px] px-1">
                    {copiedCode === src.code ? <Check className="h-3.5 w-3.5" /> : <><Copy className="h-3 w-3" /> Copy</>}
                  </Button>
                  <Button size="sm" onClick={() => shareWhatsApp(src.code, src.label)} className="text-[10px] px-1 bg-[#25D366] hover:bg-[#20BD5A] text-white">
                    <MessageCircle className="h-3 w-3" /> WA
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => shareEmail(src.code, src.label)} className="text-[10px] px-1">
                    <Mail className="h-3 w-3" /> Email
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => shareLink(src.code, src.label)} className="text-[10px] px-1">
                    <Share2 className="h-3 w-3" /> More
                  </Button>
                </div>

                {/* Secondary actions */}
                <div className="flex gap-2">
                  <a href={`/api/events/${eventId}/qr/${src.id}/download?code=${src.code}`} download className="flex-1">
                    <Button variant="outline" size="sm" className="w-full text-xs">
                      <Download className="h-3 w-3 mr-1" /> QR Image
                    </Button>
                  </a>
                  <a href={`/v/${src.code}`} target="_blank" className="flex-1">
                    <Button variant="outline" size="sm" className="w-full text-xs">
                      <Users className="h-3 w-3 mr-1" /> Volunteer
                    </Button>
                  </a>
                  <a href={`/p/${src.code}`} target="_blank">
                    <Button variant="outline" size="sm"><ExternalLink className="h-3 w-3" /></Button>
                  </a>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Create dialog */}
      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogHeader>
          <DialogTitle>Create Pledge Link</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Each link is trackable. Create one per source to see where pledges come from.
          </p>
          <div className="space-y-2">
            <Label>Label *</Label>
            <Input
              placeholder="e.g. WhatsApp Family Group, Table 5, Instagram Bio, Ahmed's Link"
              value={form.label}
              onChange={(e) => setForm((f) => ({ ...f, label: e.target.value }))}
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Source / Channel <span className="text-muted-foreground font-normal">(optional)</span></Label>
              <Input
                placeholder="e.g. Table 5, WhatsApp, Twitter"
                value={form.tableName}
                onChange={(e) => setForm((f) => ({ ...f, tableName: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Person <span className="text-muted-foreground font-normal">(optional)</span></Label>
              <Input
                placeholder="e.g. Ahmed, Sarah"
                value={form.volunteerName}
                onChange={(e) => setForm((f) => ({ ...f, volunteerName: e.target.value }))}
              />
            </div>
          </div>
          <div className="flex gap-3 pt-2">
            <Button variant="outline" onClick={() => setShowCreate(false)} className="flex-1">Cancel</Button>
            <Button onClick={handleCreate} disabled={!form.label || creating} className="flex-1">
              {creating ? "Creating..." : "Create Link"}
            </Button>
          </div>
        </div>
      </Dialog>
    </div>
  )
}
