'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 PterodactylPage() {
  const { data: session } = useSession()
  const router = useRouter()
  const [packages, setPackages] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [buyingId, setBuyingId] = useState<string | null>(null)
  const [showModal, setShowModal] = useState(false)
  const [selectedPkg, setSelectedPkg] = useState<any>(null)
  const [paymentMethod, setPaymentMethod] = useState<'BALANCE' | 'QRIS'>('BALANCE')
  const [pteroUsername, setPteroUsername] = useState('')
  const [pteroPassword, setPteroPassword] = useState('')
  const [pteroError, setPteroError] = useState('')

  useEffect(() => {
    fetch('/api/pterodactyl/packages')
      .then(res => res.json())
      .then(data => {
        setPackages(data)
        setLoading(false)
      })
      .catch(console.error)
  }, [])

  const handleBuy = async () => {
    if (!session) {
      alert('Silakan login terlebih dahulu!')
      router.push('/auth/login')
      return
    }
    if (!selectedPkg) return
    if (!pteroUsername.trim()) { setPteroError('Nickname panel wajib diisi'); return }
    if (!pteroPassword.trim()) { setPteroError('Password panel wajib diisi'); return }
    if (pteroPassword.trim().length < 8) { setPteroError('Password minimal 8 karakter'); return }
    setPteroError('')

    setBuyingId(selectedPkg.id)
    try {
      const res = await fetch('/api/pterodactyl/order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ packageId: selectedPkg.id, method: paymentMethod, pteroUsername: pteroUsername.trim(), pteroPassword: pteroPassword.trim() })
      })
      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! Server sedang disiapkan, cek Dashboard Anda.')
        router.push('/dashboard/pterodactyl')
      }
    } catch (e: any) {
      alert(e.message)
    } finally {
      setBuyingId(null)
      setShowModal(false)
      setPteroUsername('')
      setPteroPassword('')
      setPteroError('')
    }
  }

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f' }}>
      <Navbar />
      
      <div style={{ maxWidth: '1280px', margin: '0 auto', padding: '100px 24px 60px' }}>
        <div style={{ textAlign: 'center', marginBottom: '40px' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', background: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.3)', borderRadius: '100px', padding: '4px 12px', fontSize: '12px', color: '#3b82f6', fontWeight: 600, marginBottom: '16px' }}>
            ☁️ Cloud Hosting Server
          </div>
          <h1 className="font-game" style={{ fontSize: '36px', fontWeight: 800, color: '#f1f5f9', marginBottom: '16px' }}>
            Panel Pterodactyl
          </h1>
          <p style={{ color: '#94a3b8', maxWidth: '600px', margin: '0 auto', lineHeight: 1.6 }}>
            Hosting game server premium dengan performa tinggi dan harga terjangkau. Server akan aktif seketika setelah pembayaran berhasil.
          </p>
        </div>

        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px' }}>
            <div className="spinner" style={{ width: 40, height: 40 }} />
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '24px' }}>
            {packages.map(pkg => (
              <div key={pkg.id} style={{
                background: '#111118',
                border: '1px solid rgba(255,255,255,0.05)',
                borderRadius: '16px',
                padding: '24px',
                position: 'relative',
                overflow: 'hidden'
              }}>
                <div style={{ borderBottom: '1px solid rgba(255,255,255,0.05)', paddingBottom: '16px', marginBottom: '16px' }}>
                  <h3 style={{ fontSize: '20px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>{pkg.name}</h3>
                  <div style={{ fontSize: '24px', fontWeight: 800, color: '#3b82f6' }}>
                    {formatRupiah(pkg.price)}<span style={{ fontSize: '14px', color: '#64748b', fontWeight: 500 }}>/{pkg.durationDays} hari</span>
                  </div>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', marginBottom: '24px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '14px' }}>
                    <span style={{ color: '#94a3b8' }}>RAM</span>
                    <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{pkg.memory} MB</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '14px' }}>
                    <span style={{ color: '#94a3b8' }}>Storage</span>
                    <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{pkg.disk} MB</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '14px' }}>
                    <span style={{ color: '#94a3b8' }}>CPU</span>
                    <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{pkg.cpu}%</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '14px' }}>
                    <span style={{ color: '#94a3b8' }}>Databases</span>
                    <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{pkg.databases}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '14px' }}>
                    <span style={{ color: '#94a3b8' }}>Backups</span>
                    <span style={{ color: '#f1f5f9', fontWeight: 600 }}>{pkg.backups}</span>
                  </div>
                </div>

                <button 
                  onClick={() => { setSelectedPkg(pkg); setShowModal(true); }}
                  style={{
                    width: '100%',
                    background: 'linear-gradient(135deg, #3b82f6, #2563eb)',
                    color: '#fff',
                    border: 'none',
                    padding: '12px',
                    borderRadius: '8px',
                    fontWeight: 600,
                    cursor: 'pointer',
                    transition: 'opacity 0.2s'
                  }}
                  onMouseEnter={e => (e.target as HTMLButtonElement).style.opacity = '0.9'}
                  onMouseLeave={e => (e.target as HTMLButtonElement).style.opacity = '1'}
                >
                  Beli Sekarang
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Payment Modal */}
      {showModal && selectedPkg && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.8)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
          <div style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '16px', width: '100%', maxWidth: '440px', padding: '24px' }}>
            <h3 style={{ fontSize: '20px', fontWeight: 700, color: '#f1f5f9', marginBottom: '4px' }}>Konfirmasi Pembelian</h3>
            <p style={{ fontSize: '13px', color: '#64748b', marginBottom: '20px' }}>Masukkan kredensial untuk akun Panel Pterodactyl Anda.</p>

            <div style={{ background: '#0a0a0f', borderRadius: '8px', padding: '16px', marginBottom: '20px' }}>
              <div style={{ fontSize: '14px', color: '#94a3b8', marginBottom: '4px' }}>Paket</div>
              <div style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '12px' }}>{selectedPkg.name}</div>
              <div style={{ fontSize: '14px', color: '#94a3b8', marginBottom: '4px' }}>Total Harga</div>
              <div style={{ fontSize: '20px', fontWeight: 700, color: '#3b82f6' }}>{formatRupiah(selectedPkg.price)}</div>
            </div>

            {/* Ptero Credentials */}
            <div style={{ marginBottom: '16px' }}>
              <label style={{ display: 'block', fontSize: '13px', color: '#cbd5e1', marginBottom: '6px', fontWeight: 600 }}>Nickname / Username Panel *</label>
              <input
                type="text"
                className="input"
                placeholder="Nama pengguna untuk login ke panel"
                value={pteroUsername}
                onChange={e => setPteroUsername(e.target.value)}
              />
              <p style={{ fontSize: '11px', color: '#475569', marginTop: '4px' }}>Huruf kecil, angka, strip (-) dan titik (.) diperbolehkan.</p>
            </div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', fontSize: '13px', color: '#cbd5e1', marginBottom: '6px', fontWeight: 600 }}>Password Panel *</label>
              <input
                type="password"
                className="input"
                placeholder="Minimal 8 karakter"
                value={pteroPassword}
                onChange={e => setPteroPassword(e.target.value)}
              />
            </div>

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

            <div style={{ marginBottom: '24px' }}>
              <div style={{ fontSize: '14px', color: '#94a3b8', marginBottom: '8px' }}>Pilih Metode Pembayaran</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <button
                  onClick={() => setPaymentMethod('BALANCE')}
                  style={{
                    background: paymentMethod === 'BALANCE' ? 'rgba(59,130,246,0.1)' : 'transparent',
                    border: `1px solid ${paymentMethod === 'BALANCE' ? '#3b82f6' : 'rgba(255,255,255,0.1)'}`,
                    color: paymentMethod === 'BALANCE' ? '#3b82f6' : '#94a3b8',
                    padding: '12px',
                    borderRadius: '8px',
                    fontWeight: 600,
                    cursor: 'pointer'
                  }}
                >
                  Saldo Akun
                </button>
                <button
                  onClick={() => setPaymentMethod('QRIS')}
                  style={{
                    background: paymentMethod === 'QRIS' ? 'rgba(59,130,246,0.1)' : 'transparent',
                    border: `1px solid ${paymentMethod === 'QRIS' ? '#3b82f6' : 'rgba(255,255,255,0.1)'}`,
                    color: paymentMethod === 'QRIS' ? '#3b82f6' : '#94a3b8',
                    padding: '12px',
                    borderRadius: '8px',
                    fontWeight: 600,
                    cursor: 'pointer'
                  }}
                >
                  QRIS (Instant)
                </button>
              </div>
            </div>

            <div style={{ display: 'flex', gap: '12px' }}>
              <button 
                onClick={() => setShowModal(false)}
                style={{ flex: 1, padding: '12px', background: 'transparent', border: '1px solid rgba(255,255,255,0.1)', color: '#94a3b8', borderRadius: '8px', fontWeight: 600, cursor: 'pointer' }}
              >
                Batal
              </button>
              <button 
                onClick={handleBuy}
                disabled={buyingId !== null}
                style={{ flex: 1, padding: '12px', background: '#3b82f6', border: 'none', color: '#fff', borderRadius: '8px', fontWeight: 600, cursor: buyingId ? 'not-allowed' : 'pointer', opacity: buyingId ? 0.7 : 1 }}
              >
                {buyingId ? 'Memproses...' : 'Bayar'}
              </button>
            </div>
          </div>
        </div>
      )}

    </main>
  )
}
