'use client'

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

export default function AdminOrders() {
  const [orders, setOrders] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [actionLoading, setActionLoading] = useState<string | null>(null)

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

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

  const handleAction = async (orderId: string, action: string, payload?: any) => {
    if (!confirm('Yakin ingin melakukan aksi ini?')) return
    setActionLoading(orderId)
    try {
      const res = await fetch(`/api/admin/orders?id=${orderId}&action=${action}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload || {}),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      alert('Berhasil')
      fetchOrders()
    } catch (err: any) {
      alert(err.message)
    }
    setActionLoading(null)
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: '24px' }}>
        <div>
          <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>Manajemen Pesanan</h1>
          <p style={{ color: '#64748b' }}>Kelola semua transaksi yang masuk</p>
        </div>
        <div style={{ display: 'flex', gap: '12px' }}>
          <select className="input" value={status} onChange={e => { setStatus(e.target.value); setPage(1) }} style={{ width: 160 }}>
            <option value="">Semua Status</option>
            <option value="PENDING">Pending</option>
            <option value="PAID">Paid</option>
            <option value="PROCESSING">Processing</option>
            <option value="SUCCESS">Success</option>
            <option value="FAILED">Failed</option>
          </select>
          <input className="input" placeholder="Cari ID/User..." value={search} onChange={e => { setSearch(e.target.value); setPage(1) }} style={{ width: 200 }} />
        </div>
      </div>

      <div className="card table-container">
        {loading ? <div className="spinner" style={{ margin: '40px auto', display: 'block' }} /> : (
          <table>
            <thead>
              <tr>
                <th>Order ID / Waktu</th>
                <th>User</th>
                <th>Produk</th>
                <th>Target ID</th>
                <th>Harga</th>
                <th>Status</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {orders.map(order => {
                const statusConfig = getOrderStatusConfig(order.status)
                const isVip = order.productType === 'VIP'
                return (
                  <tr key={order.id}>
                    <td style={{ fontFamily: 'monospace' }}>
                      <div style={{ color: '#f59e0b' }}>#{order.id.slice(-8).toUpperCase()}</div>
                      <div style={{ fontSize: '11px', color: '#64748b' }}>{formatDate(order.createdAt)}</div>
                    </td>
                    <td>
                      <div style={{ fontWeight: 500, color: '#e2e8f0' }}>{order.user?.name}</div>
                      <div style={{ fontSize: '12px', color: '#64748b' }}>{order.user?.email}</div>
                    </td>
                    <td>
                      <div style={{ fontWeight: 500 }}>
                        {order.vipProduct?.productName || order.digitalProduct?.name || order.smmProduct?.name || <span style={{ color: '#475569', fontStyle: 'italic' }}>Produk dihapus</span>}
                      </div>
                      <span style={{ fontSize: '10px', padding: '2px 6px', background: 'rgba(255,255,255,0.1)', borderRadius: 4 }}>
                        {order.productType}
                      </span>
                    </td>
                    <td style={{ fontFamily: 'monospace' }}>
                      {order.targetId || '-'} {order.zone ? `(${order.zone})` : ''}
                    </td>
                    <td style={{ fontWeight: 600, color: '#10b981' }}>{formatRupiah(order.price)}</td>
                    <td>
                      <span className="badge" style={{ background: statusConfig.bg, color: statusConfig.color }}>
                        {statusConfig.label}
                      </span>
                    </td>
                    <td>
                      <div style={{ display: 'flex', gap: '8px' }}>
                        {order.status === 'PROCESSING' && isVip && (
                          <button 
                            className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '12px' }}
                            onClick={() => handleAction(order.id, 'retry-vip')}
                            disabled={actionLoading === order.id}
                          >
                            {actionLoading === order.id ? '...' : 'Retry VIP'}
                          </button>
                        )}
                        {order.status === 'PROCESSING' && !isVip && (
                          <button 
                            className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '12px', color: '#f59e0b', borderColor: 'rgba(245,158,11,0.3)' }}
                            onClick={() => {
                              const email = prompt('Masukkan Email Akun:')
                              if (!email) return
                              const password = prompt('Masukkan Password Akun:')
                              if (!password) return
                              handleAction(order.id, 'manual-deliver', { email, password })
                            }}
                          >
                            Kirim Akun
                          </button>
                        )}
                        <select 
                          className="input" style={{ padding: '4px 8px', fontSize: '12px', width: 'auto', height: 'auto' }}
                          onChange={(e) => {
                            if(e.target.value) handleAction(order.id, 'update-status', { status: e.target.value })
                            e.target.value = ''
                          }}
                        >
                          <option value="">Ubah Status...</option>
                          <option value="SUCCESS">Success</option>
                          <option value="FAILED">Failed</option>
                          <option value="REFUNDED">Refund</option>
                        </select>
                      </div>
                      {order.adminNote && <div style={{ fontSize: '11px', color: '#ef4444', marginTop: 4 }}>Note: {order.adminNote}</div>}
                    </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>
  )
}
