'use client'

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

export function AdminGoldManager({ initial }: { initial: GoldOption[] }) {
  const t = useTranslations('Admin')
  const [opts, setOpts] = useState(initial)
  const [form, setForm] = useState({ goldAmount: '', price: '' })
  const [busy, setBusy] = useState(false)

  function upd(k: string, v: string) {
    setForm((f) => ({ ...f, [k]: v }))
  }

  async function create(e: React.FormEvent) {
    e.preventDefault()
    const goldAmount = Number(form.goldAmount)
    const price = Number(form.price)
    if (busy || !(goldAmount > 0) || !(price >= 0)) return
    setBusy(true)
    try {
      const res = await fetch('/api/admin/gold', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ goldAmount, price }),
      })
      const data: { success?: boolean; id?: number } = await res.json()
      if (data.success && data.id) {
        setOpts(
          [...opts, { id: data.id, gold_amount: goldAmount, price }].sort((a, b) => a.gold_amount - b.gold_amount),
        )
        setForm({ goldAmount: '', price: '' })
      }
    } finally {
      setBusy(false)
    }
  }

  async function remove(id: number) {
    if (!confirm(t('confirmDelete'))) return
    const res = await fetch(`/api/admin/gold/${id}`, { method: 'DELETE', credentials: 'same-origin' })
    if ((await res.json()).success) setOpts(opts.filter((o) => o.id !== id))
  }

  return (
    <div>
      <form onSubmit={create} className="admin-form info-box-light separate2">
        <span className="second-brown">{t('goldAmount')}</span>
        <input type="number" min="1" value={form.goldAmount} onChange={(e) => upd('goldAmount', e.target.value)} placeholder="10000" />
        <span className="second-brown">{t('goldPrice')}</span>
        <input type="number" min="0" step="0.01" value={form.price} onChange={(e) => upd('price', e.target.value)} placeholder="4.99" />
        <button type="submit" disabled={busy}>
          {busy ? t('creating') : t('create')}
        </button>
      </form>
      <br />
      {opts.length === 0 ? (
        <p className="second-brown centered">{t('noGold')}</p>
      ) : (
        <table className="max-center-table">
          <tbody>
            {opts.map((o) => (
              <tr key={o.id} className="team-center-table-tr">
                <td className="lefted separate">
                  <span className="yellow-info">{o.gold_amount.toLocaleString()} {t('goldUnit')}</span>
                  <p className="third-brown small-font">{o.price.toFixed(2)} €</p>
                </td>
                <td className="real-info-box">
                  <button onClick={() => remove(o.id)} className="ns-tool-btn red-info2">
                    {t('delete')}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  )
}
