'use client'

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

interface VipProduct {
  id: string
  productName: string
  price: number
  sellPrice: number
  description: string
  status: boolean
}

interface GameCategory {
  id: string
  name: string
  slug: string
}

export default function GameDetailPage({ params }: { params: { slug: string } }) {
  const { data: session } = useSession()
  const router = useRouter()
  const [category, setCategory] = useState<GameCategory | null>(null)
  const [products, setProducts] = useState<VipProduct[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedProduct, setSelectedProduct] = useState<VipProduct | null>(null)
  const [targetId, setTargetId] = useState('')
  const [zone, setZone] = useState('')
  const [additionalData, setAdditionalData] = useState('')
  const [nickname, setNickname] = useState('')
  const [nickLoading, setNickLoading] = useState(false)
  const [checkoutLoading, setCheckoutLoading] = useState(false)
  const [paymentMethod, setPaymentMethod] = useState<'qris' | 'balance'>('qris')
  const [error, setError] = useState('')
  const [showLoginModal, setShowLoginModal] = useState(false)
  const [voucherCode, setVoucherCode] = useState('')
  const [voucherInfo, setVoucherInfo] = useState<{code: string, discount: number, error?: string} | null>(null)
  const [isValidatingVoucher, setIsValidatingVoucher] = useState(false)

  useEffect(() => {
    fetch(`/api/games/${params.slug}`)
      .then(r => r.json())
      .then(d => { setCategory(d.category); setProducts(d.products || []); setLoading(false) })
      .catch(() => setLoading(false))
  }, [params.slug])

  const checkNickname = useCallback(async () => {
    if (!targetId || !selectedProduct) return
    setNickLoading(true)
    setNickname('')
    try {
      const res = await fetch(`/api/games/${params.slug}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: selectedProduct.id, targetId, zone }),
      })
      const data = await res.json()
      if (data.nickname) setNickname(data.nickname)
      else setNickname('ID tidak ditemukan')
    } catch {
      setNickname('Gagal verifikasi ID')
    }
    setNickLoading(false)
  }, [targetId, zone, selectedProduct, params.slug])

  const applyVoucher = async () => {
    if (!voucherCode || !selectedProduct) return
    setIsValidatingVoucher(true)
    try {
      const res = await fetch('/api/vouchers/validate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: voucherCode, amount: selectedProduct.sellPrice })
      })
      const data = await res.json()
      if (res.ok) {
        setVoucherInfo({ code: data.code, discount: data.discountAmount })
      } else {
        setVoucherInfo({ code: voucherCode, discount: 0, error: data.error })
      }
    } catch (e) {
      setVoucherInfo({ code: voucherCode, discount: 0, error: 'Terjadi kesalahan jaringan' })
    } finally {
      setIsValidatingVoucher(false)
    }
  }

  // Clear voucher when product changes
  useEffect(() => {
    setVoucherInfo(null)
    setVoucherCode('')
  }, [selectedProduct])

  const handleCheckout = async () => {
    if (!session) {
      setShowLoginModal(true)
      return
    }
    if (!selectedProduct) { setError('Pilih nominal terlebih dahulu'); return }
    if (!targetId) { setError('Masukkan ID game kamu'); return }

    setCheckoutLoading(true)
    setError('')
    try {
      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          productType: 'VIP',
          productId: selectedProduct.id,
          targetId,
          zone: zone || undefined,
          additionalData: additionalData || undefined,
          paymentMethod,
          voucherCode: voucherInfo && !voucherInfo.error ? voucherInfo.code : undefined
        }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Gagal membuat order')
      
      if (paymentMethod === 'balance') {
        router.push('/dashboard/orders')
      } else {
        sessionStorage.setItem(`order_${data.order.id}`, JSON.stringify(data.order))
        router.push(`/checkout/${data.order.id}`)
      }
    } catch (err: any) {
      setError(err.message)
    }
    setCheckoutLoading(false)
  }

  const needsZone = category?.name?.toLowerCase().includes('mobile legends') ||
    category?.name?.toLowerCase().includes('arena of valor')

  return (
    <main style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <div style={{ paddingTop: '64px', flex: 1 }}>
        {loading ? (
          <div style={{ maxWidth: '800px', margin: '60px auto', padding: '0 24px' }}>
            <div className="skeleton" style={{ height: 120, borderRadius: 16, marginBottom: 24 }} />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
              {Array(6).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 80, borderRadius: 12 }} />)}
            </div>
          </div>
        ) : !category ? (
          <div style={{ textAlign: 'center', padding: '100px 24px', color: '#64748b' }}>
            <div style={{ fontSize: '48px', marginBottom: 16 }}>😕</div>
            <p>Game tidak ditemukan</p>
          </div>
        ) : (
          <div style={{ maxWidth: '900px', margin: '0 auto', padding: '48px 24px' }}>
            {/* Header */}
            <div className="card glass-accent" style={{ padding: '32px', marginBottom: '32px' }}>
              <h1 className="font-game" style={{ fontSize: '32px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
                🎮 {category.name}
              </h1>
              <p style={{ color: '#64748b', fontSize: '14px' }}>{products.length} produk tersedia</p>
              <p style={{ color: '#94a3b8', fontSize: '14px', marginTop: '4px' }}> Cara Order </p>
              <p style={{ color: '#94a3b8', fontSize: '14px', marginTop: '4px' }}> 1. Pilih Layanan atau Game</p>
              <p style={{ color: '#94a3b8', fontSize: '14px', marginTop: '4px' }}> 2. Masukkan Data Akun</p>
              <p style={{ color: '#94a3b8', fontSize: '14px', marginTop: '4px' }}> 3. Pilih Nominal / Produk</p>
              <p style={{ color: '#94a3b8', fontSize: '14px', marginTop: '4px' }}> 4. Periksa Ringkasan Order</p>
              <p style={{ color: '#94a3b8', fontSize: '14px', marginTop: '4px' }}> 5. Lakukan Pembayaran</p>
              <p style={{ color: '#94a3b8', fontSize: '14px', marginTop: '4px' }}> 6. Transaksi Berhasil</p>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-6">
              
              {/* Left - Products */}
              <div>
                <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#94a3b8', marginBottom: '16px' }}>
                  Pilih Nominal
                </h2>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: '10px', marginBottom: '32px' }}>
                  {products.map(product => (
                    <button
                      key={product.id}
                      onClick={() => setSelectedProduct(product)}
                      style={{
                        padding: '14px 12px',
                        borderRadius: '12px',
                        border: `2px solid ${selectedProduct?.id === product.id ? '#f59e0b' : 'rgba(255,255,255,0.08)'}`,
                        background: selectedProduct?.id === product.id ? 'rgba(245,158,11,0.12)' : '#16161f',
                        color: '#f1f5f9',
                        cursor: 'pointer',
                        textAlign: 'left',
                        transition: 'all 0.2s',
                      }}
                    >
                      <div style={{ fontSize: '12px', fontWeight: 600, marginBottom: '6px', color: '#94a3b8' }}>
                        {product.productName}
                      </div>
                      <div style={{ fontSize: '14px', fontWeight: 700, color: '#f59e0b' }}>
                        {formatRupiah(product.sellPrice)}
                      </div>
                    </button>
                  ))}
                </div>

                {/* DYNAMIC INPUT FIELDS */}
                {(() => {
                  const config = (category.fieldConfig as any) || {}
                  const targetLabel = config.targetLabel || 'User ID'
                  const hasZone = config.hasZone !== false // default true for legacy compatibility
                  const zoneLabel = config.zoneLabel || 'Zone / Server'
                  const zoneType = config.zoneType || 'text'
                  const hasExtra = config.hasExtra === true
                  const extraLabel = config.extraLabel || 'Additional Data'

                  return (
                    <div style={{ marginBottom: '32px' }}>
                      {/* Target Input */}
                      <div style={{ marginBottom: '16px' }}>
                        <label className="label">{targetLabel} *</label>
                        <div style={{ display: 'flex', gap: '8px' }}>
                          <input
                            className="input"
                            placeholder={`Masukkan ${targetLabel}`}
                            value={targetId}
                            onChange={e => { setTargetId(e.target.value); setNickname('') }}
                          />
                          {/* Tombol Cek Nickname hanya aktif jika ada Check Nickname API, default hide unless needed, tapi karena ini legacy kita biarkan dulu */}
                          {!config.targetLabel && (
                            <button
                              className="btn btn-secondary"
                              onClick={checkNickname}
                              disabled={!targetId || nickLoading}
                              style={{ flexShrink: 0, minWidth: 80 }}
                            >
                              {nickLoading ? <span className="spinner" /> : 'Cek'}
                            </button>
                          )}
                        </div>
                        {nickname && !config.targetLabel && (
                          <div style={{
                            marginTop: '8px',
                            padding: '10px 14px',
                            background: nickname.includes('tidak') || nickname.includes('Gagal')
                              ? 'rgba(239,68,68,0.1)' : 'rgba(16,185,129,0.1)',
                            border: `1px solid ${nickname.includes('tidak') || nickname.includes('Gagal') ? 'rgba(239,68,68,0.2)' : 'rgba(16,185,129,0.2)'}`,
                            borderRadius: '8px',
                            fontSize: '13px',
                            color: nickname.includes('tidak') || nickname.includes('Gagal') ? '#ef4444' : '#10b981',
                          }}>
                            {nickname.includes('tidak') || nickname.includes('Gagal') ? '❌' : '✅'} {nickname}
                          </div>
                        )}
                      </div>

                      {/* Zone Input */}
                      {hasZone && (
                        <div style={{ marginBottom: '16px' }}>
                          <label className="label">{zoneLabel} *</label>
                          {zoneType === 'server' ? (
                            <select className="input" value={zone} onChange={e => setZone(e.target.value)}>
                              <option value="">-- Pilih Server --</option>
                              <option value="Asia">Asia</option>
                              <option value="America">America</option>
                              <option value="Europe">Europe</option>
                              <option value="TW, HK, MO">TW, HK, MO</option>
                            </select>
                          ) : (
                            <input
                              className="input"
                              placeholder={`Masukkan ${zoneLabel}`}
                              value={zone}
                              onChange={e => setZone(e.target.value)}
                            />
                          )}
                        </div>
                      )}

                      {/* Extra Input */}
                      {hasExtra && (
                        <div style={{ marginBottom: '16px' }}>
                          <label className="label">{extraLabel} *</label>
                          <input
                            className="input"
                            placeholder={`Masukkan ${extraLabel}`}
                            value={additionalData}
                            onChange={e => setAdditionalData(e.target.value)}
                          />
                        </div>
                      )}
                    </div>
                  )
                })()}
              </div>

              {/* Right - Order Summary */}
              <div>
                <div className="card sticky top-24" style={{ padding: '24px' }}>
                  <h3 style={{ fontSize: '15px', fontWeight: 600, color: '#94a3b8', marginBottom: '20px' }}>
                    Ringkasan Order
                  </h3>

                  {selectedProduct ? (
                    <>
                      <div style={{ marginBottom: '16px' }}>
                        <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '6px' }}>Produk</div>
                        <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0' }}>{selectedProduct.productName}</div>
                      </div>
                      <div style={{ marginBottom: '16px' }}>
                        <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '6px' }}>ID Tujuan</div>
                        <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0' }}>
                          {targetId || '-'}{zone ? ` (${zone})` : ''}
                        </div>
                        {additionalData && (
                          <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0', marginTop: '4px' }}>
                            <span style={{color: '#94a3b8'}}>Ekstra:</span> {additionalData}
                          </div>
                        )}
                      </div>
                      {nickname && !nickname.includes('tidak') && !nickname.includes('Gagal') && (
                        <div style={{ marginBottom: '16px' }}>
                          <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '6px' }}>Nickname</div>
                          <div style={{ fontSize: '14px', fontWeight: 600, color: '#10b981' }}>✅ {nickname}</div>
                        </div>
                      )}
                      <hr style={{ border: 'none', borderTop: '1px solid rgba(255,255,255,0.06)', margin: '16px 0' }} />
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                        <span style={{ color: '#94a3b8', fontSize: '14px' }}>Total</span>
                        <span style={{ color: '#f59e0b', fontSize: '20px', fontWeight: 700 }}>
                          {formatRupiah(selectedProduct.sellPrice)}
                        </span>
                      </div>
                      
                      {/* VOUCHER SECTION */}
                      <div style={{ marginTop: '20px', padding: '16px', background: 'rgba(255,255,255,0.03)', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)' }}>
                        <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '8px', fontWeight: 600 }}>Punya Kode Voucher?</div>
                        <div style={{ display: 'flex', gap: '8px' }}>
                          <input 
                            type="text" 
                            className="input" 
                            placeholder="Masukkan kode promo" 
                            value={voucherCode}
                            onChange={e => setVoucherCode(e.target.value.toUpperCase())}
                            style={{ flex: 1, textTransform: 'uppercase', fontSize: '14px', padding: '10px 14px' }}
                            disabled={isValidatingVoucher || (voucherInfo && !voucherInfo.error ? true : false)}
                          />
                          {(voucherInfo && !voucherInfo.error) ? (
                            <button 
                              className="btn btn-secondary" 
                              onClick={() => { setVoucherInfo(null); setVoucherCode('') }}
                              style={{ padding: '0 16px', fontSize: '13px' }}
                            >
                              Hapus
                            </button>
                          ) : (
                            <button 
                              className="btn btn-primary" 
                              onClick={applyVoucher}
                              disabled={!voucherCode || isValidatingVoucher}
                              style={{ padding: '0 16px', fontSize: '13px' }}
                            >
                              {isValidatingVoucher ? 'Cek...' : 'Pakai'}
                            </button>
                          )}
                        </div>
                        {voucherInfo?.error && (
                          <div style={{ fontSize: '12px', color: '#ef4444', marginTop: '8px' }}>❌ {voucherInfo.error}</div>
                        )}
                        {voucherInfo && !voucherInfo.error && (
                          <div style={{ fontSize: '12px', color: '#10b981', marginTop: '8px' }}>✅ Voucher <b>{voucherInfo.code}</b> berhasil dipakai! (Diskon {formatRupiah(voucherInfo.discount)})</div>
                        )}
                      </div>

                      {voucherInfo && !voucherInfo.error && (
                        <>
                          <hr style={{ border: 'none', borderTop: '1px dashed rgba(255,255,255,0.1)', margin: '16px 0' }} />
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                            <span style={{ color: '#10b981', fontSize: '15px', fontWeight: 600 }}>Total Bayar</span>
                            <span style={{ color: '#10b981', fontSize: '24px', fontWeight: 800 }}>
                              {formatRupiah(Number(selectedProduct.sellPrice) - voucherInfo.discount)}
                            </span>
                          </div>
                        </>
                      )}
                    </>
                  ) : (
                    <div style={{ textAlign: 'center', padding: '20px 0', color: '#475569', fontSize: '14px' }}>
                      Pilih nominal untuk melanjutkan
                    </div>
                  )}

                  {selectedProduct && (
                    <div style={{ marginBottom: '20px' }}>
                      <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '8px' }}>Pilih Metode Pembayaran</div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                        <button
                          className={`btn ${paymentMethod === 'qris' ? 'btn-primary' : ''}`}
                          style={{ 
                            background: paymentMethod === 'qris' ? 'rgba(245,158,11,0.1)' : 'rgba(255,255,255,0.05)',
                            border: `1px solid ${paymentMethod === 'qris' ? '#f59e0b' : 'rgba(255,255,255,0.1)'}`,
                            color: paymentMethod === 'qris' ? '#f59e0b' : '#94a3b8',
                            justifyContent: 'flex-start', padding: '12px',
                          }}
                          onClick={() => setPaymentMethod('qris')}
                        >
                          📱 QRIS (Instan)
                        </button>
                        <button
                          className={`btn ${paymentMethod === 'balance' ? 'btn-primary' : ''}`}
                          style={{ 
                            background: paymentMethod === 'balance' ? 'rgba(16,185,129,0.1)' : 'rgba(255,255,255,0.05)',
                            border: `1px solid ${paymentMethod === 'balance' ? '#10b981' : 'rgba(255,255,255,0.1)'}`,
                            color: paymentMethod === 'balance' ? '#10b981' : '#94a3b8',
                            justifyContent: 'space-between', padding: '12px',
                          }}
                          onClick={() => setPaymentMethod('balance')}
                        >
                          <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            💰 Saldo Akun
                          </span>
                          {session?.user && (
                            <span style={{ fontSize: '12px', fontWeight: 600 }}>
                              {formatRupiah(Number((session.user as any).balance || 0))}
                            </span>
                          )}
                        </button>
                      </div>
                      {paymentMethod === 'balance' && session?.user && Number((session.user as any).balance || 0) < selectedProduct.sellPrice && (
                        <div style={{ marginTop: '8px', fontSize: '12px', color: '#ef4444' }}>
                          Saldo tidak mencukupi. Silakan topup terlebih dahulu.
                        </div>
                      )}
                    </div>
                  )}

                  {error && (
                    <div style={{ marginBottom: '12px', padding: '10px', background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: '8px', color: '#ef4444', fontSize: '13px' }}>
                      {error}
                    </div>
                  )}

                  <button
                    className="btn btn-primary"
                    style={{ width: '100%', fontSize: '14px', padding: '12px' }}
                    disabled={
                      !selectedProduct || 
                      !targetId || 
                      checkoutLoading || 
                      (paymentMethod === 'balance' && session?.user && Number((session.user as any).balance || 0) < selectedProduct.sellPrice)
                    }
                    onClick={handleCheckout}
                  >
                    {checkoutLoading ? <><span className="spinner" /> Memproses...</> : '⚡ Bayar Sekarang'}
                  </button>

                  <p style={{ textAlign: 'center', fontSize: '12px', color: '#475569', marginTop: '12px' }}>
                    {paymentMethod === 'qris' ? 'Bayar via QRIS • Proses Instan' : 'Bayar via Saldo • Proses Instan Tanpa Admin'}
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Login Modal */}
      {showLoginModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)' }} onClick={() => setShowLoginModal(false)} />
          <div className="card animate-slide-in" style={{ position: 'relative', width: '100%', maxWidth: '400px', padding: '32px', textAlign: 'center' }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>🔐</div>
            <h2 style={{ fontSize: '24px', fontWeight: 700, color: '#f1f5f9', marginBottom: '12px' }}>Login Diperlukan</h2>
            <p style={{ color: '#94a3b8', fontSize: '14px', marginBottom: '24px', lineHeight: 1.5 }}>
              Untuk menjamin keamanan dan memudahkan pelacakan pesanan Anda, silakan login terlebih dahulu sebelum melakukan pembayaran.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
              <button onClick={() => router.push('/auth/login')} className="btn btn-primary" style={{ padding: '12px' }}>
                Login ke Akun Saya
              </button>
              <button onClick={() => setShowLoginModal(false)} className="btn btn-secondary" style={{ padding: '12px' }}>
                Batal
              </button>
            </div>
          </div>
        </div>
      )}

      <Footer />
    </main>
  )
}
