import { useState, useEffect, useRef } from 'react'
import { X, Copy, CheckCircle, Clock, RefreshCw } from 'lucide-react'
import { RaffleAPI } from '../api'

interface Props {
  orderId: number
  pixCode: string
  pixQr?: string
  amount: number
  onClose: () => void
  onConfirmed: () => void
}

export default function PixModal({ orderId, pixCode, pixQr, amount, onClose, onConfirmed }: Props) {
  const [copied, setCopied] = useState(false)
  const [status, setStatus] = useState<'pending' | 'confirmed' | 'expired'>('pending')
  const [elapsed, setElapsed] = useState(0)
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const MAX_SECONDS = 300

  function copy() {
    navigator.clipboard.writeText(pixCode).then(() => {
      setCopied(true)
      setTimeout(() => setCopied(false), 2500)
    })
  }

  useEffect(() => {
    // Countdown timer
    intervalRef.current = setInterval(() => {
      setElapsed(s => {
        if (s >= MAX_SECONDS - 1) {
          clearInterval(intervalRef.current!)
          setStatus('expired')
          return s
        }
        return s + 1
      })
    }, 1000)

    // Poll payment status every 5s
    pollRef.current = setInterval(async () => {
      try {
        const data = await RaffleAPI.getOrderStatus(orderId)
        if (data.status === 'paid' || data.status === 'confirmed') {
          setStatus('confirmed')
          clearInterval(pollRef.current!)
          clearInterval(intervalRef.current!)
          setTimeout(onConfirmed, 1500)
        }
      } catch {}
    }, 5000)

    return () => {
      clearInterval(intervalRef.current!)
      clearInterval(pollRef.current!)
    }
  }, [orderId])

  const remaining = MAX_SECONDS - elapsed
  const minutes = Math.floor(remaining / 60)
  const seconds = remaining % 60

  return (
    <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-md overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <div>
            <h3 className="text-lg font-black text-white">Pagar via PIX</h3>
            <p className="text-sm text-slate-400">R$ {Number(amount).toFixed(2).replace('.', ',')}</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors p-1">
            <X size={20} />
          </button>
        </div>

        <div className="p-6 space-y-5">
          {status === 'confirmed' && (
            <div className="flex flex-col items-center gap-3 py-8">
              <CheckCircle size={56} className="text-emerald-400" />
              <p className="text-xl font-black text-white">Pagamento confirmado!</p>
              <p className="text-slate-400 text-sm text-center">Seus números estão garantidos. Boa sorte! 🍀</p>
            </div>
          )}

          {status === 'expired' && (
            <div className="flex flex-col items-center gap-3 py-8">
              <Clock size={48} className="text-amber-400" />
              <p className="text-lg font-black text-white">Tempo expirado</p>
              <p className="text-slate-400 text-sm text-center">O tempo de pagamento expirou. Tente novamente.</p>
              <button onClick={onClose}
                className="mt-2 px-6 py-2.5 bg-amber-500 hover:bg-amber-400 text-black font-black rounded-xl text-sm transition-colors">
                Fechar
              </button>
            </div>
          )}

          {status === 'pending' && (
            <>
              {pixQr && (
                <div className="flex justify-center">
                  <div className="bg-white p-3 rounded-2xl">
                    <img src={`data:image/png;base64,${pixQr}`} alt="QR Code PIX" className="w-44 h-44 object-contain" />
                  </div>
                </div>
              )}

              <div>
                <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Código Copia e Cola</p>
                <div className="bg-slate-800 rounded-xl p-3 flex items-start gap-3">
                  <p className="text-xs text-slate-300 flex-1 break-all font-mono leading-relaxed">{pixCode}</p>
                  <button onClick={copy}
                    className="shrink-0 p-1.5 rounded-lg bg-slate-700 hover:bg-slate-600 transition-colors text-slate-300">
                    {copied ? <CheckCircle size={15} className="text-emerald-400" /> : <Copy size={15} />}
                  </button>
                </div>
              </div>

              <div className="flex items-center justify-between bg-slate-800/50 rounded-xl px-4 py-3">
                <div className="flex items-center gap-2 text-slate-400">
                  <RefreshCw size={14} className="animate-spin" />
                  <span className="text-xs">Aguardando pagamento…</span>
                </div>
                <span className={`text-sm font-black tabular-nums ${remaining < 60 ? 'text-rose-400' : 'text-amber-400'}`}>
                  {String(minutes).padStart(2, '0')}:{String(seconds).padStart(2, '0')}
                </span>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
