'use client'

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

export default function SmmPage() {
  const { data: session } = useSession()
  const router = useRouter()
  
  const [categories, setCategories] = useState<Record<string, any[]>>({})
  const [categoryKeys, setCategoryKeys] = useState<string[]>([])
  const [loading, setLoading] = useState(true)
  
  const [selectedCategory, setSelectedCategory] = useState('')
  const [selectedProduct, setSelectedProduct] = useState<any>(null)
  const [target, setTarget] = useState('')
  const [quantity, setQuantity] = useState<number>(0)
  
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [paymentMethod, setPaymentMethod] = useState<'BALANCE' | 'QRIS'>('BALANCE')

  useEffect(() => {
    fetch('/api/smm/products')
      .then(res => res.json())
      .then(data => {
        setCategories(data)
        const keys = Object.keys(data).sort()
        setCategoryKeys(keys)
        if (keys.length > 0) {
          setSelectedCategory(keys[0])
        }
        setLoading(false)
      })
      .catch(console.error)
  }, [])

  useEffect(() => {
    setSelectedProduct(null)
    setQuantity(0)
  }, [selectedCategory])

  const calculateTotal = () => {
    if (!selectedProduct || !quantity) return 0
    return (quantity / 1000) * Number(selectedProduct.sellPrice)
  }

  const handleBuy = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!session) {
      alert('Silakan login terlebih dahulu!')
      router.push('/login')
      return
    }
    if (!selectedProduct || !target || !quantity) return

    if (quantity < selectedProduct.minOrder) return alert(`Minimal order ${selectedProduct.minOrder}`)
    if (quantity > selectedProduct.maxOrder) return alert(`Maksimal order ${selectedProduct.maxOrder}`)

    setIsSubmitting(true)
    try {
      const res = await fetch('/api/smm/order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          productId: selectedProduct.id, 
          target, 
          quantity, 
          method: paymentMethod 
        })
      })
      const data = await res.json()

      if (!res.ok) throw new Error(data.error)

      if (paymentMethod === 'QRIS' && data.invoiceUrl) {
        window.location.href = data.invoiceUrl
      } else {
        alert('Pembelian berhasil! Pesanan sedang diproses.')
        router.push('/dashboard/orders')
      }
    } catch (e: any) {
      alert(e.message)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', overflowX: 'hidden' }}>
      <Navbar />
      
      <div style={{ maxWidth: '800px', margin: '0 auto', padding: '88px 16px 120px' }}>
        <div style={{ textAlign: 'center', marginBottom: '40px' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', background: 'rgba(236, 72, 153, 0.1)', border: '1px solid rgba(236, 72, 153, 0.3)', borderRadius: '100px', padding: '4px 12px', fontSize: '12px', color: '#ec4899', fontWeight: 600, marginBottom: '16px' }}>
            📱 SMM Panel
          </div>
          <h1 className="font-game" style={{ fontSize: '36px', fontWeight: 800, color: '#f1f5f9', marginBottom: '16px' }}>
            Social Media Marketing
          </h1>
          <p style={{ color: '#94a3b8', maxWidth: '600px', margin: '0 auto', lineHeight: 1.6 }}>
            Tingkatkan engagement sosial media Anda dengan cepat. Followers, Likes, Views untuk Instagram, TikTok, YouTube dan lainnya.
          </p>
        </div>

        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px' }}>
            <div className="spinner" style={{ width: 40, height: 40 }} />
          </div>
        ) : (
          <form onSubmit={handleBuy} style={{ background: '#111118', border: '1px solid rgba(255,255,255,0.05)', borderRadius: '16px', padding: '20px 16px' }}>
            
            {/* Category Select */}
            <div style={{ marginBottom: '24px' }}>
              <label style={{ display: 'block', fontSize: '14px', color: '#94a3b8', marginBottom: '8px', fontWeight: 500 }}>1. Pilih Kategori</label>
              <select 
                value={selectedCategory}
                onChange={e => setSelectedCategory(e.target.value)}
                style={{ width: '100%', padding: '12px', background: '#0a0a0f', border: '1px solid rgba(255,255,255,0.1)', color: '#f1f5f9', borderRadius: '8px', fontSize: '16px' }}
              >
                {categoryKeys.map(cat => (
                  <option key={cat} value={cat}>{cat}</option>
                ))}
              </select>
            </div>

            {/* Service Select */}
            <div style={{ marginBottom: '24px' }}>
              <label style={{ display: 'block', fontSize: '14px', color: '#94a3b8', marginBottom: '8px', fontWeight: 500 }}>2. Pilih Layanan</label>
              <select 
                value={selectedProduct?.id || ''}
                onChange={e => {
                  const prod = categories[selectedCategory]?.find(p => p.id === e.target.value)
                  setSelectedProduct(prod || null)
                  if (prod) {
                    setQuantity(prod.minOrder)
                  }
                }}
                style={{ width: '100%', padding: '12px', background: '#0a0a0f', border: '1px solid rgba(255,255,255,0.1)', color: '#f1f5f9', borderRadius: '8px', fontSize: '16px' }}
              >
                <option value="">-- Pilih Layanan --</option>
                {categories[selectedCategory]?.map(prod => (
                  <option key={prod.id} value={prod.id}>
                    {prod.name} (Rp {Number(prod.sellPrice).toLocaleString('id-ID')} / 1000)
                  </option>
                ))}
              </select>
            </div>

            {selectedProduct && (
              <div style={{ background: 'rgba(59,130,246,0.05)', border: '1px solid rgba(59,130,246,0.2)', padding: '16px', borderRadius: '8px', marginBottom: '24px', fontSize: '14px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '12px' }}>
                  <div><span style={{ color: '#94a3b8' }}>Min Order:</span> <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{selectedProduct.minOrder}</span></div>
                  <div><span style={{ color: '#94a3b8' }}>Max Order:</span> <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{selectedProduct.maxOrder}</span></div>
                  <div><span style={{ color: '#94a3b8' }}>Rata-rata Waktu:</span> <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{selectedProduct.averageTime || '-'}</span></div>
                  <div><span style={{ color: '#94a3b8' }}>Refill:</span> <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{selectedProduct.isRefill ? 'Ya' : 'Tidak'}</span></div>
                </div>
                {selectedProduct.description && (
                  <div>
                    <span style={{ color: '#94a3b8', display: 'block', marginBottom: '4px' }}>Deskripsi:</span>
                    <div style={{ color: '#e2e8f0', lineHeight: 1.5 }} dangerouslySetInnerHTML={{ __html: selectedProduct.description }} />
                  </div>
                )}
              </div>
            )}

            {/* Target Data */}
            <div style={{ marginBottom: '24px' }}>
              <label style={{ display: 'block', fontSize: '14px', color: '#94a3b8', marginBottom: '8px', fontWeight: 500 }}>3. Target (Link / Username)</label>
              <input 
                required
                value={target}
                onChange={e => setTarget(e.target.value)}
                placeholder="https://instagram.com/username atau @username"
                style={{ width: '100%', padding: '12px', background: '#0a0a0f', border: '1px solid rgba(255,255,255,0.1)', color: '#f1f5f9', borderRadius: '8px', fontSize: '16px' }}
              />
            </div>

            {/* Quantity */}
            <div style={{ marginBottom: '24px' }}>
              <label style={{ display: 'block', fontSize: '14px', color: '#94a3b8', marginBottom: '8px', fontWeight: 500 }}>4. Jumlah</label>
              <input 
                required
                type="number"
                min={selectedProduct?.minOrder || 1}
                max={selectedProduct?.maxOrder || 1000000}
                value={quantity || ''}
                onChange={e => setQuantity(Number(e.target.value))}
                style={{ width: '100%', padding: '12px', background: '#0a0a0f', border: '1px solid rgba(255,255,255,0.1)', color: '#f1f5f9', borderRadius: '8px', fontSize: '16px' }}
              />
            </div>

            {/* Payment Method */}
            <div style={{ marginBottom: '32px' }}>
              <label style={{ display: 'block', fontSize: '14px', color: '#94a3b8', marginBottom: '8px', fontWeight: 500 }}>5. Metode Pembayaran</label>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div
                  onClick={() => setPaymentMethod('BALANCE')}
                  style={{
                    background: paymentMethod === 'BALANCE' ? 'rgba(236,72,153,0.1)' : 'transparent',
                    border: `1px solid ${paymentMethod === 'BALANCE' ? '#ec4899' : 'rgba(255,255,255,0.1)'}`,
                    color: paymentMethod === 'BALANCE' ? '#ec4899' : '#94a3b8',
                    padding: '16px',
                    borderRadius: '8px',
                    fontWeight: 600,
                    cursor: 'pointer',
                    textAlign: 'center'
                  }}
                >
                  Saldo Akun
                </div>
                <div
                  onClick={() => setPaymentMethod('QRIS')}
                  style={{
                    background: paymentMethod === 'QRIS' ? 'rgba(236,72,153,0.1)' : 'transparent',
                    border: `1px solid ${paymentMethod === 'QRIS' ? '#ec4899' : 'rgba(255,255,255,0.1)'}`,
                    color: paymentMethod === 'QRIS' ? '#ec4899' : '#94a3b8',
                    padding: '16px',
                    borderRadius: '8px',
                    fontWeight: 600,
                    cursor: 'pointer',
                    textAlign: 'center'
                  }}
                >
                  QRIS (Instant)
                </div>
              </div>
            </div>

            {/* Total & Submit */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: '20px', gap: '12px', flexWrap: 'wrap' }}>
              <div>
                <div style={{ fontSize: '14px', color: '#94a3b8', marginBottom: '4px' }}>Total Harga</div>
                <div style={{ fontSize: '28px', fontWeight: 800, color: '#ec4899' }}>{formatRupiah(calculateTotal())}</div>
              </div>
              <button 
                type="submit"
                disabled={!selectedProduct || isSubmitting}
                style={{ 
                  background: 'linear-gradient(135deg, #ec4899, #be185d)', 
                  color: '#fff', 
                  border: 'none', 
                  padding: '16px 32px', 
                  borderRadius: '100px', 
                  fontWeight: 700, 
                  fontSize: '16px',
                  cursor: (!selectedProduct || isSubmitting) ? 'not-allowed' : 'pointer', 
                  opacity: (!selectedProduct || isSubmitting) ? 0.7 : 1,
                  boxShadow: '0 4px 14px rgba(236, 72, 153, 0.4)'
                }}
              >
                {isSubmitting ? 'Memproses...' : 'Beli Sekarang'}
              </button>
            </div>

          </form>
        )}
      </div>
    </main>
  )
}
