'use client'

import { useState, useEffect } from 'react'
import { formatRupiah } from '@/lib/utils'

export default function AdminPterodactylPage() {
  const [activeTab, setActiveTab] = useState<'PACKAGES' | 'SERVERS'>('PACKAGES')
  const [packages, setPackages] = useState<any[]>([])
  const [servers, setServers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  const [isEditing, setIsEditing] = useState(false)
  const [formData, setFormData] = useState<any>({
    name: '', price: '', durationDays: 30, memory: 1024, disk: 10240, cpu: 100, 
    databases: 1, backups: 1, allocations: 1, eggId: '', nestId: '', locationId: '', image: '', startup: ''
  })

  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = async () => {
    setLoading(true)
    try {
      const [pkgRes, srvRes] = await Promise.all([
        fetch('/api/admin/pterodactyl/packages'),
        fetch('/api/admin/pterodactyl/servers')
      ])
      setPackages(await pkgRes.json())
      setServers(await srvRes.json())
    } catch (e) {
      console.error(e)
    }
    setLoading(false)
  }

  const handleSavePackage = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      const url = '/api/admin/pterodactyl/packages'
      const method = formData.id ? 'PATCH' : 'POST'
      
      const payload = {
        ...formData,
        price: Number(formData.price),
        durationDays: Number(formData.durationDays),
        memory: Number(formData.memory),
        disk: Number(formData.disk),
        cpu: Number(formData.cpu),
        databases: Number(formData.databases),
        backups: Number(formData.backups),
        allocations: Number(formData.allocations),
        eggId: Number(formData.eggId),
        nestId: Number(formData.nestId),
        locationId: Number(formData.locationId),
      }

      await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
      
      setIsEditing(false)
      fetchData()
    } catch (e) {
      alert('Gagal menyimpan paket')
    }
  }

  const handleDeletePackage = async (id: string) => {
    if (!confirm('Yakin ingin menghapus paket ini?')) return
    try {
      const res = await fetch(`/api/admin/pterodactyl/packages?id=${id}`, { method: 'DELETE' })
      const data = await res.json()
      if (!res.ok) {
        alert('❌ ' + (data.error || 'Gagal menghapus paket'))
        return
      }
      alert('✅ Paket berhasil dihapus')
      fetchData()
    } catch (e) {
      alert('Gagal menghubungi server')
    }
  }

  const handleServerAction = async (id: string, action: string) => {
    if (!confirm(`Yakin ingin melakukan ${action} pada server ini?`)) return
    try {
      const res = await fetch('/api/admin/pterodactyl/servers', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, action })
      })
      if (!res.ok) throw new Error(await res.text())
      fetchData()
    } catch (e: any) {
      alert(`Gagal: ${e.message}`)
    }
  }

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

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h1 style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>☁️ Pterodactyl</h1>
          <p style={{ color: '#94a3b8' }}>Kelola paket hosting dan server user</p>
        </div>
        
        <div style={{ display: 'flex', gap: '8px', background: '#111118', padding: '4px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.05)' }}>
          <button 
            onClick={() => setActiveTab('PACKAGES')}
            style={{ padding: '8px 16px', borderRadius: '6px', background: activeTab === 'PACKAGES' ? '#3b82f6' : 'transparent', color: activeTab === 'PACKAGES' ? '#fff' : '#94a3b8', border: 'none', cursor: 'pointer', fontWeight: 600 }}
          >Paket Hosting</button>
          <button 
            onClick={() => setActiveTab('SERVERS')}
            style={{ padding: '8px 16px', borderRadius: '6px', background: activeTab === 'SERVERS' ? '#3b82f6' : 'transparent', color: activeTab === 'SERVERS' ? '#fff' : '#94a3b8', border: 'none', cursor: 'pointer', fontWeight: 600 }}
          >Daftar Server</button>
        </div>
      </div>

      {activeTab === 'PACKAGES' && (
        <div className="card" style={{ padding: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
            <h2 style={{ fontSize: '18px', fontWeight: 600, color: '#f1f5f9' }}>Daftar Paket</h2>
            <button 
              onClick={() => {
                setFormData({ name: '', price: '', durationDays: 30, memory: 1024, disk: 10240, cpu: 100, databases: 1, backups: 1, allocations: 1, eggId: '', nestId: '', locationId: '', image: '', startup: '' })
                setIsEditing(true)
              }}
              style={{ background: '#10b981', color: '#fff', border: 'none', padding: '8px 16px', borderRadius: '6px', fontWeight: 600, cursor: 'pointer' }}
            >
              + Tambah Paket
            </button>
          </div>

          {isEditing && (
            <form onSubmit={handleSavePackage} style={{ background: '#0a0a0f', padding: '20px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.05)', marginBottom: '20px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginBottom: '16px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Nama Paket</label>
                  <input required value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Harga</label>
                  <input required type="number" value={formData.price} onChange={e => setFormData({...formData, price: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Durasi (Hari)</label>
                  <input required type="number" value={formData.durationDays} onChange={e => setFormData({...formData, durationDays: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
              </div>
              
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '16px', marginBottom: '16px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>RAM (MB)</label>
                  <input required type="number" value={formData.memory} onChange={e => setFormData({...formData, memory: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Disk (MB)</label>
                  <input required type="number" value={formData.disk} onChange={e => setFormData({...formData, disk: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>CPU (%)</label>
                  <input required type="number" value={formData.cpu} onChange={e => setFormData({...formData, cpu: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Databases</label>
                  <input required type="number" value={formData.databases} onChange={e => setFormData({...formData, databases: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '16px', marginBottom: '16px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Egg ID</label>
                  <input required type="number" value={formData.eggId} onChange={e => setFormData({...formData, eggId: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Nest ID</label>
                  <input required type="number" value={formData.nestId} onChange={e => setFormData({...formData, nestId: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Location ID</label>
                  <input required type="number" value={formData.locationId} onChange={e => setFormData({...formData, locationId: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', color: '#94a3b8', marginBottom: '4px' }}>Docker Image</label>
                  <input required value={formData.image} onChange={e => setFormData({...formData, image: e.target.value})} style={{ width: '100%', padding: '10px', background: '#111118', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '6px' }} />
                </div>
              </div>
              
              <div style={{ display: 'flex', gap: '12px', marginTop: '20px' }}>
                <button type="submit" style={{ background: '#3b82f6', color: '#fff', border: 'none', padding: '10px 20px', borderRadius: '6px', fontWeight: 600, cursor: 'pointer' }}>Simpan</button>
                <button type="button" onClick={() => setIsEditing(false)} style={{ background: 'transparent', color: '#94a3b8', border: '1px solid rgba(255,255,255,0.1)', padding: '10px 20px', borderRadius: '6px', fontWeight: 600, cursor: 'pointer' }}>Batal</button>
              </div>
            </form>
          )}

          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '14px' }}>
              <thead>
                <tr style={{ background: 'rgba(255,255,255,0.02)', color: '#94a3b8', textAlign: 'left' }}>
                  <th style={{ padding: '12px' }}>Nama</th>
                  <th style={{ padding: '12px' }}>Harga/Bulan</th>
                  <th style={{ padding: '12px' }}>RAM / Disk</th>
                  <th style={{ padding: '12px' }}>Ptero IDs</th>
                  <th style={{ padding: '12px', textAlign: 'right' }}>Aksi</th>
                </tr>
              </thead>
              <tbody>
                {packages.map(pkg => (
                  <tr key={pkg.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                    <td style={{ padding: '12px', color: '#f1f5f9', fontWeight: 500 }}>{pkg.name}</td>
                    <td style={{ padding: '12px', color: '#10b981', fontWeight: 600 }}>{formatRupiah(pkg.price)}</td>
                    <td style={{ padding: '12px', color: '#94a3b8' }}>{pkg.memory} MB / {pkg.disk} MB</td>
                    <td style={{ padding: '12px', color: '#94a3b8' }}>Egg: {pkg.eggId}, Nest: {pkg.nestId}, Loc: {pkg.locationId}</td>
                    <td style={{ padding: '12px', textAlign: 'right' }}>
                      <button onClick={() => { setFormData(pkg); setIsEditing(true); }} style={{ background: 'rgba(59,130,246,0.1)', color: '#3b82f6', border: '1px solid rgba(59,130,246,0.2)', padding: '6px 12px', borderRadius: '4px', cursor: 'pointer', marginRight: '8px' }}>Edit</button>
                      <button onClick={() => handleDeletePackage(pkg.id)} style={{ background: 'rgba(239,68,68,0.1)', color: '#ef4444', border: '1px solid rgba(239,68,68,0.2)', padding: '6px 12px', borderRadius: '4px', cursor: 'pointer' }}>Hapus</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeTab === 'SERVERS' && (
        <div className="card" style={{ padding: '24px' }}>
          <h2 style={{ fontSize: '18px', fontWeight: 600, color: '#f1f5f9', marginBottom: '20px' }}>Semua Server User</h2>
          
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '14px' }}>
              <thead>
                <tr style={{ background: 'rgba(255,255,255,0.02)', color: '#94a3b8', textAlign: 'left' }}>
                  <th style={{ padding: '12px' }}>User</th>
                  <th style={{ padding: '12px' }}>Paket</th>
                  <th style={{ padding: '12px' }}>Ptero IDs</th>
                  <th style={{ padding: '12px' }}>Status</th>
                  <th style={{ padding: '12px' }}>Expired</th>
                  <th style={{ padding: '12px', textAlign: 'right' }}>Aksi</th>
                </tr>
              </thead>
              <tbody>
                {servers.map(server => (
                  <tr key={server.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                    <td style={{ padding: '12px' }}>
                      <div style={{ color: '#f1f5f9', fontWeight: 500 }}>{server.user?.name}</div>
                      <div style={{ color: '#64748b', fontSize: '12px' }}>{server.user?.email}</div>
                    </td>
                    <td style={{ padding: '12px', color: '#e2e8f0' }}>{server.package?.name}</td>
                    <td style={{ padding: '12px' }}>
                      <div style={{ color: '#94a3b8' }}>User: {server.pteroUserId || '-'}</div>
                      <div style={{ color: '#94a3b8' }}>Server: {server.pteroServerId || '-'}</div>
                    </td>
                    <td style={{ padding: '12px' }}>
                      <span style={{ 
                        background: server.status === 'ACTIVE' ? 'rgba(16,185,129,0.1)' : server.status === 'SUSPENDED' ? 'rgba(245,158,11,0.1)' : 'rgba(239,68,68,0.1)',
                        color: server.status === 'ACTIVE' ? '#10b981' : server.status === 'SUSPENDED' ? '#f59e0b' : '#ef4444',
                        padding: '4px 8px', borderRadius: '4px', fontSize: '12px', fontWeight: 600
                      }}>
                        {server.status}
                      </span>
                    </td>
                    <td style={{ padding: '12px', color: '#94a3b8' }}>
                      {server.expiresAt ? new Date(server.expiresAt).toLocaleDateString('id-ID') : '-'}
                    </td>
                    <td style={{ padding: '12px', textAlign: 'right', display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
                      {server.status === 'ACTIVE' && (
                        <button onClick={() => handleServerAction(server.id, 'suspend')} style={{ background: 'rgba(245,158,11,0.1)', color: '#f59e0b', border: '1px solid rgba(245,158,11,0.2)', padding: '6px 12px', borderRadius: '4px', cursor: 'pointer' }}>Suspend</button>
                      )}
                      {server.status === 'SUSPENDED' && (
                        <button onClick={() => handleServerAction(server.id, 'unsuspend')} style={{ background: 'rgba(16,185,129,0.1)', color: '#10b981', border: '1px solid rgba(16,185,129,0.2)', padding: '6px 12px', borderRadius: '4px', cursor: 'pointer' }}>Unsuspend</button>
                      )}
                      <button onClick={() => handleServerAction(server.id, 'delete')} style={{ background: 'rgba(239,68,68,0.1)', color: '#ef4444', border: '1px solid rgba(239,68,68,0.2)', padding: '6px 12px', borderRadius: '4px', cursor: 'pointer' }}>Hapus</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
