"use client"

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

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

export function BankInstructionsStep({ pledge, amount, eventName }: Props) {
  const [copied, setCopied] = useState(false)
  const [markedPaid, setMarkedPaid] = useState(false)

  const copyReference = async () => {
    await navigator.clipboard.writeText(pledge.reference)
    setCopied(true)
    setTimeout(() => setCopied(false), 3000)
    // Track
    fetch("/api/analytics", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ eventType: "instruction_copy_clicked", pledgeId: pledge.id }),
    }).catch(() => {})
  }

  const handleIPaid = async () => {
    setMarkedPaid(true)
    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(() => {})
  }

  const bd = pledge.bankDetails

  if (markedPaid) {
    return (
      <div className="max-w-md mx-auto pt-8 text-center space-y-6">
        <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-success-green/10">
          <Check className="h-10 w-10 text-success-green" />
        </div>
        <h1 className="text-2xl font-extrabold text-gray-900">Thank you!</h1>
        <p className="text-muted-foreground">
          We&apos;ll confirm once your payment of <span className="font-bold text-foreground">£{(amount / 100).toFixed(2)}</span> is received.
        </p>
        <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">{pledge.reference}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">Event</span>
              <span>{eventName}</span>
            </div>
          </CardContent>
        </Card>
        <p className="text-xs text-muted-foreground">
          Need help? Contact the charity directly.
        </p>
      </div>
    )
  }

  return (
    <div className="max-w-md mx-auto pt-4 space-y-6">
      <div className="text-center space-y-2">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-trust-blue/10 mb-2">
          <span className="text-3xl">🏦</span>
        </div>
        <h1 className="text-2xl font-extrabold text-gray-900">
          Transfer £{(amount / 100).toFixed(2)}
        </h1>
        <p className="text-muted-foreground">
          Use these details in your banking app
        </p>
      </div>

      {/* Bank details card */}
      {bd && (
        <Card>
          <CardContent className="pt-6 space-y-4">
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <p className="text-muted-foreground text-xs uppercase tracking-wider">Sort Code</p>
                <p className="font-mono font-bold text-lg">{bd.sortCode}</p>
              </div>
              <div>
                <p className="text-muted-foreground text-xs uppercase tracking-wider">Account No</p>
                <p className="font-mono font-bold text-lg">{bd.accountNo}</p>
              </div>
            </div>
            <div className="text-sm">
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Account Name</p>
              <p className="font-semibold">{bd.accountName}</p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Reference - THE KEY */}
      <div className="rounded-2xl border-2 border-trust-blue bg-trust-blue/5 p-6 text-center space-y-3">
        <p className="text-xs font-semibold text-trust-blue uppercase tracking-wider">
          Payment Reference — use exactly:
        </p>
        <p className="text-3xl font-mono font-extrabold text-trust-blue tracking-wider">
          {pledge.reference}
        </p>
        <Button
          onClick={copyReference}
          variant={copied ? "success" : "default"}
          size="lg"
          className="w-full"
        >
          {copied ? (
            <>
              <Check className="h-5 w-5 mr-2" /> Copied!
            </>
          ) : (
            <>
              <Copy className="h-5 w-5 mr-2" /> Copy Reference
            </>
          )}
        </Button>
      </div>

      {/* Suggestion */}
      <div className="rounded-2xl bg-warm-amber/5 border border-warm-amber/20 p-4 text-center">
        <p className="text-sm font-medium text-warm-amber">
          <ExternalLink className="h-4 w-4 inline mr-1" />
          Open your banking app now and search for &quot;new payment&quot;
        </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 take 1-2 hours to arrive. We&apos;ll confirm once received.
      </p>
    </div>
  )
}
