'use client'

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

export const dynamic = 'force-dynamic'

export default function DigitalProductsPage() {
  const router = useRouter()
  const { data: session } = useSession()
  const [products, setProducts] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [checkoutLoading, setCheckoutLoading] = useState(false)
  const [selectedProduct, setSelectedProduct] = useState<any | null>(null)
  const [paymentMethod, setPaymentMethod] = useState<'qris' | 'balance'>('qris')
  const [showLoginModal, setShowLoginModal] = useState(false)
  const [search, setSearch] = useState(() => {
    if (typeof window !== 'undefined') {
      return new URLSearchParams(window.location.search).get('search') || ''
    }
    return ''
  })

  useEffect(() => {
    fetch(`/api/products${search ? `?search=${search}` : ''}`)
      .then(r => r.json())
      .then(d => { setProducts(d.products || []); setLoading(false) })
      .catch(() => setLoading(false))
  }, [search])

  const openCheckoutModal = (product: any) => {
    if (!session) {
      setShowLoginModal(true)
      return
    }
    setSelectedProduct(product)
    setPaymentMethod('qris')
  }

  const handleConfirmCheckout = async () => {
    if (!session || !selectedProduct) return
    setCheckoutLoading(true)

    try {
      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          productType: 'DIGITAL', 
          productId: selectedProduct.id,
          paymentMethod 
        }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      
      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) {
      alert(err.message)
      setCheckoutLoading(false)
    }
  }

  const getIcon = (name: string) => {
    const n = name.toLowerCase()
    if (n.includes('netflix')) return { icon: '🎬', color: '#ef4444' }
    if (n.includes('spotify')) return { icon: '🎵', color: '#10b981' }
    if (n.includes('youtube')) return { icon: '▶️', color: '#ef4444' }
    if (n.includes('canva')) return { icon: '🎨', color: '#8b5cf6' }
    if (n.includes('chatgpt') || n.includes('gpt')) return { icon: '🤖', color: '#10b981' }
    if (n.includes('disney')) return { icon: '✨', color: '#3b82f6' }
    if (n.includes('prime') || n.includes('amazon')) return { icon: '📦', color: '#06b6d4' }
    return { icon: '📱', color: '#f59e0b' }
  }

  return (
    <main style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <div style={{ paddingTop: '64px', flex: 1 }}>
        <div style={{ background: 'linear-gradient(135deg, rgba(139,92,246,0.06) 0%, rgba(245,158,11,0.04) 100%)', borderBottom: '1px solid rgba(255,255,255,0.06)', padding: '50px 24px' }}>
          <div style={{ maxWidth: '1280px', margin: '0 auto' }}>
            <h1 className="font-game" style={{ fontSize: '40px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
              📱 App <span className="gradient-text">Premium</span>
            </h1>
            <p style={{ color: '#64748b', fontSize: '15px', marginBottom: '24px' }}>
              Akun premium legal bergaransi, harga lebih murah dari official
            </p>
            <input className="input" style={{ maxWidth: '400px' }} placeholder="🔍 Cari aplikasi (cth: Netflix, Canva)..." value={search} onChange={e => setSearch(e.target.value)} />
          </div>
        </div>

        <div style={{ maxWidth: '1280px', margin: '0 auto', padding: '48px 24px' }}>
          {loading ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '20px' }}>
              {Array(6).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: '220px', borderRadius: '16px' }} />)}
            </div>
          ) : products.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 20px', color: '#475569' }}>
              <div style={{ fontSize: '48px', marginBottom: '16px' }}>📱</div>
              <p>Belum ada produk digital yang tersedia.</p>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '24px' }}>
              {products.map(product => {
                const { icon, color } = getIcon(product.name)
                return (
                  <div key={product.id} className="card" style={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                    <div style={{ display: 'flex', gap: '16px', marginBottom: '16px' }}>
                      <div style={{ width: 60, height: 60, borderRadius: '16px', background: `${color}15`, border: `1px solid ${color}30`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '32px', flexShrink: 0 }}>
                        {icon}
                      </div>
                      <div>
                        <h3 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '4px', lineHeight: 1.3 }}>{product.name}</h3>
                        <div style={{ fontSize: '18px', fontWeight: 700, color: '#f59e0b' }}>{formatRupiah(product.price)}</div>
                      </div>
                    </div>
                    
                    <p style={{ color: '#94a3b8', fontSize: '13px', lineHeight: 1.6, marginBottom: '20px', flex: 1, whiteSpace: 'pre-wrap' }}>
                      {product.description || 'Akun premium legal bergaransi full.'}
                    </p>

                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span className="badge badge-purple" style={{ fontSize: '11px' }}>{product.type === 'AUTO' ? '⚡ Instan' : '⏳ Manual'}</span>
                      <button className="btn btn-primary" style={{ padding: '8px 20px', fontSize: '13px' }} onClick={() => openCheckoutModal(product)}>
                        Beli Sekarang
                      </button>
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>

      {/* Checkout Modal */}
      {selectedProduct && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.8)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px'
        }} onClick={() => !checkoutLoading && setSelectedProduct(null)}>
          <div className="card" style={{ width: '100%', maxWidth: '400px', padding: '24px' }} onClick={e => e.stopPropagation()}>
            <h3 style={{ fontSize: '18px', fontWeight: 600, color: '#f1f5f9', marginBottom: '16px' }}>Konfirmasi Pembelian</h3>
            
            <div style={{ background: 'rgba(255,255,255,0.03)', padding: '16px', borderRadius: '12px', marginBottom: '20px' }}>
              <div style={{ fontSize: '14px', color: '#94a3b8', marginBottom: '4px' }}>Produk</div>
              <div style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '12px' }}>{selectedProduct.name}</div>
              
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid rgba(255,255,255,0.1)', paddingTop: '12px' }}>
                <div style={{ fontSize: '14px', color: '#94a3b8' }}>Total</div>
                <div style={{ fontSize: '18px', fontWeight: 700, color: '#f59e0b' }}>{formatRupiah(selectedProduct.price)}</div>
              </div>
            </div>

            <div style={{ marginBottom: '24px' }}>
              <div style={{ fontSize: '14px', color: '#64748b', marginBottom: '12px' }}>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.price && (
                <div style={{ marginTop: '8px', fontSize: '12px', color: '#ef4444' }}>
                  Saldo tidak mencukupi. Silakan topup terlebih dahulu.
                </div>
              )}
            </div>

            <div style={{ display: 'flex', gap: '12px' }}>
              <button 
                className="btn" 
                style={{ flex: 1, background: 'rgba(255,255,255,0.1)', color: '#e2e8f0' }}
                onClick={() => setSelectedProduct(null)}
                disabled={checkoutLoading}
              >
                Batal
              </button>
              <button 
                className="btn btn-primary" 
                style={{ flex: 1 }}
                disabled={checkoutLoading || (paymentMethod === 'balance' && session?.user && Number((session.user as any).balance || 0) < selectedProduct.price)}
                onClick={handleConfirmCheckout}
              >
                {checkoutLoading ? <span className="spinner" /> : 'Bayar'}
              </button>
            </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 pembelian.
            </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>
  )
}
