'use client'

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

export default function AdminVipProducts() {
  const [products, setProducts] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [search, setSearch] = useState('')
  const [syncing, setSyncing] = useState(false)
  const [syncResult, setSyncResult] = useState<any>(null)

  const fetchProducts = () => {
    setLoading(true)
    fetch(`/api/admin/products/vip?page=${page}&limit=20&search=${search}`)
      .then(r => r.json())
      .then(d => { setProducts(d.products || []); setTotalPages(d.pages || 1); setLoading(false) })
  }

  useEffect(() => {
    const delay = setTimeout(fetchProducts, 300)
    return () => clearTimeout(delay)
  }, [page, search])

  const handleSync = async () => {
    if (!confirm('Proses ini akan memakan waktu. Lanjutkan?')) return
    setSyncing(true)
    setSyncResult(null)
    try {
      const res = await fetch('/api/admin/products/vip', { 
        method: 'POST', 
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ defaultMargin: 15 }) 
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Gagal sinkronisasi')
      setSyncResult(data)
      fetchProducts()
    } catch (err: any) {
      setSyncResult({ error: true, message: err.message })
    }
    setSyncing(false)
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: '24px', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>Game VIP Products</h1>
          <p style={{ color: '#64748b' }}>Sinkronisasi dan margin produk dari VIP Reseller</p>
        </div>
        <div style={{ display: 'flex', gap: '12px' }}>
          <input className="input" placeholder="Cari game/produk..." value={search} onChange={e => { setSearch(e.target.value); setPage(1) }} style={{ width: 250 }} />
          <button className="btn btn-primary" onClick={handleSync} disabled={syncing}>
            {syncing ? <><span className="spinner"/> Syncing...</> : '🔄 Sync VIP Reseller'}
          </button>
        </div>
      </div>

      {syncResult && (
        <div style={{ padding: '16px', background: syncResult.error ? 'rgba(239,68,68,0.1)' : 'rgba(16,185,129,0.1)', border: `1px solid ${syncResult.error ? 'rgba(239,68,68,0.2)' : 'rgba(16,185,129,0.2)'}`, borderRadius: '12px', marginBottom: '24px', color: syncResult.error ? '#ef4444' : '#10b981' }}>
          {syncResult.error ? '❌ ' : '✅ '} {syncResult.message}
        </div>
      )}

      <div className="card table-container">
        {loading ? <div className="spinner" style={{ margin: '40px auto', display: 'block' }} /> : (
          <table>
            <thead>
              <tr>
                <th>Kode</th>
                <th>Game / Kategori</th>
                <th>Nama Produk</th>
                <th>Harga Asli</th>
                <th>Harga Jual (Margin)</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {products.map(p => (
                <tr key={p.id}>
                  <td style={{ fontFamily: 'monospace', color: '#94a3b8' }}>{p.providerCode}</td>
                  <td style={{ fontWeight: 600 }}>{p.gameName}</td>
                  <td>{p.productName}</td>
                  <td style={{ color: '#ef4444' }}>{formatRupiah(p.price)}</td>
                  <td style={{ color: '#10b981', fontWeight: 600 }}>
                    {formatRupiah(p.sellPrice)} <span style={{ fontSize: 10, color: '#64748b', fontWeight: 400 }}>({p.margin}%)</span>
                  </td>
                  <td>
                    <span className="badge" style={{ background: p.status ? 'rgba(16,185,129,0.1)' : 'rgba(239,68,68,0.1)', color: p.status ? '#10b981' : '#ef4444' }}>
                      {p.status ? 'Tersedia' : 'Gangguan'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {totalPages > 1 && (
        <div style={{ display: 'flex', justifyContent: 'center', gap: '8px', marginTop: '24px' }}>
          <button className="btn btn-secondary" disabled={page === 1} onClick={() => setPage(p => p - 1)}>Prev</button>
          <span style={{ padding: '8px 16px', color: '#94a3b8' }}>{page} / {totalPages}</span>
          <button className="btn btn-secondary" disabled={page === totalPages} onClick={() => setPage(p => p + 1)}>Next</button>
        </div>
      )}
    </div>
  )
}
