'use client'

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

const ENDPOINT_DOCS = [
  {
    method: 'GET',
    path: '/api/h2h/v1/balance',
    title: 'Cek Saldo Akun',
    desc: 'Mendapatkan informasi saldo terkini akun reseller Anda.',
    headers: { 'x-api-key': 'String (Wajib)' },
    response: `{
  "balance": "50000.00"
}`
  },
  {
    method: 'GET',
    path: '/api/h2h/v1/games',
    title: 'Daftar Kategori Game',
    desc: 'Menampilkan semua daftar game yang tersedia di sistem beserta slug-nya.',
    headers: { 'x-api-key': 'String (Wajib)' },
    response: `{
  "games": [
    { "name": "Mobile Legends", "slug": "mobile-legends" },
    { "name": "Free Fire", "slug": "free-fire" }
  ]
}`
  },
  {
    method: 'GET',
    path: '/api/h2h/v1/games?slug={slug}',
    title: 'Daftar Produk Game',
    desc: 'Menampilkan list produk (denom) dari game spesifik berdasarkan slug.',
    headers: { 'x-api-key': 'String (Wajib)' },
    response: `{
  "game": "Mobile Legends",
  "products": [
    {
      "id": "cuid_xyz123",
      "productName": "86 Diamonds",
      "price": 20000,
      "status": true
    }
  ]
}`
  },
  {
    method: 'GET',
    path: '/api/h2h/v1/products',
    title: 'Daftar App Premium',
    desc: 'Menampilkan daftar produk digital/aplikasi premium.',
    headers: { 'x-api-key': 'String (Wajib)' },
    response: `{
  "products": [
    {
      "id": "cuid_abc890",
      "name": "Netflix 1 Bulan",
      "price": 35000,
      "stock": 10
    }
  ]
}`
  },
  {
    method: 'POST',
    path: '/api/h2h/v1/deposit',
    title: 'Top Up / Deposit Saldo',
    desc: 'Membuat tagihan QRIS untuk menambah saldo akun H2H secara otomatis.',
    headers: { 'x-api-key': 'String (Wajib)', 'Content-Type': 'application/json' },
    body: `{
  "amount": 50000 // Minimal 10000
}`,
    response: `{
  "success": true,
  "message": "Silakan lakukan pembayaran sesuai instruksi",
  "data": {
    "transactionId": "cuid_tx123",
    "invoiceId": "cashify_trx_123",
    "amount": 50000,
    "totalAmount": 50123,
    "uniqueCode": 123,
    "qrString": "000201010211...",
    "qrImageUrl": "https://larabert-qrgen...",
    "expiresAt": "2026-04-28T12:00:00.000Z"
  }
}`
  },
  {
    method: 'POST',
    path: '/api/h2h/v1/orders',
    title: 'Buat Pesanan Baru',
    desc: 'Digunakan untuk melakukan transaksi pembelian Game (VIP) atau Produk Digital.',
    headers: { 'x-api-key': 'String (Wajib)', 'Content-Type': 'application/json' },
    body: `{
  // Wajib (Pilih salah satu tipe produk: VIP atau DIGITAL)
  "productType": "VIP", 
  
  // ID produk didapatkan dari endpoint games/products
  "productId": "cuid_xyz123",

  // Wajib untuk transaksi tipe VIP (Game)
  "targetId": "12345678",
  "zone": "1234" // Boleh dikosongkan jika game tidak butuh zone
}`,
    response: `{
  "message": "Pesanan berhasil dibuat",
  "orderId": "order_cuid_123",
  "status": "PROCESSING", // atau PENDING/SUCCESS
  "price": 20000,
  "balanceAfter": 30000
}`
  },
  {
    method: 'GET',
    path: '/api/h2h/v1/orders/{id}',
    title: 'Cek Status Pesanan',
    desc: 'Mendapatkan status pesanan secara real-time dan detail data akun (jika beli produk digital).',
    headers: { 'x-api-key': 'String (Wajib)' },
    response: `{
  "orderId": "order_cuid_123",
  "status": "SUCCESS", // PENDING, PROCESSING, SUCCESS, FAILED, REFUNDED
  "price": "20000",
  "targetId": "12345678",
  "zone": "1234",
  "deliveryData": null // Akan berisi detail akun/password jika produk digital
}`
  }
]

export default function ResellerPage() {
  const { data: session } = useSession()
  const router = useRouter()
  const [apiKeys, setApiKeys] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [creating, setCreating] = useState(false)
  const [keyName, setKeyName] = useState('')
  const [showKey, setShowKey] = useState<Record<string, boolean>>({})
  const [error, setError] = useState('')
  const [copiedId, setCopiedId] = useState('')
  const [ipEditing, setIpEditing] = useState<Record<string, boolean>>({})
  const [ipInputs, setIpInputs] = useState<Record<string, string[]>>({})
  const [webhookInputs, setWebhookInputs] = useState<Record<string, string>>({})
  const [ipSaving, setIpSaving] = useState<Record<string, boolean>>({})

  const userRole = (session?.user as any)?.role

  useEffect(() => {
    if (session === null) { router.push('/auth/login'); return }
    if (session) fetchKeys()
  }, [session])

  const fetchKeys = async () => {
    setLoading(true)
    try {
      const res = await fetch('/api/h2h/v1/apikeys')
      const data = await res.json()
      setApiKeys(data.keys || [])
    } catch {}
    setLoading(false)
  }

  const createKey = async () => {
    setCreating(true)
    setError('')
    try {
      const res = await fetch('/api/h2h/v1/apikeys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: keyName || 'My API Key' }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      setApiKeys(prev => [data.apiKey, ...prev])
      setKeyName('')
    } catch (err: any) {
      setError(err.message)
    }
    setCreating(false)
  }

  const deleteKey = async (id: string) => {
    if (!confirm('Hapus API Key ini?')) return
    await fetch(`/api/h2h/v1/apikeys?id=${id}`, { method: 'DELETE' })
    setApiKeys(prev => prev.filter(k => k.id !== id))
  }

  const copyKey = (key: string, id: string) => {
    navigator.clipboard.writeText(key)
    setCopiedId(id)
    setTimeout(() => setCopiedId(''), 2000)
  }

  const startEditConfig = (keyId: string, currentWhitelist: string | null, currentWebhook: string | null) => {
    const ips: string[] = currentWhitelist ? JSON.parse(currentWhitelist) : []
    while (ips.length < 3) ips.push('')
    setIpInputs(p => ({ ...p, [keyId]: ips }))
    setWebhookInputs(p => ({ ...p, [keyId]: currentWebhook || '' }))
    setIpEditing(p => ({ ...p, [keyId]: true }))
  }

  const saveConfig = async (keyId: string) => {
    setIpSaving(p => ({ ...p, [keyId]: true }))
    try {
      const ips = (ipInputs[keyId] || []).filter(ip => ip.trim())
      const webhook = webhookInputs[keyId]?.trim() || ''
      const res = await fetch('/api/h2h/v1/apikeys', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ keyId, ipWhitelist: ips, webhookUrl: webhook })
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      setApiKeys(prev => prev.map(k => k.id === keyId ? { ...k, ipWhitelist: ips.length > 0 ? JSON.stringify(ips) : null, webhookUrl: webhook || null } : k))
      setIpEditing(p => ({ ...p, [keyId]: false }))
    } catch (e: any) {
      alert(e.message)
    }
    setIpSaving(p => ({ ...p, [keyId]: false }))
  }

  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: '900px', margin: '0 auto', padding: '100px 24px 60px' }}>
        
        <div style={{ marginBottom: '32px' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', background: 'rgba(139,92,246,0.1)', border: '1px solid rgba(139,92,246,0.3)', borderRadius: '100px', padding: '4px 12px', fontSize: '12px', color: '#8b5cf6', fontWeight: 600, marginBottom: '12px' }}>
            🔗 H2H Developer API
          </div>
          <h1 className="font-game" style={{ fontSize: '32px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>API & Integrasi</h1>
          <p style={{ color: '#64748b' }}>Kelola API Key dan integrasikan layanan AmaneNime ke platform/bot Anda</p>
        </div>

        {/* API Keys */}
        <div className="card" style={{ padding: '24px', marginBottom: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', flexWrap: 'wrap', gap: '12px' }}>
            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9' }}>🔑 API Keys</h2>
            <div style={{ display: 'flex', gap: '8px' }}>
              <input className="input" placeholder="Nama Key (opsional)" value={keyName} onChange={e => setKeyName(e.target.value)} style={{ width: 180 }} />
              <button onClick={createKey} disabled={creating} className="btn btn-primary" style={{ fontSize: '13px' }}>
                {creating ? <span className="spinner" /> : '+ Buat Key'}
              </button>
            </div>
          </div>

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

          {loading ? (
            Array(2).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 64, borderRadius: 10, marginBottom: 10 }} />)
          ) : apiKeys.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px', color: '#475569' }}>
              <div style={{ fontSize: '32px', marginBottom: '8px' }}>🔑</div>
              <p>Belum ada API Key. Buat satu untuk memulai.</p>
            </div>
          ) : (
            apiKeys.map(key => (
              <div key={key.id} style={{ padding: '16px', background: 'rgba(255,255,255,0.03)', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.06)', marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
                  <div>
                    <div style={{ fontSize: '14px', fontWeight: 600, color: '#f1f5f9', marginBottom: '4px' }}>{key.name}</div>
                    <div style={{ fontFamily: 'monospace', fontSize: '13px', color: '#64748b' }}>
                      {showKey[key.id] ? key.key : key.key.slice(0, 8) + '••••••••••••••••••••' + key.key.slice(-4)}
                    </div>
                    <div style={{ fontSize: '11px', color: '#475569', marginTop: '4px' }}>
                      Dibuat: {formatDate(key.createdAt)} {key.lastUsedAt ? `• Terakhir: ${formatDate(key.lastUsedAt)}` : ''}
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    <button onClick={() => setShowKey(p => ({ ...p, [key.id]: !p[key.id] }))} className="btn btn-secondary" style={{ fontSize: '12px', padding: '6px 10px' }}>
                      {showKey[key.id] ? '🙈' : '👁️'}
                    </button>
                    <button onClick={() => copyKey(key.key, key.id)} className="btn btn-secondary" style={{ fontSize: '12px', padding: '6px 10px' }}>
                      {copiedId === key.id ? '✅' : '📋'}
                    </button>
                    <button onClick={() => startEditConfig(key.id, key.ipWhitelist, key.webhookUrl)} className="btn btn-secondary" style={{ fontSize: '12px', padding: '6px 10px', borderColor: 'rgba(59,130,246,0.3)', color: '#3b82f6' }}>
                      ⚙️ Konfigurasi
                    </button>
                    <button onClick={() => deleteKey(key.id)} className="btn btn-danger" style={{ fontSize: '12px', padding: '6px 10px' }}>🗑️</button>
                  </div>
                </div>

                {/* Status Whitelist & Webhook */}
                {!ipEditing[key.id] && (
                  <div style={{ marginTop: '10px', fontSize: '12px', color: '#475569', display: 'flex', flexDirection: 'column', gap: '4px' }}>
                    <div>
                      🛡️ IP Whitelist: {key.ipWhitelist ? (
                        <span style={{ color: '#3b82f6' }}>{(JSON.parse(key.ipWhitelist) as string[]).join(', ')}</span>
                      ) : <span style={{ color: '#374151' }}>Semua IP diizinkan</span>}
                    </div>
                    <div>
                      🔗 Webhook: {key.webhookUrl ? (
                        <span style={{ color: '#10b981' }}>{key.webhookUrl}</span>
                      ) : <span style={{ color: '#374151' }}>Belum diatur</span>}
                    </div>
                  </div>
                )}

                {/* Webhook & IP Whitelist Editor */}
                {ipEditing[key.id] && (
                  <div style={{ marginTop: '12px', padding: '16px', background: 'rgba(59,130,246,0.05)', border: '1px solid rgba(59,130,246,0.15)', borderRadius: '8px' }}>
                    
                    {/* Webhook Configuration */}
                    <div style={{ marginBottom: '16px' }}>
                      <div style={{ fontSize: '12px', color: '#8b5cf6', fontWeight: 600, marginBottom: '8px' }}>🔗 Webhook URL (Opsional)</div>
                      <input
                        className="input"
                        style={{ fontSize: '13px', width: '100%' }}
                        placeholder="https://server-bot-anda.com/webhook"
                        value={webhookInputs[key.id] || ''}
                        onChange={e => setWebhookInputs(p => ({ ...p, [key.id]: e.target.value }))}
                      />
                      <div style={{ fontSize: '11px', color: '#475569', marginTop: '6px' }}>Sistem akan mengirim HTTP POST ke URL ini saat pesanan/deposit sukses.</div>
                    </div>

                    <div style={{ height: '1px', background: 'rgba(255,255,255,0.05)', margin: '16px 0' }} />

                    {/* IP Whitelist */}
                    <div style={{ fontSize: '12px', color: '#3b82f6', fontWeight: 600, marginBottom: '8px' }}>🛡️ Whitelist IP (maks. 3 IP)</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', marginBottom: '10px' }}>
                      {[0, 1, 2].map(idx => (
                        <input
                          key={idx}
                          className="input"
                          style={{ fontSize: '13px', fontFamily: 'monospace', width: '100%' }}
                          placeholder={`IP ${idx + 1} (contoh: 1.2.3.4)`}
                          value={(ipInputs[key.id] || ['', '', ''])[idx]}
                          onChange={e => {
                            const arr = [...(ipInputs[key.id] || ['', '', ''])]
                            arr[idx] = e.target.value
                            setIpInputs(p => ({ ...p, [key.id]: arr }))
                          }}
                        />
                      ))}
                    </div>
                    <div style={{ fontSize: '11px', color: '#475569', marginBottom: '16px' }}>Kosongkan semua untuk mengizinkan semua IP (kurang aman).</div>
                    
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button onClick={() => saveConfig(key.id)} disabled={ipSaving[key.id]} className="btn btn-primary" style={{ fontSize: '12px', padding: '6px 16px' }}>
                        {ipSaving[key.id] ? 'Menyimpan...' : 'Simpan Konfigurasi'}
                      </button>
                      <button onClick={() => setIpEditing(p => ({ ...p, [key.id]: false }))} className="btn btn-secondary" style={{ fontSize: '12px', padding: '6px 16px' }}>Batal</button>
                    </div>
                  </div>
                )}
              </div>
            ))
          )}
        </div>

        {/* Documentation */}
        <div className="card" style={{ padding: '24px', marginBottom: '24px' }}>
          <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#f1f5f9', marginBottom: '20px' }}>📖 Dokumentasi API Lengkap</h2>
          
          <div style={{ display: 'grid', gap: '20px' }}>
            <div style={{ padding: '16px', background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.2)', borderRadius: '12px' }}>
              <div style={{ fontSize: '12px', color: '#f59e0b', fontWeight: 600, marginBottom: '8px' }}>BASE URL & AUTENTIKASI</div>
              <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>
                <div>
                  <div style={{ fontSize: '11px', color: '#64748b', marginBottom: '4px' }}>Endpoint Base URL</div>
                  <code style={{ background: '#0d0d14', padding: '6px 12px', borderRadius: '6px', color: '#fbbf24', fontSize: '13px' }}>https://store.amanenime.my.id</code>
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#64748b', marginBottom: '4px' }}>Header Autentikasi (Opsi 1)</div>
                  <code style={{ background: '#0d0d14', padding: '6px 12px', borderRadius: '6px', color: '#fbbf24', fontSize: '13px' }}>x-api-key: YOUR_API_KEY</code>
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#64748b', marginBottom: '4px' }}>Query Parameter (Opsi 2 - Mudah untuk Bot)</div>
                  <code style={{ background: '#0d0d14', padding: '6px 12px', borderRadius: '6px', color: '#fbbf24', fontSize: '13px' }}>?api_key=YOUR_API_KEY</code>
                </div>
              </div>
            </div>

            <div style={{ padding: '16px', background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.2)', borderRadius: '12px' }}>
              <div style={{ fontSize: '12px', color: '#10b981', fontWeight: 600, marginBottom: '8px' }}>FORMAT PAYLOAD WEBHOOK (CALLBACK)</div>
              <p style={{ fontSize: '12px', color: '#64748b', marginBottom: '8px' }}>
                Jika Anda mengatur Webhook URL di pengaturan konfigurasi, sistem akan mengirimkan request HTTP POST dengan format JSON ke URL Anda saat ada event transaksi.
              </p>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '16px' }}>
                <div>
                  <div style={{ fontSize: '11px', color: '#64748b', marginBottom: '4px' }}>Event: Topup / Deposit Saldo Sukses</div>
                  <pre style={{ background: '#0d0d14', padding: '12px', borderRadius: '6px', color: '#e2e8f0', fontSize: '11px', overflowX: 'auto', margin: 0 }}>
{`{
  "event": "DEPOSIT_SUCCESS",
  "transactionId": "cuid_tx_123",
  "amount": 50000,
  "balance": 150000
}`}
                  </pre>
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#64748b', marginBottom: '4px' }}>Event: Status Order Berubah</div>
                  <pre style={{ background: '#0d0d14', padding: '12px', borderRadius: '6px', color: '#e2e8f0', fontSize: '11px', overflowX: 'auto', margin: 0 }}>
{`{
  "event": "ORDER_UPDATE",
  "orderId": "order_cuid_123",
  "status": "SUCCESS", // PENDING/PROCESSING/SUCCESS/FAILED
  "note": "Pesanan berhasil diproses",
  "sn": "Voucher/SN jika ada"
}`}
                  </pre>
                </div>
              </div>
            </div>

            {ENDPOINT_DOCS.map(ep => (
              <div key={ep.path} style={{ border: '1px solid rgba(255,255,255,0.06)', borderRadius: '12px', overflow: 'hidden' }}>
                <div style={{ padding: '16px', background: 'rgba(255,255,255,0.02)', display: 'flex', alignItems: 'flex-start', gap: '16px', borderBottom: '1px solid rgba(255,255,255,0.04)' }}>
                  <span style={{ padding: '4px 12px', borderRadius: '6px', fontSize: '12px', fontWeight: 700, background: ep.method === 'GET' ? 'rgba(16,185,129,0.15)' : 'rgba(59,130,246,0.15)', color: ep.method === 'GET' ? '#10b981' : '#3b82f6' }}>{ep.method}</span>
                  <div>
                    <h3 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '4px' }}>{ep.title}</h3>
                    <code style={{ fontSize: '13px', color: '#94a3b8' }}>{ep.path}</code>
                  </div>
                </div>
                <div style={{ padding: '16px', background: '#0a0a0f' }}>
                  <p style={{ fontSize: '14px', color: '#94a3b8', marginBottom: '16px', lineHeight: 1.6 }}>{ep.desc}</p>
                  
                  {ep.body && (
                    <div style={{ marginBottom: '16px' }}>
                      <div style={{ fontSize: '12px', fontWeight: 600, color: '#e2e8f0', marginBottom: '8px' }}>JSON Request Body:</div>
                      <pre style={{ margin: 0, padding: '12px', background: '#111118', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.05)', fontSize: '12px', color: '#10b981', overflowX: 'auto' }}>
                        {ep.body}
                      </pre>
                    </div>
                  )}

                  <div>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: '#e2e8f0', marginBottom: '8px' }}>Contoh Response (Success 200 OK):</div>
                    <pre style={{ margin: 0, padding: '12px', background: '#111118', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.05)', fontSize: '12px', color: '#3b82f6', overflowX: 'auto' }}>
                      {ep.response}
                    </pre>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Example Request */}
        <div className="card" style={{ padding: '24px' }}>
          <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '16px' }}>💻 Contoh Request (cURL)</h2>
          <pre style={{ background: '#0d0d14', borderRadius: '10px', padding: '16px', fontSize: '12px', color: '#94a3b8', overflowX: 'auto', margin: 0 }}>
{`# Cek Saldo
curl -X GET "https://store.amanenime.my.id/api/h2h/v1/balance" \\
  -H "x-api-key: ANK-xxxxxxxx"

# Buat Order
curl -X POST "https://store.amanenime.my.id/api/h2h/v1/orders" \\
  -H "x-api-key: ANK-xxxxxxxx" \\
  -H "Content-Type: application/json" \\
  -d '{
    "productType": "VIP",
    "productId": "product_id_here",
    "targetId": "12345678",
    "zone": "1234"
  }'`}
          </pre>
        </div>
      </div>
    </main>
  )
}
