'use client'

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

interface OrderData {
  id: string
  productName: string
  price: number
  totalAmount: number
  uniqueCode: number
  status: string
  invoiceId: string
  qrString: string
  qrImageUrl: string
  expiresAt: string
}

export default function CheckoutPage() {
  const params = useParams()
  const router = useRouter()
  const { data: session } = useSession()
  const [order, setOrder] = useState<OrderData | null>(null)
  const [paymentStatus, setPaymentStatus] = useState<string>('pending')
  const [timeLeft, setTimeLeft] = useState<number>(0)
  const [loading, setLoading] = useState(true)

  // Fetch order data from session storage (passed from order creation)
  useEffect(() => {
    const saved = sessionStorage.getItem(`order_${params.id}`)
    if (saved) {
      const data = JSON.parse(saved)
      setOrder(data)
      const exp = new Date(data.expiresAt).getTime() - Date.now()
      setTimeLeft(Math.max(0, Math.floor(exp / 1000)))
    } else {
      // Fetch from API
      fetch(`/api/orders/${params.id}`)
        .then(r => r.json())
        .then(d => { if (d.order) setOrder(d.order); setLoading(false) })
        .catch(() => setLoading(false))
    }
    setLoading(false)
  }, [params.id])

  // Countdown timer
  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])

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

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

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

  if (loading) return (
    <main><Navbar /><div style={{ paddingTop: 100, textAlign: 'center' }}><span className="spinner" /></div></main>
  )

  if (!order) return (
    <main><Navbar />
      <div style={{ paddingTop: 100, textAlign: 'center', color: '#64748b', padding: '100px 24px' }}>
        <p>Order tidak ditemukan</p>
      </div>
    </main>
  )

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f' }}>
      <Navbar />
      <div style={{ paddingTop: '80px', padding: '80px 24px 60px', maxWidth: '580px', margin: '0 auto' }}>
        
        {paymentStatus === 'paid' ? (
          /* SUCCESS STATE */
          <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' }}>
              Pembayaran Berhasil!
            </h1>
            <p style={{ color: '#64748b', marginBottom: '8px' }}>Order sedang diproses...</p>
            <p style={{ color: '#475569', fontSize: '13px' }}>Kamu akan diarahkan ke dashboard dalam 3 detik</p>
          </div>
        ) : (
          /* PAYMENT QR */
          <div>
            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
              <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
                ⚡ Selesaikan Pembayaran
              </h1>
              <p style={{ color: '#64748b', fontSize: '14px' }}>Scan QR Code di bawah untuk membayar</p>
            </div>

            <div className="card" style={{ padding: '32px', textAlign: 'center', marginBottom: '20px' }}>
              {/* Timer */}
              <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>

              {/* QR Code */}
              {order.qrImageUrl ? (
                <div className="qr-container" style={{ margin: '0 auto 24px', display: 'inline-block' }}>
                  <img src={order.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' }}>
                  {order.qrString?.substring(0, 100)}...
                </div>
              )}

              {/* Amount */}
              <div style={{ marginBottom: '8px' }}>
                <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '4px' }}>Bayar tepat</div>
                <div style={{ fontSize: '32px', fontWeight: 800, color: '#f59e0b' }}>
                  {formatRupiah(order.totalAmount)}
                </div>
                {order.uniqueCode > 0 && (
                  <div style={{ fontSize: '12px', color: '#475569', marginTop: '4px' }}>
                    (termasuk kode unik +{order.uniqueCode})
                  </div>
                )}
              </div>

              <div style={{
                background: 'rgba(245,158,11,0.06)',
                border: '1px solid rgba(245,158,11,0.15)',
                borderRadius: '10px',
                padding: '12px 16px',
                fontSize: '12px',
                color: '#94a3b8',
                marginTop: '16px',
              }}>
                ⚠️ Bayar <strong>tepat sesuai nominal</strong> di atas termasuk kode unik agar transaksi terdeteksi otomatis
              </div>
            </div>

            {/* Order Details */}
            <div className="card" style={{ padding: '20px 24px' }}>
              <h3 style={{ fontSize: '14px', fontWeight: 600, color: '#94a3b8', marginBottom: '14px' }}>Detail Order</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                {[
                  { label: 'Order ID', value: `#${order.id.slice(-8).toUpperCase()}` },
                  { label: 'Produk', value: order.productName },
                  { label: 'Harga', value: formatRupiah(order.price) },
                ].map(item => (
                  <div key={item.label} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '14px' }}>
                    <span style={{ color: '#64748b' }}>{item.label}</span>
                    <span style={{ color: '#e2e8f0', fontWeight: 500 }}>{item.value}</span>
                  </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>
  )
}
