"use client";

import { useState } from "react";
import { Plus, Edit, Trash2, Eye, EyeOff, XCircle, AlertTriangle, Newspaper } from "lucide-react";
import { createNoticia, updateNoticia, deleteNoticia, togglePublicado } from "@/app/actions/noticias";
import { useRouter } from "next/navigation";

type Colegio = { id: string; nombre: string };
type Noticia = {
  id: string; titulo: string; resumen: string | null; contenido: string;
  publicado: boolean; createdAt: Date; colegioId: string | null;
  colegio: { id: string; nombre: string } | null;
};

export default function NoticiasListClient({ noticias, colegios }: { noticias: Noticia[]; colegios: Colegio[] }) {
  const router = useRouter();
  const [showCreate, setShowCreate] = useState(false);
  const [editingNoticia, setEditingNoticia] = useState<Noticia | null>(null);
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [errorMsg, setErrorMsg] = useState("");

  const handleDelete = async (id: string) => {
    if (!confirm("¿Eliminar esta noticia permanentemente?")) return;
    setLoadingId(id);
    const res = await deleteNoticia(id);
    if (!res.success) setErrorMsg(res.error || "Error");
    setLoadingId(null);
  };

  const handleToggle = async (id: string, current: boolean) => {
    setLoadingId(id);
    await togglePublicado(id, !current);
    setLoadingId(null);
  };

  return (
    <div className="p-8 max-w-7xl mx-auto">
      <div className="flex justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-800">Noticias y Publicaciones</h1>
          <p className="text-gray-500">Crea y publica artículos por sede o globales para el portal público.</p>
        </div>
        <button onClick={() => setShowCreate(true)}
          className="bg-[#0066ff] hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg flex items-center gap-2 shadow-sm transition-colors">
          <Plus className="w-5 h-5" /> Nueva Noticia
        </button>
      </div>

      {errorMsg && (
        <div className="bg-red-50 text-red-700 p-4 mb-6 rounded-lg font-semibold flex gap-2 items-center">
          <AlertTriangle className="w-5 h-5 shrink-0" /> {errorMsg}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        {noticias.map(noticia => (
          <div key={noticia.id} className={`bg-white rounded-xl border shadow-sm overflow-hidden transition-all hover:shadow-md ${!noticia.publicado ? 'opacity-70 border-dashed border-gray-300' : 'border-gray-100'}`}>
            <div className="p-6">
              <div className="flex items-start justify-between gap-2 mb-3">
                <span className={`text-xs font-bold px-2 py-1 rounded-full ${noticia.publicado ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}`}>
                  {noticia.publicado ? '● Publicado' : '○ Borrador'}
                </span>
                <span className="text-xs text-gray-400">{new Date(noticia.createdAt).toLocaleDateString('es-VE')}</span>
              </div>
              <h3 className="font-bold text-gray-800 text-base mb-2 line-clamp-2">{noticia.titulo}</h3>
              {noticia.resumen && <p className="text-gray-500 text-sm line-clamp-2 mb-3">{noticia.resumen}</p>}
              {noticia.colegio && (
                <span className="inline-block bg-blue-50 text-blue-600 text-xs font-semibold px-2 py-1 rounded-full mb-4">
                  🏫 {noticia.colegio.nombre}
                </span>
              )}
              {!noticia.colegio && (
                <span className="inline-block bg-purple-50 text-purple-600 text-xs font-semibold px-2 py-1 rounded-full mb-4">
                  🌐 Global
                </span>
              )}
            </div>
            <div className="border-t border-gray-50 px-6 py-3 flex justify-end gap-2 bg-gray-50/50">
              <button onClick={() => handleToggle(noticia.id, noticia.publicado)} disabled={loadingId === noticia.id}
                className="text-gray-500 hover:text-blue-600 p-2 rounded hover:bg-blue-50 transition-colors"
                title={noticia.publicado ? "Despublicar" : "Publicar"}>
                {noticia.publicado ? <EyeOff className="w-4 h-4"/> : <Eye className="w-4 h-4"/>}
              </button>
              <button onClick={() => setEditingNoticia(noticia)}
                className="text-blue-500 hover:bg-blue-50 p-2 rounded transition-colors">
                <Edit className="w-4 h-4"/>
              </button>
              <button onClick={() => handleDelete(noticia.id)} disabled={loadingId === noticia.id}
                className="text-red-500 hover:bg-red-50 p-2 rounded transition-colors">
                {loadingId === noticia.id ? <span className="animate-spin block">⟳</span> : <Trash2 className="w-4 h-4"/>}
              </button>
            </div>
          </div>
        ))}

        {noticias.length === 0 && (
          <div className="col-span-3 flex flex-col items-center justify-center py-20 text-gray-400">
            <Newspaper className="w-16 h-16 mb-4 opacity-30" />
            <p className="text-lg font-semibold">Ninguna noticia publicada todavía.</p>
            <p className="text-sm">Crea la primera con el botón superior.</p>
          </div>
        )}
      </div>

      {showCreate && (
        <NoticiaModal title="Nueva Noticia" colegios={colegios} onClose={() => setShowCreate(false)}
          onSubmit={async (fd) => {
            const res = await createNoticia(fd);
            if (res.success) {
              setShowCreate(false);
              router.refresh();
              return { success: true };
            } else {
              return { success: false, error: res.error || "Error al crear" };
            }
          }} />
      )}

      {/* Modal Editar */}
      {editingNoticia && (
        <NoticiaModal title={`Editar: ${editingNoticia.titulo.slice(0,30)}...`}
          colegios={colegios} defaults={editingNoticia}
          onClose={() => setEditingNoticia(null)}
          onSubmit={async (fd) => {
            const res = await updateNoticia(editingNoticia.id, fd);
            if (res.success) {
              setEditingNoticia(null);
              router.refresh();
              return { success: true };
            } else {
              return { success: false, error: res.error || "Error al actualizar" };
            }
          }} />
      )}
    </div>
  );
}

function NoticiaModal({ title, colegios, defaults, onClose, onSubmit }: {
  title: string; colegios: Colegio[]; defaults?: Noticia | null;
  onClose: () => void; onSubmit: (fd: FormData) => Promise<{ success: boolean; error?: string }>;
}) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError("");
    setIsSubmitting(true);
    const fd = new FormData(e.currentTarget);
    const res = await onSubmit(fd);
    if (!res.success) {
      setError(res.error || "Error inesperado.");
    }
    setIsSubmitting(false);
  };
  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl w-full max-w-2xl shadow-2xl p-8 max-h-[92vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-800">{title}</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><XCircle className="w-6 h-6"/></button>
        </div>
        <form onSubmit={handleSubmit} className="space-y-4">
          {error && (
            <div className="bg-red-50 text-red-700 p-3 rounded-lg text-sm font-bold flex gap-2 items-center">
              <AlertTriangle className="w-4 h-4 shrink-0" /> {error}
            </div>
          )}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">Título *</label>
            <input required name="titulo" type="text" defaultValue={defaults?.titulo || ""}
              placeholder="Título de la noticia"
              className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none" />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">Resumen / Descripción breve</label>
            <input name="resumen" type="text" defaultValue={defaults?.resumen || ""}
              placeholder="Un párrafo corto para la vista previa"
              className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none" />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">Contenido completo *</label>
            <textarea required name="contenido" rows={6} defaultValue={defaults?.contenido || ""}
              placeholder="Escribe aquí el cuerpo de la noticia..."
              className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none resize-none" />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">Sede (opcional — vacío = global)</label>
            <select name="colegioId" defaultValue={defaults?.colegioId || ""}
              className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none bg-white">
              <option value="">🌐 Global (todas las sedes)</option>
              {colegios.map(c => <option key={c.id} value={c.id}>{c.nombre}</option>)}
            </select>
          </div>
          <div className="flex items-center gap-3 pt-2">
            <input type="checkbox" name="publicado" id="publicado" defaultChecked={defaults?.publicado ?? false}
              className="w-5 h-5 accent-[#0066ff] rounded" />
            <label htmlFor="publicado" className="text-sm font-semibold text-gray-700 cursor-pointer">
              Publicar inmediatamente en el portal
            </label>
          </div>
          <div className="pt-4 flex justify-end gap-3">
            <button type="button" onClick={onClose} disabled={isSubmitting} className="px-5 py-3 rounded-lg font-semibold text-gray-600 hover:bg-gray-100 transition-colors disabled:opacity-50">Cancelar</button>
            <button type="submit" disabled={isSubmitting} className="bg-[#1e2a47] hover:bg-black text-white px-6 py-3 rounded-lg font-bold transition-colors shadow-md disabled:opacity-50 flex items-center gap-2">
              {isSubmitting ? <span className="animate-spin block">⟳</span> : null}
              {defaults ? "Guardar Cambios" : "Publicar Noticia"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
