'use client'

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

export default function UserDashboard() {
  const { data: session } = useSession()
  const [orders, setOrders] = useState<any[]>([])
  const [balance, setBalance] = useState(0)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    Promise.all([
      fetch('/api/orders?limit=5').then(r => r.json()),
      fetch('/api/wallet?limit=1').then(r => r.json()),
    ]).then(([ordersData, walletData]) => {
      setOrders(ordersData.orders || [])
      setBalance(Number(walletData.balance || 0))
      setLoading(false)
    }).catch(() => setLoading(false))
  }, [])

  const dashboardLinks = [
    { href: '/dashboard/orders', label: 'Riwayat Order', icon: '📦', desc: 'Lihat semua pesananmu' },
    { href: '/dashboard/wallet', label: 'Saldo & Topup', icon: '💰', desc: `Saldo: ${formatRupiah(balance)}` },
    { href: '/dashboard/pterodactyl', label: 'Server Hosting', icon: '☁️', desc: 'Kelola Panel Pterodactyl Anda' },
    { href: '/dashboard/orders', label: 'Produk Saya', icon: '🔑', desc: 'Akun premium yang kamu beli' },
  ]

  const userRole = (session?.user as any)?.role
  if (['RESELLER', 'ADMIN'].includes(userRole)) {
    dashboardLinks.push({ href: '/dashboard/reseller', label: 'Panel Reseller', icon: '🔗', desc: 'API Keys & H2H' })
  }

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <div style={{ paddingTop: '80px', maxWidth: '1200px', margin: '0 auto', padding: '80px 24px 60px', width: '100%' }}>
        {/* Welcome */}
        <div className="card glass-accent" style={{ padding: '32px', marginBottom: '28px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
            <div style={{
              width: 60,
              height: 60,
              borderRadius: '50%',
              background: 'linear-gradient(135deg, #f59e0b, #d97706)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '24px',
              fontWeight: 700,
              color: '#000',
              flexShrink: 0,
            }}>
              {session?.user?.name?.[0]?.toUpperCase() || 'U'}
            </div>
            <div>
              <h1 className="font-game" style={{ fontSize: '26px', fontWeight: 700, color: '#f1f5f9', marginBottom: '4px' }}>
                Halo, {session?.user?.name?.split(' ')[0]}! 👋
              </h1>
              <p style={{ color: '#64748b', fontSize: '14px' }}>{session?.user?.email}</p>
            </div>
            <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
              <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '4px' }}>Saldo</div>
              <div style={{ fontSize: '24px', fontWeight: 700, color: '#f59e0b' }}>
                {formatRupiah(Number((session?.user as any)?.balance || 0))}
              </div>
              <Link href="/dashboard/wallet" className="btn btn-primary" style={{ fontSize: '12px', padding: '6px 14px', marginTop: '8px' }}>
                + Topup
              </Link>
            </div>
          </div>
        </div>

        {/* Quick Links */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginBottom: '32px' }}>
          {dashboardLinks.map(link => (
            <Link key={link.href} href={link.href} style={{ textDecoration: 'none' }}>
              <div className="card" style={{ padding: '24px', cursor: 'pointer' }}>
                <div style={{ fontSize: '32px', marginBottom: '12px' }}>{link.icon}</div>
                <div style={{ fontSize: '15px', fontWeight: 600, color: '#f1f5f9', marginBottom: '4px' }}>{link.label}</div>
                <div style={{ fontSize: '13px', color: '#64748b' }}>{link.desc}</div>
              </div>
            </Link>
          ))}

          {/* Quick Top Up Game */}
          <Link href="/games" style={{ textDecoration: 'none' }}>
            <div className="card" style={{ padding: '24px', cursor: 'pointer', background: 'rgba(245,158,11,0.05)', borderColor: 'rgba(245,158,11,0.2)' }}>
              <div style={{ fontSize: '32px', marginBottom: '12px' }}>🎮</div>
              <div style={{ fontSize: '15px', fontWeight: 600, color: '#f59e0b', marginBottom: '4px' }}>Top Up Game</div>
              <div style={{ fontSize: '13px', color: '#64748b' }}>Topup sekarang</div>
            </div>
          </Link>
        </div>

        {/* Recent Orders */}
        <div className="card" style={{ overflow: 'hidden' }}>
          <div style={{ padding: '20px 24px', borderBottom: '1px solid rgba(255,255,255,0.06)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9' }}>📦 Pesanan Terbaru</h2>
            <Link href="/dashboard/orders" style={{ fontSize: '13px', color: '#f59e0b', textDecoration: 'none' }}>Lihat Semua →</Link>
          </div>

          {loading ? (
            <div style={{ padding: '24px' }}>
              {Array(3).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 60, borderRadius: 10, marginBottom: 10 }} />)}
            </div>
          ) : orders.length === 0 ? (
            <div style={{ padding: '60px 24px', textAlign: 'center', color: '#475569' }}>
              <div style={{ fontSize: '40px', marginBottom: '12px' }}>📦</div>
              <p>Belum ada pesanan</p>
              <Link href="/games" className="btn btn-primary" style={{ marginTop: '16px', fontSize: '13px' }}>
                Mulai Top Up
              </Link>
            </div>
          ) : (
            <div style={{ padding: '8px' }}>
              {orders.map(order => {
                const statusConfig = getOrderStatusConfig(order.status)
                const productName = order.vipProduct
                  ? `${order.vipProduct.gameName} - ${order.vipProduct.productName}`
                  : order.digitalProduct?.name || 'Produk'

                return (
                  <div key={order.id} style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '14px 16px',
                    borderRadius: '10px',
                    transition: 'background 0.2s',
                    gap: '12px',
                  }}
                    onMouseEnter={e => (e.currentTarget as HTMLElement).style.background = 'rgba(255,255,255,0.03)'}
                    onMouseLeave={e => (e.currentTarget as HTMLElement).style.background = 'transparent'}
                  >
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0', marginBottom: '4px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {productName}
                      </div>
                      <div style={{ fontSize: '12px', color: '#475569' }}>
                        #{order.id.slice(-8).toUpperCase()} • {formatDate(order.createdAt)}
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexShrink: 0 }}>
                      <div style={{ fontSize: '14px', fontWeight: 700, color: '#f59e0b' }}>
                        {formatRupiah(order.price)}
                      </div>
                      <span className="badge" style={{ background: statusConfig.bg, color: statusConfig.color }}>
                        {statusConfig.label}
                      </span>
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </main>
  )
}
