'use client'

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

export default function AdminOtpPage() {
  const [orders, setOrders] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [statusFilter, setStatusFilter] = useState('')

  const fetchOrders = () => {
    setLoading(true)
    fetch(`/api/admin/otp?page=${page}&limit=10${statusFilter ? `&status=${statusFilter}` : ''}`)
      .then(r => r.json())
      .then(d => {
        setOrders(d.orders || [])
        setTotalPages(d.pages || 1)
        setLoading(false)
      })
      .catch(() => setLoading(false))
  }

  useEffect(() => {
    fetchOrders()
  }, [page, statusFilter])

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
        <div>
          <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9' }}>🔐 OTP Orders</h1>
          <p style={{ color: '#64748b', fontSize: '14px', marginTop: '4px' }}>Manajemen pesanan nomor OTP virtual</p>
        </div>

        <select
          className="input"
          style={{ width: 'auto', minWidth: '160px' }}
          value={statusFilter}
          onChange={(e) => { setStatusFilter(e.target.value); setPage(1) }}
        >
          <option value="">Semua Status</option>
          <option value="pending">Menunggu OTP</option>
          <option value="received">Diterima</option>
          <option value="done">Selesai</option>
          <option value="cancel">Dibatalkan</option>
        </select>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: '24px' }}>
            {Array(5).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 60, borderRadius: 8, marginBottom: 16 }} />)}
          </div>
        ) : orders.length === 0 ? (
          <div style={{ padding: '40px', textAlign: 'center', color: '#64748b' }}>Belum ada pesanan OTP</div>
        ) : (
          <div className="table-container">
            <table>
              <thead>
                <tr>
                  <th>Order ID</th>
                  <th>User</th>
                  <th>Layanan</th>
                  <th>Negara & Harga</th>
                  <th>Nomor & Code</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {orders.map(order => {
                  const statusColors: Record<string, string> = {
                    pending: '#f59e0b', received: '#10b981', done: '#3b82f6', cancel: '#ef4444'
                  }
                  const c = statusColors[order.status] || '#64748b'

                  return (
                    <tr key={order.id}>
                      <td style={{ fontFamily: 'monospace', color: '#94a3b8' }}>
                        {order.id.slice(-8).toUpperCase()}
                        <div style={{ fontSize: '11px', color: '#64748b', marginTop: '4px' }}>{formatDate(order.createdAt)}</div>
                      </td>
                      <td>
                        <div style={{ fontWeight: 600, color: '#f1f5f9' }}>{order.user.name}</div>
                        <div style={{ fontSize: '12px', color: '#64748b' }}>{order.user.email}</div>
                      </td>
                      <td>
                        <div style={{ fontWeight: 600, color: '#e2e8f0' }}>{order.serviceName}</div>
                      </td>
                      <td>
                        <div style={{ color: '#e2e8f0' }}>{order.countryName}</div>
                        <div style={{ fontSize: '12px', color: '#10b981', fontWeight: 600 }}>{formatRupiah(order.price)}</div>
                      </td>
                      <td>
                        <div style={{ color: '#e2e8f0', fontFamily: 'monospace' }}>{order.phoneNumber || '-'}</div>
                        <div style={{ fontSize: '12px', color: '#f59e0b', fontWeight: 600, fontFamily: 'monospace' }}>{order.otpCode || '-'}</div>
                      </td>
                      <td>
                        <span className="badge" style={{ background: `${c}20`, color: c, textTransform: 'uppercase' }}>
                          {order.status}
                        </span>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </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>
          <div style={{ display: 'flex', alignItems: 'center', padding: '0 16px', color: '#94a3b8', fontSize: '14px' }}>
            Hal {page} dari {totalPages}
          </div>
          <button className="btn btn-secondary" disabled={page === totalPages} onClick={() => setPage(p => p + 1)}>Next →</button>
        </div>
      )}
    </div>
  )
}
