'use client'

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

export function AdminVotesManager({ initial }: { initial: VoteSite[] }) {
  const t = useTranslations('Admin')
  const [sites, setSites] = useState(initial)
  const [form, setForm] = useState({ name: '', url: '', imageUrl: '', points: '1' })
  const [busy, setBusy] = useState(false)

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

  async function create(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !form.name.trim() || !form.url.trim()) return
    setBusy(true)
    try {
      const res = await fetch('/api/admin/votes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ ...form, points: Number(form.points) }),
      })
      const data: { success?: boolean; id?: number } = await res.json()
      if (data.success && data.id) {
        setSites([
          ...sites,
          { id: data.id, name: form.name, url: form.url, image_url: form.imageUrl, points: Number(form.points) },
        ])
        setForm({ name: '', url: '', imageUrl: '', points: '1' })
      }
    } finally {
      setBusy(false)
    }
  }

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

  const field = 'nw-input'
  return (
    <div>
      <form onSubmit={create} className="mb-8 space-y-3 nw-card">
        <input value={form.name} onChange={(e) => upd('name', e.target.value)} placeholder={t('voteName')} className={field} />
        <input value={form.url} onChange={(e) => upd('url', e.target.value)} placeholder={t('voteUrl')} className={field} />
        <input value={form.imageUrl} onChange={(e) => upd('imageUrl', e.target.value)} placeholder={t('voteImage')} className={field} />
        <input type="number" min="0" value={form.points} onChange={(e) => upd('points', e.target.value)} placeholder={t('votePoints')} className={field} />
        <button type="submit" disabled={busy} className="nw-btn disabled:opacity-60">
          {busy ? t('creating') : t('create')}
        </button>
      </form>
      {sites.length === 0 ? (
        <p className="text-amber-200/70">{t('noVotes')}</p>
      ) : (
        <ul className="divide-y divide-amber-900/40">
          {sites.map((s) => (
            <li key={s.id} className="flex items-center justify-between gap-4 py-3">
              <div>
                <p className="font-semibold text-amber-300">{s.name}</p>
                <p className="text-xs text-amber-200/50">
                  {s.points} PV · {s.url}
                </p>
              </div>
              <button onClick={() => remove(s.id)} className="rounded border border-red-900/60 px-3 py-1 text-sm text-red-400 hover:bg-red-950/40">
                {t('delete')}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
