'use client'

import { useState, useEffect, useCallback } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Navbar from '@/components/Navbar'
import { formatRupiah } from '@/lib/utils'

export default function WalletPayPage() {
  const params = useParams()
  const router = useRouter()
  const [invoice, setInvoice] = useState<any>(null)
  const [paymentStatus, setPaymentStatus] = useState<string>('pending')
  const [timeLeft, setTimeLeft] = useState<number>(0)

  useEffect(() => {
    const saved = sessionStorage.getItem(`topup_${params.id}`)
    if (saved) {
      const data = JSON.parse(saved)
      setInvoice(data)
      const exp = new Date(data.expiresAt).getTime() - Date.now()
      setTimeLeft(Math.max(0, Math.floor(exp / 1000)))
    } else {
      router.push('/dashboard/wallet')
    }
  }, [params.id, router])

  useEffect(() => {
    if (timeLeft <= 0) return
    const timer = setInterval(() => {
      setTimeLeft(t => {
        if (t <= 1) { clearInterval(timer); return 0 }
        return t - 1
      })
    }, 1000)
    return () => clearInterval(timer)
  }, [timeLeft])

  const pollStatus = useCallback(async () => {
    if (!invoice?.invoiceId || paymentStatus === 'paid') return
    try {
      const res = await fetch('/api/payment/check-status', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ transactionId: invoice.invoiceId }),
      })
      const data = await res.json()
      if (data.status === 'paid' || data.status === 'success') {
        setPaymentStatus('paid')
        // Process topup webhook manually if polling hits first
        await fetch('/api/payment/process', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ transactionId: invoice.invoiceId, status: 'paid' }),
        })
        setTimeout(() => router.push(`/dashboard/wallet`), 3000)
      } else {
        setPaymentStatus(data.status)
      }
    } catch {}
  }, [invoice, paymentStatus, router])

  useEffect(() => {
    if (!invoice || paymentStatus === 'paid') return
    const interval = setInterval(pollStatus, 3000)
    return () => clearInterval(interval)
  }, [invoice, pollStatus, paymentStatus])

  if (!invoice) return <main><Navbar /><div className="spinner" style={{ margin: '100px auto', display: 'block' }}/></main>

  const mins = Math.floor(timeLeft / 60).toString().padStart(2, '0')
  const secs = (timeLeft % 60).toString().padStart(2, '0')

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f' }}>
      <Navbar />
      <div style={{ paddingTop: '80px', padding: '80px 24px 60px', maxWidth: '580px', margin: '0 auto' }}>
        {paymentStatus === 'paid' ? (
          <div className="card" style={{ padding: '60px 40px', textAlign: 'center' }}>
            <div style={{ fontSize: '64px', marginBottom: '20px', animation: 'float 1s ease-in-out' }}>✅</div>
            <h1 style={{ fontSize: '28px', fontWeight: 700, color: '#10b981', marginBottom: '12px' }}>Topup Berhasil!</h1>
            <p style={{ color: '#64748b', marginBottom: '8px' }}>Saldo kamu telah ditambahkan.</p>
            <p style={{ color: '#475569', fontSize: '13px' }}>Akan diarahkan ke dompet dalam 3 detik</p>
          </div>
        ) : (
          <div>
            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
              <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>⚡ Bayar Topup Saldo</h1>
              <p style={{ color: '#64748b', fontSize: '14px' }}>Scan QR Code untuk menyelesaikan</p>
            </div>
            <div className="card" style={{ padding: '32px', textAlign: 'center', marginBottom: '20px' }}>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: '8px',
                background: timeLeft < 120 ? 'rgba(239,68,68,0.1)' : 'rgba(245,158,11,0.1)',
                border: `1px solid ${timeLeft < 120 ? 'rgba(239,68,68,0.2)' : 'rgba(245,158,11,0.2)'}`,
                borderRadius: '100px', padding: '8px 20px', marginBottom: '24px',
              }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: timeLeft < 120 ? '#ef4444' : '#f59e0b', display: 'inline-block' }} />
                <span style={{ fontFamily: 'monospace', fontSize: '18px', fontWeight: 700, color: timeLeft < 120 ? '#ef4444' : '#f59e0b' }}>
                  {mins}:{secs}
                </span>
                <span style={{ fontSize: '12px', color: '#64748b' }}>tersisa</span>
              </div>

              {invoice.qrImageUrl ? (
                <div className="qr-container" style={{ margin: '0 auto 24px', display: 'inline-block' }}>
                  <img src={invoice.qrImageUrl} alt="QR Code" style={{ width: 220, height: 220, borderRadius: '8px', display: 'block' }} />
                </div>
              ) : (
                <div style={{ width: 220, height: 220, margin: '0 auto 24px', background: '#fff', borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#000', fontSize: 12, padding: 12, wordBreak: 'break-all' }}>
                  {invoice.qrString?.substring(0, 100)}...
                </div>
              )}

              <div style={{ marginBottom: '8px' }}>
                <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '4px' }}>Bayar tepat</div>
                <div style={{ fontSize: '32px', fontWeight: 800, color: '#f59e0b' }}>{formatRupiah(invoice.totalAmount)}</div>
                {invoice.uniqueCode > 0 && <div style={{ fontSize: '12px', color: '#475569', marginTop: '4px' }}>(termasuk kode unik +{invoice.uniqueCode})</div>}
              </div>
            </div>
            <div style={{ textAlign: 'center', marginTop: '16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', color: '#64748b', fontSize: '13px' }}>
                <span className="spinner" style={{ width: 14, height: 14 }} /> Menunggu pembayaran...
              </div>
            </div>
          </div>
        )}
      </div>
    </main>
  )
}
