'use client'

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

export default function UserPterodactylDashboard() {
  const { data: session } = useSession()
  const [servers, setServers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [renewingId, setRenewingId] = useState<string | null>(null)
  const [showRenewModal, setShowRenewModal] = useState<any>(null)
  const [paymentMethod, setPaymentMethod] = useState<'BALANCE' | 'QRIS'>('BALANCE')

  useEffect(() => {
    if (session?.user) {
      fetch('/api/pterodactyl/servers')
        .then(res => res.json())
        .then(data => {
          setServers(data)
          setLoading(false)
        })
        .catch(console.error)
    }
  }, [session])

  const handleRenew = async () => {
    if (!showRenewModal) return
    setRenewingId(showRenewModal.id)
    
    try {
      const res = await fetch('/api/pterodactyl/renew', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ serverId: showRenewModal.id, 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('Perpanjangan berhasil!')
        window.location.reload()
      }
    } catch (e: any) {
      alert(e.message)
    } finally {
      setRenewingId(null)
      setShowRenewModal(null)
    }
  }

  if (!session) {
    return (
      <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div className="spinner" style={{ width: 40, height: 40 }} />
      </main>
    )
  }

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f' }}>
      <Navbar />
      
      <div style={{ maxWidth: '1000px', margin: '0 auto', padding: '100px 24px 60px' }}>
        <div style={{ marginBottom: '32px' }}>
          <h1 className="font-game" style={{ fontSize: '32px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>Server Hosting Saya</h1>
          <p style={{ color: '#64748b' }}>Kelola server panel Pterodactyl Anda</p>
        </div>

        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px' }}>
            <div className="spinner" style={{ width: 40, height: 40 }} />
          </div>
        ) : servers.length === 0 ? (
          <div style={{ background: '#111118', border: '1px solid rgba(255,255,255,0.05)', borderRadius: '16px', padding: '40px', textAlign: 'center' }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>☁️</div>
            <h3 style={{ fontSize: '20px', fontWeight: 600, color: '#f1f5f9', marginBottom: '8px' }}>Anda belum memiliki server</h3>
            <p style={{ color: '#94a3b8', marginBottom: '24px' }}>Mulai buat server game pertama Anda sekarang.</p>
            <a href="/pterodactyl" style={{ display: 'inline-block', background: '#3b82f6', color: '#fff', padding: '12px 24px', borderRadius: '8px', textDecoration: 'none', fontWeight: 600 }}>
              Lihat Paket
            </a>
          </div>
        ) : (
          <div style={{ display: 'grid', gap: '24px' }}>
            {servers.map(server => {
              const expiresDate = server.expiresAt ? new Date(server.expiresAt) : null
              const isExpired = expiresDate && expiresDate < new Date()
              const daysRemaining = expiresDate ? Math.ceil((expiresDate.getTime() - new Date().getTime()) / (1000 * 3600 * 24)) : 0
              
              let statusColor = '#94a3b8'
              if (server.status === 'ACTIVE') statusColor = '#10b981'
              else if (server.status === 'SUSPENDED') statusColor = '#f59e0b'
              else if (server.status === 'EXPIRED') statusColor = '#ef4444'

              return (
                <div key={server.id} style={{ background: '#111118', border: '1px solid rgba(255,255,255,0.05)', borderRadius: '16px', overflow: 'hidden' }}>
                  <div style={{ padding: '20px', borderBottom: '1px solid rgba(255,255,255,0.05)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '16px' }}>
                    <div>
                      <h3 style={{ fontSize: '18px', fontWeight: 600, color: '#f1f5f9', marginBottom: '4px' }}>
                        {server.package?.name || 'Unknown Package'}
                      </h3>
                      <div style={{ fontSize: '14px', color: '#64748b', display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <span>Identifier: <code style={{ color: '#3b82f6' }}>{server.pteroIdentifier || 'Pending'}</code></span>
                        <span>•</span>
                        <span style={{ color: statusColor, fontWeight: 600 }}>{server.status}</span>
                      </div>
                    </div>
                    
                    <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
                      <a 
                        href={process.env.NEXT_PUBLIC_PTERODACTYL_URL || 'https://panel.amanenime.my.id'} 
                        target="_blank" 
                        rel="noreferrer"
                        style={{
                          background: 'linear-gradient(135deg, #3b82f6, #2563eb)',
                          color: '#fff',
                          padding: '10px 20px',
                          borderRadius: '8px',
                          textDecoration: 'none',
                          fontWeight: 600,
                          display: 'inline-block'
                        }}
                      >
                        🚀 Login Panel
                      </a>
                      <button 
                        onClick={() => setShowRenewModal(server)}
                        style={{
                          background: 'linear-gradient(135deg, #10b981, #059669)',
                          color: '#fff',
                          border: 'none',
                          padding: '10px 20px',
                          borderRadius: '8px',
                          fontWeight: 600,
                          cursor: 'pointer'
                        }}
                      >
                        Perpanjang Server
                      </button>
                    </div>
                  </div>
                  
                  <div style={{ padding: '20px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px' }}>
                    <div>
                      <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>Username Panel</div>
                      <div style={{ fontSize: '14px', color: '#f1f5f9', fontWeight: 500 }}>
                        {server.pteroUsername || 'Menunggu pembuatan'}
                      </div>
                    </div>
                    
                    <div>
                      <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>Password Panel</div>
                      <div style={{ fontSize: '14px', color: '#f1f5f9', fontWeight: 500 }}>
                        {server.pteroPassword ? (
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <code style={{ background: '#0a0a0f', padding: '4px 8px', borderRadius: '4px' }}>{server.pteroPassword}</code>
                          </div>
                        ) : (
                          <span style={{ color: '#94a3b8' }}>Gunakan email / fitur lupa password</span>
                        )}
                      </div>
                    </div>

                    <div>
                      <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>Masa Aktif</div>
                      <div style={{ fontSize: '14px', color: isExpired ? '#ef4444' : '#f1f5f9', fontWeight: 500 }}>
                        {expiresDate ? expiresDate.toLocaleDateString('id-ID') : '-'}
                        {expiresDate && !isExpired && <span style={{ color: '#10b981', fontSize: '12px', marginLeft: '8px' }}>({daysRemaining} hari)</span>}
                        {isExpired && <span style={{ color: '#ef4444', fontSize: '12px', marginLeft: '8px' }}>(EXPIRED)</span>}
                      </div>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>

      {/* Renew Modal */}
      {showRenewModal && (
        <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: '400px', padding: '24px' }}>
            <h3 style={{ fontSize: '20px', fontWeight: 700, color: '#f1f5f9', marginBottom: '16px' }}>Perpanjang Server</h3>
            
            <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' }}>{showRenewModal.package?.name}</div>
              
              <div style={{ fontSize: '14px', color: '#94a3b8', marginBottom: '4px' }}>Total Harga (+{showRenewModal.package?.durationDays} hari)</div>
              <div style={{ fontSize: '20px', fontWeight: 700, color: '#10b981' }}>{formatRupiah(showRenewModal.package?.price)}</div>
            </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(16,185,129,0.1)' : 'transparent',
                    border: `1px solid ${paymentMethod === 'BALANCE' ? '#10b981' : 'rgba(255,255,255,0.1)'}`,
                    color: paymentMethod === 'BALANCE' ? '#10b981' : '#94a3b8',
                    padding: '12px',
                    borderRadius: '8px',
                    fontWeight: 600,
                    cursor: 'pointer'
                  }}
                >
                  Saldo Akun
                </button>
                <button
                  onClick={() => setPaymentMethod('QRIS')}
                  style={{
                    background: paymentMethod === 'QRIS' ? 'rgba(16,185,129,0.1)' : 'transparent',
                    border: `1px solid ${paymentMethod === 'QRIS' ? '#10b981' : 'rgba(255,255,255,0.1)'}`,
                    color: paymentMethod === 'QRIS' ? '#10b981' : '#94a3b8',
                    padding: '12px',
                    borderRadius: '8px',
                    fontWeight: 600,
                    cursor: 'pointer'
                  }}
                >
                  QRIS (Instant)
                </button>
              </div>
            </div>

            <div style={{ display: 'flex', gap: '12px' }}>
              <button 
                onClick={() => setShowRenewModal(null)}
                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={handleRenew}
                disabled={renewingId !== null}
                style={{ flex: 1, padding: '12px', background: '#10b981', border: 'none', color: '#fff', borderRadius: '8px', fontWeight: 600, cursor: renewingId ? 'not-allowed' : 'pointer', opacity: renewingId ? 0.7 : 1 }}
              >
                {renewingId ? 'Memproses...' : 'Bayar'}
              </button>
            </div>
          </div>
        </div>
      )}
    </main>
  )
}
