'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))
  }

  return (
    <div>
      <form onSubmit={create} className="admin-form info-box-light separate2">
        <input value={titulo} onChange={(e) => setTitulo(e.target.value)} placeholder={t('newsTitle')} maxLength={200} />
        <textarea value={contenido} onChange={(e) => setContenido(e.target.value)} placeholder={t('newsContent')} rows={5} />
        <input value={enlace} onChange={(e) => setEnlace(e.target.value)} placeholder={t('newsLink')} />
        <button type="submit" disabled={busy}>
          {busy ? t('creating') : t('create')}
        </button>
        <div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
          {error && <span className="red-form-response">{error}</span>}
        </div>
      </form>
      <br />

      {news.length === 0 ? (
        <p className="second-brown centered">{t('noNews')}</p>
      ) : (
        <table className="max-center-table">
          <tbody>
            {news.map((n) => (
              <tr key={n.id} className="team-center-table-tr">
                <td className="lefted separate">
                  <span className="yellow-info">{n.titulo}</span>
                  {n.fecha && <p className="third-brown small-font">{new Date(n.fecha).toLocaleString(locale)}</p>}
                </td>
                <td className="real-info-box">
                  <button onClick={() => remove(n.id)} className="nw-tool-btn red-info2">
                    {t('delete')}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  )
}
