"use client"

import { useEffect, useState, useCallback } from "react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Check, Share2, MessageCircle, Copy, Sparkles } from "lucide-react"

interface Props {
  pledge: { id: string; reference: string }
  amount: number
  rail: string
  eventName: string
  shareUrl?: string
  donorPhone?: string
  isDeferred?: boolean
  dueDateLabel?: string
  installmentCount?: number
  installmentAmount?: number
}

// Mini confetti
function Confetti() {
  const [pieces, setPieces] = useState<Array<{ x: number; color: string; delay: number; size: number }>>([])

  useEffect(() => {
    setPieces(
      Array.from({ length: 40 }, () => ({
        x: Math.random() * 100,
        color: ["#1e40af", "#16a34a", "#f59e0b", "#ec4899", "#8b5cf6"][Math.floor(Math.random() * 5)],
        delay: Math.random() * 2,
        size: 4 + Math.random() * 8,
      }))
    )
  }, [])

  return (
    <div className="fixed inset-0 pointer-events-none overflow-hidden z-50">
      {pieces.map((p, i) => (
        <div
          key={i}
          className="absolute top-0"
          style={{
            left: `${p.x}%`,
            width: p.size,
            height: p.size,
            backgroundColor: p.color,
            borderRadius: Math.random() > 0.5 ? "50%" : "2px",
            animation: `confetti-fall ${2 + Math.random() * 2}s ease-in forwards`,
            animationDelay: `${p.delay}s`,
          }}
        />
      ))}
    </div>
  )
}

export function ConfirmationStep({ pledge, amount, rail, eventName, shareUrl, donorPhone, isDeferred, dueDateLabel, installmentCount, installmentAmount }: Props) {
  const [copied, setCopied] = useState(false)
  const [whatsappSent, setWhatsappSent] = useState(false)

  const railLabels: Record<string, string> = {
    bank: "Bank Transfer",
    gocardless: "Direct Debit",
    card: "Card Payment",
  }

  const deferredMessage = isDeferred
    ? installmentCount && installmentCount > 1
      ? `You've pledged ${installmentCount} payments of £${((installmentAmount || 0) / 100).toFixed(0)}/month. We'll send you payment details before each due date via ${donorPhone ? "WhatsApp" : "email"}.`
      : `Your payment is scheduled for ${dueDateLabel}. We'll send you payment details on the day via ${donorPhone ? "WhatsApp" : "email"}. No action needed until then.`
    : null

  const nextStepMessages: Record<string, string> = {
    bank: deferredMessage || "We've sent you payment instructions. Transfer at your convenience — we'll confirm once received.",
    gocardless: `Your Direct Debit mandate is set up. £${(amount / 100).toFixed(2)} will be collected automatically in 3-5 working days. Protected by the Direct Debit Guarantee.`,
    card: "Your card payment has been processed. Confirmation email is on its way.",
  }

  // Send WhatsApp receipt if phone provided
  const sendWhatsAppReceipt = useCallback(async () => {
    if (!donorPhone || whatsappSent) return
    try {
      await fetch("/api/whatsapp/send", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          type: "receipt",
          phone: donorPhone,
          data: {
            amountPounds: (amount / 100).toFixed(0),
            eventName,
            reference: pledge.reference,
            rail,
          },
        }),
      })
      setWhatsappSent(true)
    } catch {
      // Silent fail — not critical
    }
  }, [donorPhone, whatsappSent, amount, eventName, pledge.reference, rail])

  useEffect(() => {
    sendWhatsAppReceipt()
  }, [sendWhatsAppReceipt])

  const handleWhatsAppShare = () => {
    const text = `I just pledged £${(amount / 100).toFixed(0)} to ${eventName}! 🤲\n\nYou can pledge too: ${shareUrl || window.location.origin}`
    window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank")
  }

  const handleShare = async () => {
    const text = `I just pledged £${(amount / 100).toFixed(0)} to ${eventName}!`
    if (navigator.share) {
      await navigator.share({ title: eventName, text, url: shareUrl || window.location.origin })
    } else {
      handleWhatsAppShare()
    }
  }

  const copyRef = async () => {
    await navigator.clipboard.writeText(pledge.reference)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <>
      <Confetti />
      <div className="max-w-md mx-auto pt-6 text-center space-y-6 animate-fade-up">
        {/* Success icon with pulse */}
        <div className="relative inline-flex items-center justify-center">
          <div className="absolute w-16 h-16 bg-success-green/20" />
          <div className="relative w-16 h-16 bg-fulfilled-green flex items-center justify-center">
            <Check className="h-10 w-10 text-white" strokeWidth={3} />
          </div>
        </div>

        <div className="space-y-2">
          <h1 className="text-2xl font-black text-gray-900">
            {isDeferred
              ? "Pledge Locked In!"
              : rail === "card" ? "Payment Complete!" : rail === "gocardless" ? "Mandate Set Up!" : "Pledge Received!"}
          </h1>
          <p className="text-muted-foreground">
            Thank you for your generous support of{" "}
            <span className="font-semibold text-foreground">{eventName}</span>
          </p>
        </div>

        {/* Details card */}
        <Card className="text-left overflow-hidden">
          <div className="h-1 bg-promise-blue" />
          <CardContent className="pt-5 space-y-3 text-sm">
            <div className="flex justify-between items-center">
              <span className="text-muted-foreground">Amount</span>
              <span className="font-black text-lg">£{(amount / 100).toFixed(2)}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-muted-foreground">Method</span>
              <span className="font-medium">{railLabels[rail] || rail}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-muted-foreground">Reference</span>
              <button onClick={copyRef} className="font-mono font-bold text-trust-blue flex items-center gap-1.5 hover:underline">
                {pledge.reference}
                {copied ? <Check className="h-3.5 w-3.5 text-success-green" /> : <Copy className="h-3.5 w-3.5" />}
              </button>
            </div>
            {isDeferred && dueDateLabel && (
              <div className="flex justify-between items-center pt-1 border-t">
                <span className="text-muted-foreground">{installmentCount && installmentCount > 1 ? "Schedule" : "Payment Date"}</span>
                <span className="font-semibold text-warm-amber">
                  {installmentCount && installmentCount > 1
                    ? `${installmentCount}× £${((installmentAmount || 0) / 100).toFixed(0)}/mo`
                    : dueDateLabel
                  }
                </span>
              </div>
            )}
            {rail === "card" && !isDeferred && (
              <div className="flex justify-between items-center pt-1 border-t">
                <span className="text-muted-foreground">Status</span>
                <span className="text-success-green font-bold flex items-center gap-1">
                  <Check className="h-4 w-4" /> Paid
                </span>
              </div>
            )}
          </CardContent>
        </Card>

        {/* What happens next */}
        <div className="rounded-lg bg-trust-blue/5 border border-trust-blue/10 p-4 text-left">
          <p className="text-sm font-semibold text-trust-blue mb-1">What happens next?</p>
          <p className="text-sm text-muted-foreground">{nextStepMessages[rail] || nextStepMessages.bank}</p>
        </div>

        {whatsappSent && (
          <div className="rounded-lg bg-[#25D366]/10 border border-[#25D366]/20 p-3 text-sm text-[#25D366] font-medium flex items-center justify-center gap-2 animate-fade-in">
            <MessageCircle className="h-4 w-4" /> Receipt sent to your WhatsApp ✓
          </div>
        )}

        {/* Share */}
        <div className="rounded-lg bg-generosity-gold/5 border border-warm-amber/20 p-5 space-y-3">
          <div className="flex items-center justify-center gap-2">
            <Sparkles className="h-4 w-4 text-warm-amber" />
            <p className="text-sm font-bold text-gray-900">
              Double your impact — share with friends
            </p>
          </div>
          <p className="text-xs text-muted-foreground">
            Every share can inspire another pledge
          </p>
          <div className="flex gap-2">
            <Button onClick={handleWhatsAppShare} className="flex-1 bg-[#25D366] hover:bg-[#20BD5A] text-white shadow-lg shadow-[#25D366]/25">
              <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>
        </div>

        <p className="text-xs text-muted-foreground pb-4">
          Need help? Contact the charity directly · Ref: {pledge.reference}
        </p>
      </div>
    </>
  )
}
