"use client";

import { useState, useEffect } from "react";
import { 
  Search, User, ShieldCheck, HardHat, MapPin, Phone, ArrowLeft, 
  MessageCircle, Edit3, Globe, UserCheck, Power, X, Save, Hash, 
  BookOpenCheck, Smartphone, ChevronLeft, ChevronRight, ListOrdered, Menu
} from "lucide-react";
import Link from "next/link";

export default function MilitantsList() {
  const [militants, setMilitants] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [scope, setScope] = useState<"all" | "mine">("all");
  const [isMenuOpen, setIsMenuOpen] = useState(false); // Para controles móviles
  
  // Estados de Paginación
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10); 

  // Estados para Modal y Edición
  const [showEditModal, setShowEditModal] = useState(false);
  const [selectedMilitant, setSelectedMilitant] = useState<any>(null);
  const [saving, setSaving] = useState(false);
  const [colonias, setColonias] = useState<any[]>([]);

  const fetchMilitants = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/militants/list?scope=${scope}`);
      const data = await res.json();
      setMilitants(Array.isArray(data) ? data : []);
      setCurrentPage(1);
    } catch (err) { console.error(err); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchMilitants(); }, [scope]);

  useEffect(() => {
    if (selectedMilitant?.postal_code?.length === 5) {
      fetch(`/api/sections?cp=${selectedMilitant.postal_code}`)
        .then(res => res.json())
        .then(data => setColonias(Array.isArray(data) ? data : []));
    }
  }, [selectedMilitant?.postal_code]);

  const handleToggleStatus = async (id: number) => {
    if (!confirm("¿Inhabilitar a este militante? Dejará de contar en las metas.")) return;
    await fetch("/api/militants/toggle-status", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status: 'inactive' })
    });
    fetchMilitants();
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    const res = await fetch("/api/brigadist/update", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(selectedMilitant)
    });
    if (res.ok) {
      setShowEditModal(false);
      fetchMilitants();
    }
    setSaving(false);
  };

  const filteredData = militants.filter(m => 
    `${m.first_name} ${m.last_name_paternal}`.toLowerCase().includes(searchTerm.toLowerCase()) ||
    m.curp?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const totalPages = Math.ceil(filteredData.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const paginatedData = filteredData.slice(startIndex, startIndex + itemsPerPage);

  const getLevelBadge = (role: string) => {
    const base = "flex items-center gap-1.5 px-3 py-1 rounded-full text-[8px] md:text-[9px] font-black uppercase tracking-tighter border w-fit";
    if (role === 'leader') return <div className={`${base} bg-blue-500/10 text-blue-400 border-blue-500/20`}><ShieldCheck size={10}/> Líder</div>;
    if (role === 'brigadist') return <div className={`${base} bg-purple-500/10 text-purple-400 border-purple-500/20`}><HardHat size={10}/> Brigadista</div>;
    return <div className={`${base} bg-gray-500/10 text-gray-400 border-gray-500/20`}><User size={10}/> Militante</div>;
  };

  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 space-y-6">
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
          <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">Padrón <span className="text-blue-500">Consolidado</span></h1>
          </div>
          
          <button 
            onClick={() => setIsMenuOpen(!isMenuOpen)} 
            className="md:hidden flex items-center justify-center gap-2 w-full py-3 bg-[#0a0a0a] border border-gray-800 rounded-xl text-[10px] font-black uppercase"
          >
            {isMenuOpen ? <X size={16}/> : <Menu size={16}/>} Filtros y Controles
          </button>
        </div>

        <div className={`${isMenuOpen ? 'flex' : 'hidden'} md:flex flex-col lg:flex-row gap-6 justify-between items-start lg:items-center animate-in slide-in-from-top-2 duration-300`}>
          <div className="flex bg-[#0a0a0a] p-1 rounded-2xl border border-gray-900 w-full sm:w-fit shadow-xl">
            <button onClick={() => { setScope("all"); setIsMenuOpen(false); }} className={`flex-1 sm:flex-none flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl text-[10px] font-black uppercase transition-all ${scope === 'all' ? 'bg-blue-600 text-white shadow-lg' : 'text-gray-500 hover:text-white'}`}><Globe size={14} /> Global</button>
            <button onClick={() => { setScope("mine"); setIsMenuOpen(false); }} className={`flex-1 sm:flex-none flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl text-[10px] font-black uppercase transition-all ${scope === 'mine' ? 'bg-blue-600 text-white shadow-lg' : 'text-gray-500 hover:text-white'}`}><UserCheck size={14} /> Mis Capturas</button>
          </div>

          <div className="flex flex-col sm:flex-row gap-4 w-full lg:w-fit">
            <div className="flex items-center justify-between gap-3 bg-[#0a0a0a] border border-gray-800 px-4 py-2.5 rounded-2xl">
                <div className="flex items-center gap-2">
                  <ListOrdered size={14} className="text-gray-500" />
                  <span className="text-[10px] font-black text-gray-500 uppercase">Ver:</span>
                </div>
                <select 
                    value={itemsPerPage} 
                    onChange={(e) => { setItemsPerPage(Number(e.target.value)); setCurrentPage(1); }}
                    className="bg-transparent text-[10px] font-black uppercase outline-none cursor-pointer text-blue-500"
                >
                    <option value={10}>10</option>
                    <option value={25}>25</option>
                    <option value={50}>50</option>
                </select>
            </div>

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

      {/* --- LISTADO ADAPTADO --- */}
      <div className="space-y-4 mb-8">
        {loading ? (
          <div className="p-20 text-center animate-pulse text-[10px] font-black uppercase text-gray-600 tracking-[0.3em]">Sincronizando registros territoriales...</div>
        ) : paginatedData.length === 0 ? (
          <div className="p-20 text-center border-2 border-dashed border-gray-900 rounded-[2rem] md:rounded-[3rem] text-gray-700 text-[10px] font-black uppercase italic">Sin registros coincidentes</div>
        ) : paginatedData.map((m) => (
          <div key={m.id} className="bg-[#0a0a0a] border border-gray-900 rounded-3xl md:rounded-[2rem] p-4 md:p-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4 group hover:border-blue-500/30 transition-all shadow-xl">
            <div className="flex items-center gap-4 md:gap-6">
              <div className="relative shrink-0">
                <div className="w-12 h-12 md:w-14 md:h-14 bg-gray-900 rounded-2xl flex items-center justify-center border border-gray-800 group-hover:border-blue-500/50 transition-colors">
                  <User size={20} className="md:w-6 md:h-6 text-gray-600 group-hover:text-blue-500 transition-colors" />
                </div>
                {m.created_by === m.current_user_id && (
                   <div className="absolute -top-1 -right-1 bg-blue-600 text-[7px] font-black px-1.5 py-0.5 rounded-md animate-bounce shadow-lg shadow-blue-600/20 uppercase">Mío</div>
                )}
              </div>

              <div className="space-y-1 min-w-0">
                <div className="flex flex-wrap items-center gap-2">
                  <h3 className="text-xs md:text-sm font-black uppercase italic tracking-tight truncate max-w-[150px] md:max-w-none">{m.first_name} {m.last_name_paternal}</h3>
                  {getLevelBadge(m.user_role)}
                </div>
                <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-gray-500 text-[9px] md:text-[10px] font-bold uppercase tracking-widest">
                  <span className="flex items-center gap-1"><MapPin size={10} className="text-blue-500"/> {m.neighborhood}</span>
                  <span className="flex items-center gap-1">SECC. {m.section_number}</span>
                  <span className="flex items-center gap-1"><Smartphone size={10} className="text-gray-700"/> {m.phone || 'S/N'}</span>
                </div>
              </div>
            </div>

            <div className="flex items-center justify-between sm:justify-end gap-2 border-t border-gray-900 pt-3 sm:border-t-0 sm:pt-0">
              <div className="flex gap-2">
                <a href={`tel:${m.phone}`} className="p-3 bg-gray-900 text-gray-400 hover:text-blue-500 hover:bg-blue-500/10 rounded-xl transition-all"><Phone size={16}/></a>
                <a href={`https://wa.me/52${m.phone}`} target="_blank" className="p-3 bg-gray-900 text-gray-400 hover:text-emerald-500 hover:bg-emerald-500/10 rounded-xl transition-all"><MessageCircle size={16}/></a>
              </div>
              <div className="flex gap-2">
                <button onClick={() => { setSelectedMilitant(m); setShowEditModal(true); }} className="p-3 bg-gray-900 text-gray-400 hover:text-yellow-500 hover:bg-yellow-500/10 rounded-xl transition-all"><Edit3 size={16}/></button>
                <button onClick={() => handleToggleStatus(m.id)} className="p-3 bg-gray-900 text-red-500/50 hover:text-red-500 hover:bg-red-500/10 rounded-xl transition-all"><Power size={16}/></button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* --- PAGINACIÓN ADAPTADA --- */}
      {!loading && filteredData.length > 0 && (
        <div className="flex flex-col sm:flex-row justify-between items-center bg-[#0a0a0a] border border-gray-900 p-5 md:p-6 rounded-3xl md:rounded-[2.5rem] shadow-2xl gap-4">
            <p className="text-[9px] md:text-[10px] font-black text-gray-600 uppercase tracking-widest italic text-center sm:text-left">
                Pág. <span className="text-blue-500">{currentPage}</span> de {totalPages} — <span className="text-white">{filteredData.length}</span> Totales
            </p>
            <div className="flex gap-3 w-full sm:w-fit">
                <button 
                    disabled={currentPage === 1}
                    onClick={() => setCurrentPage(prev => prev - 1)}
                    className="flex-1 sm:flex-none flex items-center justify-center gap-2 px-6 py-3 bg-gray-900 border border-gray-800 rounded-xl text-[10px] font-black uppercase hover:border-blue-500 disabled:opacity-20 transition-all active:scale-95"
                >
                    <ChevronLeft size={14} /> Ant.
                </button>
                <button 
                    disabled={currentPage >= totalPages}
                    onClick={() => setCurrentPage(prev => prev + 1)}
                    className="flex-1 sm:flex-none flex items-center justify-center gap-2 px-6 py-3 bg-gray-900 border border-gray-800 rounded-xl text-[10px] font-black uppercase hover:border-blue-500 disabled:opacity-20 transition-all active:scale-95"
                >
                    Sig. <ChevronRight size={14} />
                </button>
            </div>
        </div>
      )}

      {/* --- MODAL DE EDICIÓN ADAPTADO --- */}
      {showEditModal && selectedMilitant && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/95 backdrop-blur-md">
          <div className="bg-[#050505] border border-gray-800 w-full max-w-2xl rounded-3xl md:rounded-[3rem] p-5 md:p-8 shadow-2xl relative animate-in zoom-in duration-200 flex flex-col max-h-[90vh]">
            <div className="absolute top-0 right-0 p-4 md:p-8">
               <button onClick={() => setShowEditModal(false)} className="text-gray-500 hover:text-white p-2 rounded-full hover:bg-white/5"><X size={24}/></button>
            </div>

            <h2 className="text-xl md:text-2xl font-black uppercase italic mb-6 md:mb-8 flex items-center gap-3 tracking-tighter shrink-0">
              <Edit3 className="text-blue-500 w-6 h-6" /> Corregir <span className="text-blue-500">Militante</span>
            </h2>

            <form onSubmit={handleUpdate} className="space-y-6 overflow-y-auto pr-2 md:pr-4 custom-scrollbar pb-2">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6">
                <div className="space-y-4 bg-[#0a0a0a] p-5 rounded-2xl md:rounded-3xl border border-gray-900 shadow-inner">
                  <div className="flex items-center gap-2 mb-1">
                    <User size={12} className="text-blue-500"/>
                    <p className="text-[9px] font-black text-gray-500 uppercase tracking-widest">Identidad</p>
                  </div>
                  <div className="space-y-1">
                    <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-700 ml-1 italic">Nombre(s)</label>
                    <input value={selectedMilitant.first_name} onChange={e => setSelectedMilitant({...selectedMilitant, first_name: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs uppercase font-bold focus:border-blue-500 outline-none" />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div className="space-y-1">
                      <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-700 ml-1 italic">Paterno</label>
                      <input value={selectedMilitant.last_name_paternal} onChange={e => setSelectedMilitant({...selectedMilitant, last_name_paternal: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs uppercase font-bold focus:border-blue-500 outline-none" />
                    </div>
                    <div className="space-y-1">
                      <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-700 ml-1 italic">Materno</label>
                      <input value={selectedMilitant.last_name_maternal} onChange={e => setSelectedMilitant({...selectedMilitant, last_name_maternal: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs uppercase font-bold focus:border-blue-500 outline-none" />
                    </div>
                  </div>
                </div>

                <div className="space-y-4 bg-[#0a0a0a] p-5 rounded-2xl md:rounded-3xl border border-gray-900 shadow-inner">
                  <div className="flex items-center gap-2 mb-1">
                    <BookOpenCheck size={12} className="text-purple-500"/>
                    <p className="text-[9px] font-black text-gray-500 uppercase tracking-widest">Documentación</p>
                  </div>
                  <div className="space-y-1">
                    <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-700 ml-1 italic">CURP</label>
                    <input value={selectedMilitant.curp} onChange={e => setSelectedMilitant({...selectedMilitant, curp: e.target.value.toUpperCase()})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs font-mono font-bold focus:border-purple-500 outline-none text-purple-400" maxLength={18} />
                  </div>
                  <div className="space-y-1">
                    <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-700 ml-1 italic">Clave Elector</label>
                    <input value={selectedMilitant.elector_key} onChange={e => setSelectedMilitant({...selectedMilitant, elector_key: e.target.value.toUpperCase()})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs font-mono font-bold focus:border-purple-500 outline-none" maxLength={18} />
                  </div>
                </div>

                <div className="md:col-span-2 grid grid-cols-1 md:grid-cols-3 gap-4 bg-[#0a0a0a] p-5 rounded-2xl md:rounded-3xl border border-gray-900 shadow-inner">
                   <div className="space-y-1">
                      <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-600 ml-1 italic">Teléfono</label>
                      <input value={selectedMilitant.phone} onChange={e => setSelectedMilitant({...selectedMilitant, phone: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs font-bold focus:border-emerald-500 outline-none" />
                   </div>
                   <div className="space-y-1">
                      <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-600 ml-1">C.P.</label>
                      <input value={selectedMilitant.postal_code} onChange={e => setSelectedMilitant({...selectedMilitant, postal_code: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs font-bold focus:border-blue-500 outline-none" />
                   </div>
                   <div className="space-y-1">
                      <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-600 ml-1">Sección</label>
                      <input value={selectedMilitant.section_number} onChange={e => setSelectedMilitant({...selectedMilitant, section_number: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs font-bold focus:border-blue-500 outline-none" />
                   </div>
                   <div className="md:col-span-3 space-y-1">
                      <label className="text-[7px] md:text-[8px] font-black uppercase text-gray-600 ml-1 italic">Colonia</label>
                      <select value={selectedMilitant.neighborhood} onChange={e => setSelectedMilitant({...selectedMilitant, neighborhood: e.target.value})} className="w-full bg-[#050505] border border-gray-800 rounded-xl p-2.5 text-xs font-black uppercase outline-none focus:border-blue-500">
                        <option value="">Selecciona Colonia...</option>
                        {colonias.map((c, i) => <option key={i} value={c.colonia}>{c.colonia}</option>)}
                      </select>
                   </div>
                </div>
              </div>

              <button type="submit" disabled={saving} className="w-full bg-blue-600 hover:bg-blue-500 text-white font-black uppercase text-[10px] tracking-[0.2em] py-4 md:py-5 rounded-2xl flex items-center justify-center gap-3 shadow-2xl transition-all active:scale-95 italic shrink-0">
                {saving ? "Sincronizando..." : <><Save size={18}/> Actualizar Expediente</>}
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}