'use client'

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

const EMPTY = { titulo: '', tituloEn: '', contenido: '', contenidoEn: '', enlace: '' }
type Draft = typeof EMPTY

export function AdminNewsManager({ initialNews }: { initialNews: NewsItem[] }) {
  const t = useTranslations('Admin')
  const locale = useLocale()
  const [news, setNews] = useState(initialNews)
  const [draft, setDraft] = useState<Draft>(EMPTY)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [editId, setEditId] = useState<number | null>(null)
  const [edit, setEdit] = useState<Draft>(EMPTY)

  async function create(e: React.FormEvent) {
    e.preventDefault()
    if (busy || !draft.titulo.trim() || !draft.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(draft),
      })
      const data: { success?: boolean; id?: number } = await res.json()
      if (data.success && data.id) {
        setNews([{ id: data.id, ...draft, fecha: new Date().toISOString(), enlace: draft.enlace || null }, ...news])
        setDraft(EMPTY)
      } else setError(t('genericError'))
    } catch {
      setError(t('genericError'))
    } finally {
      setBusy(false)
    }
  }

  function startEdit(n: NewsItem) {
    setEditId(n.id)
    setEdit({ titulo: n.titulo, tituloEn: n.tituloEn, contenido: n.contenido, contenidoEn: n.contenidoEn, enlace: n.enlace || '' })
    setError(null)
  }

  async function save(id: number) {
    if (busy || !edit.titulo.trim() || !edit.contenido.trim()) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch(`/api/admin/news/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify(edit),
      })
      const data: { success?: boolean } = await res.json()
      if (data.success) {
        setNews(news.map((n) => (n.id === id ? { ...n, ...edit, enlace: edit.enlace || null } : n)))
        setEditId(null)
      } 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={draft.titulo} onChange={(e) => setDraft({ ...draft, titulo: e.target.value })} placeholder={t('newsTitle')} maxLength={200} />
        <textarea value={draft.contenido} onChange={(e) => setDraft({ ...draft, contenido: e.target.value })} placeholder={t('newsContent')} rows={5} />
        <input value={draft.tituloEn} onChange={(e) => setDraft({ ...draft, tituloEn: e.target.value })} placeholder={t('newsTitleEn')} maxLength={200} />
        <textarea value={draft.contenidoEn} onChange={(e) => setDraft({ ...draft, contenidoEn: e.target.value })} placeholder={t('newsContentEn')} rows={5} />
        <input value={draft.enlace} onChange={(e) => setDraft({ ...draft, enlace: e.target.value })} placeholder={t('newsLink')} />
        <p className="third-brown small-font">{t('newsEnHint')}</p>
        <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">
                {editId === n.id ? (
                  <td className="lefted separate" colSpan={2}>
                    <input value={edit.titulo} onChange={(e) => setEdit({ ...edit, titulo: e.target.value })} placeholder={t('newsTitle')} maxLength={200} />
                    <textarea value={edit.contenido} onChange={(e) => setEdit({ ...edit, contenido: e.target.value })} placeholder={t('newsContent')} rows={4} />
                    <input value={edit.tituloEn} onChange={(e) => setEdit({ ...edit, tituloEn: e.target.value })} placeholder={t('newsTitleEn')} maxLength={200} />
                    <textarea value={edit.contenidoEn} onChange={(e) => setEdit({ ...edit, contenidoEn: e.target.value })} placeholder={t('newsContentEn')} rows={4} />
                    <input value={edit.enlace} onChange={(e) => setEdit({ ...edit, enlace: e.target.value })} placeholder={t('newsLink')} />
                    <button onClick={() => save(n.id)} disabled={busy} className="ns-tool-btn">
                      {busy ? t('saving') : t('save')}
                    </button>{' '}
                    <button onClick={() => setEditId(null)} className="ns-tool-btn">
                      {t('cancel')}
                    </button>
                  </td>
                ) : (
                  <>
                    <td className="lefted separate">
                      <span className="yellow-info">{n.titulo}</span>
                      {n.tituloEn && <span className="third-brown small-font"> · EN: {n.tituloEn}</span>}
                      {n.fecha && <p className="third-brown small-font">{new Date(n.fecha).toLocaleString(locale)}</p>}
                    </td>
                    <td className="real-info-box">
                      <button onClick={() => startEdit(n)} className="ns-tool-btn">
                        {t('edit')}
                      </button>{' '}
                      <button onClick={() => remove(n.id)} className="ns-tool-btn red-info2">
                        {t('delete')}
                      </button>
                    </td>
                  </>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  )
}
