'use client'

import { useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import type { NewsItem } from '@/lib/admin-news'

export function AdminNewsManager({ initialNews }: { initialNews: NewsItem[] }) {
  const t = useTranslations('Admin')
  const locale = useLocale()
  const [news, setNews] = useState(initialNews)
  const [titulo, setTitulo] = useState('')
  const [contenido, setContenido] = useState('')
  const [enlace, setEnlace] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function create(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !titulo.trim() || !contenido.trim()) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch('/api/admin/news', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ titulo, contenido, enlace }),
      })
      const data: { success?: boolean; id?: number } = await res.json()
      if (data.success && data.id) {
        setNews([{ id: data.id, titulo, fecha: new Date().toISOString(), enlace: enlace || null }, ...news])
        setTitulo('')
        setContenido('')
        setEnlace('')
      } else setError(t('genericError'))
    } catch {
      setError(t('genericError'))
    } finally {
      setBusy(false)
    }
  }

  async function remove(id: number) {
    if (!confirm(t('confirmDelete'))) return
    const res = await fetch(`/api/admin/news/${id}`, { method: 'DELETE', credentials: 'same-origin' })
    const data: { success?: boolean } = await res.json()
    if (data.success) setNews(news.filter((n) => n.id !== id))
  }

  const field = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'

  return (
    <div>
      <form onSubmit={create} className="mb-8 space-y-3 rounded-lg border border-amber-900/60 bg-[#241812] p-4">
        <input value={titulo} onChange={(e) => setTitulo(e.target.value)} placeholder={t('newsTitle')} maxLength={200} className={field} />
        <textarea value={contenido} onChange={(e) => setContenido(e.target.value)} placeholder={t('newsContent')} rows={5} className={field} />
        <input value={enlace} onChange={(e) => setEnlace(e.target.value)} placeholder={t('newsLink')} className={field} />
        <button type="submit" disabled={busy} className="rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
          {busy ? t('creating') : t('create')}
        </button>
        {error && <p className="text-red-400">{error}</p>}
      </form>

      {news.length === 0 ? (
        <p className="text-amber-200/70">{t('noNews')}</p>
      ) : (
        <ul className="divide-y divide-amber-900/40">
          {news.map((n) => (
            <li key={n.id} className="flex items-center justify-between gap-4 py-3">
              <div>
                <p className="font-semibold text-amber-300">{n.titulo}</p>
                {n.fecha && <p className="text-xs text-amber-200/50">{new Date(n.fecha).toLocaleString(locale)}</p>}
              </div>
              <button onClick={() => remove(n.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>
  )
}
