"use client";

import { useState, useEffect } from "react";
import { 
  ArrowLeft, CheckCircle, XCircle, Edit3, MessageSquare, 
  ShieldCheck, HardHat, Search, X, Save, User, MapPin, Hash, Phone, AlertCircle, Menu
} from "lucide-react";
import Link from "next/link";

export default function AdminReviewsPage() {
  const [reviews, setReviews] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  
  // Estados para el Modal de Edición
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editingMilitant, setEditingMilitant] = useState<any>(null);
  const [saving, setSaving] = useState(false);

  const fetchReviews = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/reviews");
      const data = await res.json();
      setReviews(Array.isArray(data) ? data : []);
    } catch (err) { 
      console.error("Error al cargar revisiones:", err); 
    } finally { 
      setLoading(false); 
    }
  };

  useEffect(() => { fetchReviews(); }, []);

  const handleAction = async (id: number, newStatus: string) => {
    const confirmMsg = newStatus === 'active' 
      ? "Al aprobar, el registro será oficial y se habilitará el acceso si es usuario. ¿Continuar?" 
      : "Al rechazar, el registro se dará de baja y se bloqueará el acceso. ¿Continuar?";

    if (!confirm(confirmMsg)) return;

    try {
      const res = await fetch("/api/admin/process-review", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, status: newStatus })
      });

      if (res.ok) {
        const result = await res.json();
        alert(result.message);
        fetchReviews();
      } else {
        alert("Error al procesar la solicitud en el servidor.");
      }
    } catch (error) { 
      console.error("Error en la acción:", error); 
    }
  };

  const openEditModal = (militant: any) => {
    setEditingMilitant({ ...militant });
    setIsEditModalOpen(true);
  };

  const saveChanges = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await fetch("/api/brigadist/update", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editingMilitant)
      });
      
      if (res.ok) {
        setIsEditModalOpen(false);
        fetchReviews();
        alert("Datos del militante actualizados.");
      } else {
        alert("Error al actualizar datos.");
      }
    } catch (error) {
      console.error("Update Error:", error);
    } finally {
      setSaving(false);
    }
  };

  const getRoleBadge = (role: string) => {
    const isLeader = role === 'leader';
    return (
      <div className={`flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[8px] font-black uppercase border ${isLeader ? 'bg-blue-500/10 text-blue-400 border-blue-500/20' : 'bg-purple-500/10 text-purple-400 border-purple-500/20'}`}>
        {isLeader ? <ShieldCheck size={10}/> : <HardHat size={10}/>}
        {isLeader ? 'Líder' : 'Brigadista'}
      </div>
    );
  };

  const filtered = reviews.filter(r => 
    `${r.first_name} ${r.last_name_paternal} ${r.curp}`.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="min-h-screen bg-[#050505] text-white p-4 md:p-10 font-sans overflow-x-hidden">
      
      {/* Header Adaptado */}
      <header className="mb-8 md:mb-10 flex flex-col lg:flex-row lg:items-end justify-between gap-6">
        <div className="space-y-4">
          <Link href="/admin/dashboard" className="flex items-center gap-2 text-blue-500 text-[10px] font-black uppercase tracking-widest hover:opacity-70 transition-all">
            <ArrowLeft size={16} /> Volver al Dashboard
          </Link>
          <h1 className="text-3xl md:text-4xl font-black uppercase tracking-tighter italic leading-tight">Panel de <span className="text-yellow-500">Revisiones</span></h1>
        </div>

        <div className="relative w-full lg:w-80">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-600" size={18} />
          <input 
            type="text" 
            placeholder="BUSCAR MILITANTE..." 
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="bg-[#0a0a0a] border border-gray-800 rounded-2xl py-3 pl-12 pr-6 text-[10px] font-black uppercase focus:border-yellow-500 outline-none w-full transition-all"
          />
        </div>
      </header>

      {/* Vista de Tabla / Cards Adaptada */}
      <div className="bg-[#0a0a0a] border border-gray-900 rounded-3xl md:rounded-[2.5rem] overflow-hidden shadow-2xl">
        {/* Desktop View */}
        <div className="hidden md:block overflow-x-auto">
          <table className="w-full text-left border-separate border-spacing-0">
            <thead>
              <tr className="bg-[#0d0d0d] text-[10px] font-black uppercase tracking-widest text-gray-500 border-b border-gray-900">
                <th className="p-6 italic font-bold">Militante en Duda</th>
                <th className="p-6 italic font-bold">Remitente</th>
                <th className="p-6 italic font-bold">Observaciones</th>
                <th className="p-6 text-right italic font-bold">Gestión</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-900">
              {loading ? (
                <tr><td colSpan={4} className="p-20 text-center animate-pulse italic text-gray-600 text-[10px] font-black uppercase tracking-[0.2em]">Sincronizando expedientes...</td></tr>
              ) : filtered.length === 0 ? (
                <tr><td colSpan={4} className="p-20 text-center text-gray-700 italic text-[10px] font-black uppercase tracking-[0.2em]">No hay casos en revisión</td></tr>
              ) : filtered.map((r) => (
                <tr key={r.id} className="hover:bg-yellow-500/[0.01] transition-colors group">
                  <td className="p-6">
                    <div className="flex flex-col">
                      <span className="font-bold text-white text-sm uppercase italic">{r.first_name} {r.last_name_paternal}</span>
                      <span className="text-[9px] font-mono text-gray-600 mt-1">{r.curp}</span>
                    </div>
                  </td>
                  <td className="p-6">
                    <div className="flex flex-col gap-1.5">
                      <span className="text-[11px] font-bold text-gray-300 uppercase">{r.sender_name}</span>
                      {getRoleBadge(r.sender_role)}
                    </div>
                  </td>
                  <td className="p-6">
                    <div className="flex items-start gap-2 max-w-xs bg-[#0d0d0d] p-3 rounded-xl border border-gray-800">
                      <AlertCircle size={14} className="text-yellow-600 mt-0.5 shrink-0" />
                      <p className="text-[10px] text-gray-400 italic leading-relaxed">"{r.notes || 'Revisión técnica de datos'}"</p>
                    </div>
                  </td>
                  <td className="p-6 text-right">
                    <div className="flex justify-end gap-2">
                      <button onClick={() => openEditModal(r)} className="p-3 bg-blue-500/10 text-blue-500 rounded-xl hover:bg-blue-500 hover:text-white transition-all">
                        <Edit3 size={16} />
                      </button>
                      <button onClick={() => handleAction(r.id, 'inactive')} className="p-3 bg-red-500/10 text-red-500 rounded-xl hover:bg-red-500 hover:text-white transition-all">
                        <XCircle size={16} />
                      </button>
                      <button onClick={() => handleAction(r.id, 'active')} className="p-3 bg-emerald-500/10 text-emerald-500 rounded-xl hover:bg-emerald-500 hover:text-white transition-all">
                        <CheckCircle size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Mobile View (Cards) */}
        <div className="md:hidden divide-y divide-gray-900">
          {loading ? (
            <div className="p-10 text-center animate-pulse italic text-gray-600 text-[10px] font-black uppercase tracking-[0.2em]">Sincronizando expedientes...</div>
          ) : filtered.length === 0 ? (
            <div className="p-10 text-center text-gray-700 italic text-[10px] font-black uppercase tracking-[0.2em]">No hay casos en revisión</div>
          ) : filtered.map((r) => (
            <div key={r.id} className="p-5 space-y-4">
              <div className="flex justify-between items-start">
                <div className="flex flex-col">
                  <span className="font-bold text-white text-sm uppercase italic leading-tight">{r.first_name} {r.last_name_paternal}</span>
                  <span className="text-[9px] font-mono text-gray-600 mt-1">{r.curp}</span>
                </div>
                {getRoleBadge(r.sender_role)}
              </div>
              
              <div className="bg-[#0d0d0d] p-3 rounded-xl border border-gray-800 flex gap-2">
                <AlertCircle size={14} className="text-yellow-600 shrink-0 mt-0.5" />
                <p className="text-[10px] text-gray-400 italic leading-relaxed">"{r.notes || 'Revisión técnica de datos'}"</p>
              </div>

              <div className="flex gap-2">
                <button onClick={() => openEditModal(r)} className="flex-1 flex justify-center items-center py-3 bg-blue-500/10 text-blue-500 rounded-xl border border-blue-500/20 active:bg-blue-500 active:text-white transition-all">
                  <Edit3 size={16} />
                </button>
                <button onClick={() => handleAction(r.id, 'inactive')} className="flex-1 flex justify-center items-center py-3 bg-red-500/10 text-red-500 rounded-xl border border-red-500/20 active:bg-red-500 active:text-white transition-all">
                  <XCircle size={16} />
                </button>
                <button onClick={() => handleAction(r.id, 'active')} className="flex-1 flex justify-center items-center py-3 bg-emerald-500/10 text-emerald-500 rounded-xl border border-emerald-500/20 active:bg-emerald-500 active:text-white transition-all">
                  <CheckCircle size={16} />
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Modal de Edición Maestro Adaptado */}
      {isEditModalOpen && (
        <div className="fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/95 backdrop-blur-md">
          <div className="bg-[#0a0a0a] border border-gray-800 w-full max-w-2xl rounded-3xl md:rounded-[2.5rem] overflow-hidden shadow-2xl flex flex-col max-h-[90vh]">
            <div className="p-6 md:p-8 border-b border-gray-900 flex justify-between items-center bg-[#0d0d0d] shrink-0">
              <h2 className="text-xl md:text-2xl font-black italic uppercase tracking-tighter leading-tight">Corregir Militante</h2>
              <button onClick={() => setIsEditModalOpen(false)} className="p-2 text-gray-500 hover:text-white transition-all"><X size={24} /></button>
            </div>

            <form onSubmit={saveChanges} className="p-6 md:p-8 space-y-6 overflow-y-auto custom-scrollbar">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-gray-500 uppercase px-1 italic">Nombre(s)</label>
                  <div className="relative">
                    <User className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-700" size={16} />
                    <input type="text" required value={editingMilitant.first_name} onChange={(e) => setEditingMilitant({...editingMilitant, first_name: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl py-3 pl-12 pr-4 text-xs font-bold uppercase focus:border-blue-500 outline-none transition-all"/>
                  </div>
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-gray-500 uppercase px-1 italic">Apellido Paterno</label>
                  <input type="text" required value={editingMilitant.last_name_paternal} onChange={(e) => setEditingMilitant({...editingMilitant, last_name_paternal: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl py-3 px-4 text-xs font-bold uppercase focus:border-blue-500 outline-none transition-all"/>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-gray-500 uppercase px-1 italic">CURP Identificador</label>
                  <div className="relative">
                    <Hash className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-700" size={16} />
                    <input type="text" required maxLength={18} value={editingMilitant.curp} onChange={(e) => setEditingMilitant({...editingMilitant, curp: e.target.value.toUpperCase()})} className="w-full bg-[#050505] border border-gray-800 rounded-xl py-3 pl-12 pr-4 text-xs font-mono font-bold focus:border-blue-500 outline-none transition-all"/>
                  </div>
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-gray-500 uppercase px-1 italic">Teléfono</label>
                  <div className="relative">
                    <Phone className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-700" size={16} />
                    <input type="tel" value={editingMilitant.phone || ""} onChange={(e) => setEditingMilitant({...editingMilitant, phone: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl py-3 pl-12 pr-4 text-xs font-bold focus:border-blue-500 outline-none transition-all"/>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t border-gray-900">
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-gray-500 uppercase px-1 italic">Sección</label>
                  <input type="number" value={editingMilitant.section_number} onChange={(e) => setEditingMilitant({...editingMilitant, section_number: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl py-3 px-4 text-xs font-bold focus:border-blue-500 outline-none transition-all"/>
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-black text-gray-500 uppercase px-1 italic">Colonia</label>
                  <div className="relative">
                    <MapPin className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-700" size={16} />
                    <input type="text" value={editingMilitant.neighborhood} onChange={(e) => setEditingMilitant({...editingMilitant, neighborhood: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl py-3 pl-12 pr-4 text-xs font-bold uppercase focus:border-blue-500 outline-none transition-all"/>
                  </div>
                </div>
              </div>

              <div className="flex flex-col sm:flex-row gap-3 pt-6 shrink-0">
                <button type="button" onClick={() => setIsEditModalOpen(false)} className="order-2 sm:order-1 flex-1 py-4 rounded-2xl border border-gray-800 text-[10px] font-black uppercase active:bg-gray-900 transition-all">Cancelar</button>
                <button type="submit" disabled={saving} className="order-1 sm:order-2 flex-1 py-4 rounded-2xl bg-blue-600 text-white text-[10px] font-black uppercase active:scale-95 transition-all flex items-center justify-center gap-2 shadow-xl shadow-blue-900/20">
                  {saving ? "Procesando..." : <><Save size={16} /> Guardar Cambios</>}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}