"use client"

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

interface Props {
  pledge: {
    id: string
    reference: string
    bankDetails?: {
      bankName: string
      sortCode: string
      accountNo: string
      accountName: string
    }
  }
  amount: number
  eventName: string
  donorPhone?: string
}

export function BankInstructionsStep({ pledge, amount, eventName, donorPhone }: Props) {
  const [copiedField, setCopiedField] = useState<string | null>(null)
  const [markedPaid, setMarkedPaid] = useState(false)
  const [whatsappSent, setWhatsappSent] = useState(false)

  const bd = pledge.bankDetails

  // Send bank details to WhatsApp
  useEffect(() => {
    if (!donorPhone || whatsappSent) return
    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: "bank",
          bankDetails: bd ? { sortCode: bd.sortCode, accountNo: bd.accountNo, accountName: bd.accountName } : undefined,
        },
      }),
    }).then(() => setWhatsappSent(true)).catch(() => {})
  }, [donorPhone, whatsappSent, amount, eventName, pledge.reference, bd])

  const copyField = async (value: string, field: string) => {
    await navigator.clipboard.writeText(value)
    setCopiedField(field)
    if (navigator.vibrate) navigator.vibrate(10)
    setTimeout(() => setCopiedField(null), 2000)
    // Track
    fetch("/api/analytics", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ eventType: "instruction_copy_clicked", pledgeId: pledge.id, metadata: { field } }),
    }).catch(() => {})
  }

  const handleIPaid = async () => {
    setMarkedPaid(true)
    if (navigator.vibrate) navigator.vibrate([10, 50, 10])
    fetch(`/api/pledges/${pledge.id}/mark-initiated`, { method: "POST" }).catch(() => {})
    fetch("/api/analytics", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ eventType: "i_paid_clicked", pledgeId: pledge.id }),
    }).catch(() => {})
  }

  // Post-payment view
  if (markedPaid) {
    return (
      <div className="max-w-md mx-auto pt-8 text-center space-y-6 animate-fade-up">
        <div className="relative inline-flex items-center justify-center">
          <div className="absolute w-20 h-20 rounded-full bg-success-green/20 animate-pulse-ring" />
          <div className="relative w-20 h-20 rounded-full bg-gradient-to-br from-success-green to-emerald-500 flex items-center justify-center shadow-xl shadow-success-green/30">
            <Check className="h-10 w-10 text-white" strokeWidth={3} />
          </div>
        </div>
        <h1 className="text-2xl font-black text-gray-900">Thank you!</h1>
        <p className="text-muted-foreground">
          We&apos;ll confirm once your <span className="font-bold text-foreground">£{(amount / 100).toFixed(0)}</span> is received.
        </p>

        {whatsappSent && (
          <div className="rounded-xl 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" /> Details sent to your WhatsApp ✓
          </div>
        )}

        <Card className="text-left">
          <CardContent className="pt-4 space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-muted-foreground">Reference</span>
              <span className="font-mono font-bold text-trust-blue">{pledge.reference}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">Event</span>
              <span>{eventName}</span>
            </div>
          </CardContent>
        </Card>

        {/* Share */}
        <div className="rounded-2xl bg-gradient-to-br from-warm-amber/5 to-orange-50 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">Know someone who&apos;d donate too?</p>
          </div>
          <div className="flex gap-2">
            <Button
              onClick={() => {
                const text = `I just pledged £${(amount / 100).toFixed(0)} to ${eventName}! 🤲\nPledge here: ${window.location.href}`
                window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank")
              }}
              className="flex-1 bg-[#25D366] hover:bg-[#20BD5A] text-white shadow-lg shadow-[#25D366]/25"
              size="sm"
            >
              <MessageCircle className="h-4 w-4 mr-1" /> WhatsApp
            </Button>
            <Button
              onClick={() => navigator.share?.({ title: eventName, text: `Pledge to ${eventName}`, url: window.location.href })}
              variant="outline"
              size="sm"
              className="flex-1"
            >
              <Share2 className="h-4 w-4 mr-1" /> Share
            </Button>
          </div>
        </div>

        <p className="text-xs text-muted-foreground">
          Payments usually arrive within 2 hours. We&apos;ll email you once confirmed.
        </p>
      </div>
    )
  }

  // Copy-able field component
  const CopyField = ({ label, value, fieldKey, mono }: { label: string; value: string; fieldKey: string; mono?: boolean }) => (
    <button
      onClick={() => copyField(value, fieldKey)}
      className="flex items-center justify-between w-full py-2.5 px-0 group"
    >
      <div className="text-left">
        <p className="text-[10px] text-muted-foreground uppercase tracking-wider font-medium">{label}</p>
        <p className={`font-bold text-lg ${mono ? "font-mono" : ""} text-gray-900`}>{value}</p>
      </div>
      <div className={`rounded-lg px-2.5 py-1.5 text-xs font-medium transition-all ${
        copiedField === fieldKey
          ? "bg-success-green text-white"
          : "bg-gray-100 text-gray-500 group-hover:bg-trust-blue/10 group-hover:text-trust-blue"
      }`}>
        {copiedField === fieldKey ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
      </div>
    </button>
  )

  return (
    <div className="max-w-md mx-auto pt-2 space-y-5 animate-fade-up">
      <div className="text-center space-y-2">
        <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-gradient-to-br from-trust-blue to-blue-600 shadow-lg shadow-trust-blue/30">
          <span className="text-2xl">🏦</span>
        </div>
        <h1 className="text-2xl font-black text-gray-900 tracking-tight">
          Transfer £{(amount / 100).toFixed(0)}
        </h1>
        <p className="text-sm text-muted-foreground">
          Tap any field to copy · Use your banking app
        </p>
      </div>

      {whatsappSent && (
        <div className="rounded-xl bg-[#25D366]/10 border border-[#25D366]/20 p-2.5 text-xs text-[#25D366] font-medium flex items-center justify-center gap-2 animate-fade-in">
          <MessageCircle className="h-3.5 w-3.5" /> Bank details also sent to your WhatsApp
        </div>
      )}

      {/* Bank details — tap to copy each field */}
      {bd && (
        <Card className="overflow-hidden">
          <div className="h-1 bg-gradient-to-r from-trust-blue to-blue-400" />
          <CardContent className="pt-4 divide-y">
            <CopyField label="Sort Code" value={bd.sortCode} fieldKey="sortCode" mono />
            <CopyField label="Account Number" value={bd.accountNo} fieldKey="accountNo" mono />
            <CopyField label="Account Name" value={bd.accountName} fieldKey="accountName" />
          </CardContent>
        </Card>
      )}

      {/* THE reference — the most important thing */}
      <div className="rounded-2xl border-2 border-trust-blue bg-gradient-to-br from-trust-blue/5 to-blue-50 p-5 text-center space-y-3">
        <p className="text-xs font-bold text-trust-blue uppercase tracking-widest">
          Payment Reference
        </p>
        <button
          onClick={() => copyField(pledge.reference, "reference")}
          className="group"
        >
          <p className="text-3xl font-mono font-black text-trust-blue tracking-wider group-hover:scale-105 transition-transform">
            {pledge.reference}
          </p>
        </button>
        <Button
          onClick={() => copyField(pledge.reference, "reference")}
          variant={copiedField === "reference" ? "success" : "default"}
          className="w-full"
        >
          {copiedField === "reference" ? (
            <><Check className="h-5 w-5 mr-2" /> Copied!</>
          ) : (
            <><Copy className="h-5 w-5 mr-2" /> Copy Reference</>
          )}
        </Button>
        <p className="text-[11px] text-trust-blue/70">
          ⚠️ Use this exact reference so we can match your payment
        </p>
      </div>

      {/* Open banking app hint */}
      <div className="rounded-xl bg-warm-amber/5 border border-warm-amber/20 p-3 text-center">
        <p className="text-xs font-medium text-warm-amber flex items-center justify-center gap-1.5">
          <ExternalLink className="h-3.5 w-3.5" />
          Open your banking app → New payment → Paste the details
        </p>
      </div>

      {/* I've paid */}
      <Button size="xl" variant="success" className="w-full" onClick={handleIPaid}>
        I&apos;ve Sent the Payment ✓
      </Button>

      <p className="text-center text-xs text-muted-foreground">
        Payments usually arrive within 2 hours. No rush — transfer at your convenience.
      </p>
    </div>
  )
}
