'use client'

import { useState, useEffect } from 'react'
import { useSession, signOut } from 'next-auth/react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession()
  const pathname = usePathname()
  const [isMobile, setIsMobile] = useState(false)
  const [sidebarOpen, setSidebarOpen] = useState(false)

  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 768)
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  useEffect(() => {
    if (isMobile) setSidebarOpen(false)
  }, [pathname, isMobile])

  if (status === 'loading') return <div className="spinner" style={{ margin: '100px auto', display: 'block' }} />

  if (session?.user?.role !== 'ADMIN') {
    return <div style={{ padding: '100px', textAlign: 'center', color: '#ef4444' }}>Akses Ditolak</div>
  }

  const menu = [
    { href: '/admin', label: 'Dashboard', icon: '📊' },
    { href: '/admin/orders', label: 'Pesanan', icon: '📦' },
    { href: '/admin/users', label: 'Pengguna', icon: '👥' },
    { href: '/admin/categories', label: 'Kategori Game', icon: '📁' },
    { href: '/admin/products/vip', label: 'Game VIP', icon: '🎮' },
    { href: '/admin/products/digital', label: 'App Premium', icon: '📱' },
    { href: '/admin/vouchers', label: 'Kode Voucher', icon: '🎟️' },
    { href: '/admin/pterodactyl', label: 'Hosting', icon: '☁️' },
    { href: '/admin/products/smm', label: 'SMM Panel', icon: '🚀' },
    { href: '/admin/chat', label: 'Live Chat', icon: '💬' },
    { href: '/admin/otp', label: 'OTP Orders', icon: '🔐' },
    { href: '/admin/settings', label: 'Pengaturan', icon: '⚙️' },
  ]

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: '#0a0a0f' }}>
      {/* Mobile Top Header */}
      {isMobile && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, height: '64px',
          background: '#111118', borderBottom: '1px solid rgba(255,255,255,0.06)',
          display: 'flex', alignItems: 'center', padding: '0 20px', zIndex: 40
        }}>
          <button 
            onClick={() => setSidebarOpen(!sidebarOpen)}
            style={{ background: 'transparent', border: 'none', color: '#f1f5f9', fontSize: '24px', cursor: 'pointer', marginRight: '16px' }}
          >
            ☰
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <div style={{ width: 28, height: 28, background: 'linear-gradient(135deg, #f59e0b, #d97706)', borderRadius: '6px', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '14px' }}>⚡</div>
            <span className="font-game" style={{ fontSize: '18px', fontWeight: 700, color: '#f1f5f9' }}>
              Admin<span style={{ color: '#f59e0b' }}>Panel</span>
            </span>
          </div>
        </div>
      )}

      {/* Overlay for mobile */}
      {isMobile && sidebarOpen && (
        <div 
          onClick={() => setSidebarOpen(false)}
          style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 45 }}
        />
      )}

      {/* Sidebar */}
      <aside style={{
        width: '260px',
        background: '#111118',
        borderRight: '1px solid rgba(255,255,255,0.06)',
        display: 'flex',
        flexDirection: 'column',
        position: 'fixed',
        top: 0,
        bottom: 0,
        left: isMobile ? (sidebarOpen ? 0 : '-260px') : 0,
        transition: 'left 0.3s ease',
        zIndex: 50,
      }}>
        <div style={{ padding: '24px', borderBottom: '1px solid rgba(255,255,255,0.06)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Link href="/admin" style={{ textDecoration: 'none', display: 'flex', alignItems: 'center', gap: '10px' }}>
            <div style={{ width: 32, height: 32, background: 'linear-gradient(135deg, #f59e0b, #d97706)', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '16px' }}>⚡</div>
            <span className="font-game" style={{ fontSize: '20px', fontWeight: 700, color: '#f1f5f9' }}>
              Admin<span style={{ color: '#f59e0b' }}>Panel</span>
            </span>
          </Link>
          {isMobile && (
            <button onClick={() => setSidebarOpen(false)} style={{ background: 'transparent', border: 'none', color: '#64748b', fontSize: '24px', cursor: 'pointer' }}>×</button>
          )}
        </div>

        <nav style={{ padding: '12px 16px', flex: 1, display: 'flex', flexDirection: 'column', gap: '4px', overflowY: 'auto' }}>
          {menu.map(m => {
            const isActive = pathname === m.href || (m.href !== '/admin' && pathname.startsWith(m.href))
            return (
              <Link key={m.href} href={m.href} className={`sidebar-link ${isActive ? 'active' : ''}`}>
                <span>{m.icon}</span> {m.label}
              </Link>
            )
          })}
        </nav>

        <div style={{ padding: '20px 16px', borderTop: '1px solid rgba(255,255,255,0.06)' }}>
          <Link href="/" className="sidebar-link" style={{ marginBottom: '8px' }}>🌍 Kembali ke Website</Link>
          <button onClick={() => signOut()} className="sidebar-link" style={{ width: '100%', border: 'none', background: 'transparent', textAlign: 'left', color: '#ef4444', cursor: 'pointer' }}>
            <span>🚪</span> Keluar
          </button>
        </div>
      </aside>

      {/* Main Content */}
      <main style={{ 
        flex: 1, 
        marginLeft: isMobile ? 0 : '260px', 
        padding: isMobile ? '80px 16px 32px' : '32px 40px', 
        overflowX: 'hidden',
        width: '100%'
      }}>
        {children}
      </main>
    </div>
  )
}
