'use client'

import { useState, useEffect, useCallback } from 'react'
import Header from '@/components/layout/Header'
import { useSession } from 'next-auth/react'
import { PlusIcon, XMarkIcon, CheckIcon, TrashIcon, PencilSquareIcon } from '@heroicons/react/24/outline'

type News = {
  id: number; title: string; content: string; published: boolean; createdAt: string; updatedAt: string
  author: { name: string; email: string }
}

export default function NoticiasPage() {
  const { data: session } = useSession()
  const canEdit = ['SUPER_ADMIN', 'ADMIN', 'EDITOR'].includes((session?.user as { role?: string })?.role ?? '')

  const [items, setItems] = useState<News[]>([])
  const [loading, setLoading] = useState(true)
  const [modal, setModal] = useState(false)
  const [editing, setEditing] = useState<News | null>(null)
  const [form, setForm] = useState({ title: '', content: '', published: false })
  const [saving, setSaving] = useState(false)
  const [confirmDel, setConfirmDel] = useState<News | null>(null)
  const [expanded, setExpanded] = useState<number | null>(null)

  const load = useCallback(async () => {
    setLoading(true)
    const res = await fetch('/api/noticias')
    setItems(await res.json())
    setLoading(false)
  }, [])

  useEffect(() => { load() }, [load])

  function openNew() { setEditing(null); setForm({ title: '', content: '', published: false }); setModal(true) }
  function openEdit(n: News) { setEditing(n); setForm({ title: n.title, content: n.content, published: n.published }); setModal(true) }

  async function save() {
    setSaving(true)
    await fetch(editing ? `/api/noticias/${editing.id}` : '/api/noticias', {
      method: editing ? 'PUT' : 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form),
    })
    setSaving(false); setModal(false); load()
  }

  async function togglePublish(n: News) {
    await fetch(`/api/noticias/${n.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: n.title, content: n.content, published: !n.published }),
    })
    load()
  }

  async function del(n: News) {
    await fetch(`/api/noticias/${n.id}`, { method: 'DELETE' })
    setConfirmDel(null); load()
  }

  const published = items.filter(i => i.published)
  const drafts = items.filter(i => !i.published)

  return (
    <div>
      <Header title="Noticias y Comunicados" />
      <div className="p-6 space-y-6">
        {canEdit && (
          <div className="flex justify-end">
            <button onClick={openNew} className="flex items-center gap-1.5 bg-green-600 hover:bg-green-700 text-white text-sm font-medium px-4 py-2 rounded-lg">
              <PlusIcon className="w-4 h-4" /> Nueva noticia
            </button>
          </div>
        )}

        {loading ? <p className="text-gray-400 text-sm">Cargando...</p> : (
          <>
            {published.length > 0 && (
              <div>
                <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Publicadas</h3>
                <div className="space-y-3">
                  {published.map(n => (
                    <div key={n.id} className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
                      <button
                        onClick={() => setExpanded(expanded === n.id ? null : n.id)}
                        className="w-full flex items-start justify-between p-5 text-left"
                      >
                        <div>
                          <p className="font-semibold text-gray-800">{n.title}</p>
                          <p className="text-xs text-gray-400 mt-1">
                            {n.author.name} · {new Date(n.createdAt).toLocaleDateString('es-CL')}
                          </p>
                        </div>
                        <span className="flex items-center gap-2 ml-4 flex-shrink-0">
                          <span className="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700">Publicada</span>
                          <svg className={`w-4 h-4 text-gray-400 transition-transform ${expanded === n.id ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
                        </span>
                      </button>
                      {expanded === n.id && (
                        <div className="px-5 pb-5 border-t border-gray-50">
                          <p className="text-sm text-gray-600 whitespace-pre-wrap mt-4">{n.content}</p>
                          {canEdit && (
                            <div className="flex gap-2 mt-4">
                              <button onClick={() => openEdit(n)} className="flex items-center gap-1 text-xs text-gray-500 hover:text-green-600">
                                <PencilSquareIcon className="w-3.5 h-3.5" /> Editar
                              </button>
                              <button onClick={() => togglePublish(n)} className="flex items-center gap-1 text-xs text-gray-500 hover:text-yellow-600">
                                Despublicar
                              </button>
                              <button onClick={() => setConfirmDel(n)} className="flex items-center gap-1 text-xs text-gray-500 hover:text-red-600">
                                <TrashIcon className="w-3.5 h-3.5" /> Eliminar
                              </button>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {canEdit && drafts.length > 0 && (
              <div>
                <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Borradores</h3>
                <div className="space-y-2">
                  {drafts.map(n => (
                    <div key={n.id} className="bg-white rounded-xl border border-dashed border-gray-200 p-4 flex items-center justify-between">
                      <div>
                        <p className="font-medium text-gray-700 text-sm">{n.title}</p>
                        <p className="text-xs text-gray-400">{n.author.name} · {new Date(n.updatedAt).toLocaleDateString('es-CL')}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        <button onClick={() => togglePublish(n)} className="flex items-center gap-1 text-xs font-medium text-green-600 hover:text-green-800 px-3 py-1.5 border border-green-200 rounded-lg">
                          Publicar
                        </button>
                        <button onClick={() => openEdit(n)} className="text-gray-400 hover:text-green-600"><PencilSquareIcon className="w-4 h-4" /></button>
                        <button onClick={() => setConfirmDel(n)} className="text-gray-400 hover:text-red-600"><TrashIcon className="w-4 h-4" /></button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {items.length === 0 && (
              <div className="text-center py-16 text-gray-400">
                <p className="text-sm">No hay noticias publicadas.</p>
              </div>
            )}
          </>
        )}
      </div>

      {modal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col">
            <div className="flex items-center justify-between p-5 border-b border-gray-100">
              <h3 className="font-semibold text-gray-800">{editing ? 'Editar noticia' : 'Nueva noticia'}</h3>
              <button onClick={() => setModal(false)}><XMarkIcon className="w-5 h-5 text-gray-400" /></button>
            </div>
            <div className="p-5 space-y-4 overflow-y-auto flex-1">
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1.5">Título *</label>
                <input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                  placeholder="Título de la noticia" />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1.5">Contenido *</label>
                <textarea value={form.content} onChange={e => setForm(f => ({ ...f, content: e.target.value }))}
                  rows={10} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500 resize-none"
                  placeholder="Escribe el contenido del comunicado..." />
              </div>
              <label className="flex items-center gap-2 cursor-pointer">
                <input type="checkbox" checked={form.published} onChange={e => setForm(f => ({ ...f, published: e.target.checked }))}
                  className="w-4 h-4 rounded accent-green-600" />
                <span className="text-sm text-gray-700">Publicar inmediatamente</span>
              </label>
            </div>
            <div className="p-5 border-t border-gray-100 flex justify-end gap-3">
              <button onClick={() => setModal(false)} className="px-4 py-2 text-sm text-gray-600">Cancelar</button>
              <button onClick={save} disabled={saving || !form.title || !form.content}
                className="flex items-center gap-1.5 px-4 py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-60 font-medium">
                <CheckIcon className="w-4 h-4" />{saving ? 'Guardando...' : 'Guardar'}
              </button>
            </div>
          </div>
        </div>
      )}

      {confirmDel && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-sm p-6">
            <h3 className="font-semibold text-gray-800 mb-2">Eliminar noticia</h3>
            <p className="text-sm text-gray-500 mb-5">¿Eliminar <strong>{confirmDel.title}</strong>?</p>
            <div className="flex justify-end gap-3">
              <button onClick={() => setConfirmDel(null)} className="px-4 py-2 text-sm text-gray-600">Cancelar</button>
              <button onClick={() => del(confirmDel)} className="px-4 py-2 text-sm bg-red-600 text-white rounded-lg">Eliminar</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
