'use client'

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

export default function AdminUsers() {
  const [users, setUsers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [search, setSearch] = useState('')

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

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

  const handleUpdate = async (id: string, payload: any) => {
    try {
      const res = await fetch(`/api/admin/users?id=${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })
      if (!res.ok) throw new Error('Gagal update')
      fetchUsers()
    } catch (err) {
      alert('Gagal mengupdate user')
    }
  }

  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 Pengguna</h1>
          <p style={{ color: '#64748b' }}>Kelola akun dan saldo pengguna</p>
        </div>
        <input 
          className="input" placeholder="Cari nama/email..." 
          value={search} onChange={e => { setSearch(e.target.value); setPage(1) }} 
          style={{ width: 250 }} 
        />
      </div>

      <div className="card table-container">
        {loading ? <div className="spinner" style={{ margin: '40px auto', display: 'block' }} /> : (
          <table>
            <thead>
              <tr>
                <th>Pengguna</th>
                <th>Role</th>
                <th>Saldo</th>
                <th>Pesanan</th>
                <th>Bergabung</th>
                <th>Status</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {users.map(user => (
                <tr key={user.id}>
                  <td>
                    <div style={{ fontWeight: 600, color: '#e2e8f0' }}>{user.name}</div>
                    <div style={{ fontSize: '12px', color: '#64748b' }}>{user.email}</div>
                  </td>
                  <td>
                    <select 
                      className="input" 
                      style={{ padding: '4px 8px', fontSize: '12px', width: 'auto', height: 'auto', background: user.role === 'ADMIN' ? 'rgba(245,158,11,0.1)' : user.role === 'RESELLER' ? 'rgba(139,92,246,0.1)' : 'var(--bg-secondary)', color: user.role === 'ADMIN' ? '#f59e0b' : user.role === 'RESELLER' ? '#8b5cf6' : '#e2e8f0', borderColor: user.role === 'ADMIN' ? 'rgba(245,158,11,0.3)' : user.role === 'RESELLER' ? 'rgba(139,92,246,0.3)' : 'var(--border-color)' }}
                      value={user.role}
                      onChange={e => handleUpdate(user.id, { role: e.target.value })}
                    >
                      <option value="USER">User</option>
                      <option value="RESELLER">Reseller</option>
                      <option value="ADMIN">Admin</option>
                    </select>
                  </td>
                  <td style={{ fontWeight: 600, color: '#10b981' }}>{formatRupiah(user.balance)}</td>
                  <td>{user._count?.orders || 0} TRX</td>
                  <td style={{ fontSize: '13px' }}>{formatDate(user.createdAt)}</td>
                  <td>
                    <span className="badge" style={{ background: user.isBanned ? 'rgba(239,68,68,0.1)' : 'rgba(16,185,129,0.1)', color: user.isBanned ? '#ef4444' : '#10b981' }}>
                      {user.isBanned ? 'Banned' : 'Active'}
                    </span>
                  </td>
                  <td>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button 
                        className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '12px' }}
                        onClick={() => {
                          const amt = prompt(`Masukkan saldo baru untuk ${user.name}:`, user.balance)
                          if (amt && !isNaN(Number(amt))) handleUpdate(user.id, { balance: Number(amt), reason: 'Manual admin edit' })
                        }}
                      >
                        Edit Saldo
                      </button>
                      <button 
                        className={`btn ${user.isBanned ? 'btn-secondary' : 'btn-danger'}`} style={{ padding: '6px 12px', fontSize: '12px' }}
                        onClick={() => handleUpdate(user.id, { isBanned: !user.isBanned })}
                      >
                        {user.isBanned ? 'Unban' : 'Ban'}
                      </button>
                    </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>
  )
}
