'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import type { AccountRow } from '@/lib/admin-users'

export function AdminUsersManager() {
  const t = useTranslations('Admin')
  const [q, setQ] = useState('')
  const [accounts, setAccounts] = useState<AccountRow[]>([])
  const [busy, setBusy] = useState(false)
  const [searched, setSearched] = useState(false)

  async function search(e: React.FormEvent) {
    e.preventDefault()
    if (q.trim().length < 2) return
    setBusy(true)
    try {
      const res = await fetch(`/api/admin/users?q=${encodeURIComponent(q.trim())}`, { credentials: 'same-origin' })
      const data: { success?: boolean; accounts?: AccountRow[] } = await res.json()
      setAccounts(data.accounts ?? [])
      setSearched(true)
    } finally {
      setBusy(false)
    }
  }

  async function act(acc: AccountRow, action: 'ban' | 'unban') {
    let reason = ''
    let days = 0
    if (action === 'ban') {
      reason = prompt(t('banReasonPrompt'), '') ?? ''
      if (reason === null) return
      const d = prompt(t('banDaysPrompt'), '0')
      if (d === null) return
      days = Number(d) || 0
    } else if (!confirm(t('confirmUnban', { name: acc.username }))) {
      return
    }
    const res = await fetch('/api/admin/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify({ accountId: acc.id, action, reason, days }),
    })
    if ((await res.json()).success) {
      setAccounts((list) =>
        list.map((a) =>
          a.id === acc.id
            ? { ...a, banned: action === 'ban', ban_reason: action === 'ban' ? reason : null, ban_until: null }
            : a,
        ),
      )
    }
  }

  return (
    <div>
      <form onSubmit={search} className="mb-6 flex gap-2">
        <input
          type="search"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder={t('userSearchPlaceholder')}
          className="nw-input flex-1"
        />
        <button type="submit" disabled={busy} className="nw-btn whitespace-nowrap disabled:opacity-60">
          {busy ? t('searching') : t('search')}
        </button>
      </form>

      {searched && accounts.length === 0 ? (
        <p className="text-amber-200/70">{t('noUsers')}</p>
      ) : (
        <ul className="divide-y divide-amber-900/40">
          {accounts.map((a) => (
            <li key={a.id} className="flex flex-wrap items-center justify-between gap-3 py-3">
              <div className="min-w-0">
                <p className="flex items-center gap-2 font-semibold text-amber-300">
                  {a.username}
                  {a.gmlevel > 0 && (
                    <span className="rounded bg-nw-gold/15 px-1.5 py-0.5 text-xs text-nw-gold-light">GM {a.gmlevel}</span>
                  )}
                  {a.online && <span className="text-xs text-green-400">● {t('online')}</span>}
                  {a.banned && <span className="text-xs text-red-400">⛔ {t('banned')}</span>}
                </p>
                <p className="truncate text-xs text-amber-200/50">
                  #{a.id}
                  {a.email && ` · ${a.email}`}
                  {a.last_login && ` · ${t('lastLogin')}: ${new Date(a.last_login).toLocaleDateString()}`}
                  {a.banned && a.ban_reason && ` · ${a.ban_reason}`}
                  {a.banned && a.ban_until && ` (${new Date(a.ban_until).toLocaleDateString()})`}
                </p>
              </div>
              {a.banned ? (
                <button
                  onClick={() => act(a, 'unban')}
                  className="rounded border border-green-900/60 px-3 py-1 text-sm text-green-400 hover:bg-green-950/40"
                >
                  {t('unban')}
                </button>
              ) : (
                <button
                  onClick={() => act(a, 'ban')}
                  className="rounded border border-red-900/60 px-3 py-1 text-sm text-red-400 hover:bg-red-950/40"
                >
                  {t('ban')}
                </button>
              )}
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
