"use client";

import { useState, useEffect } from "react";
import { 
  Search, MoreVertical, User, ShieldCheck, HardHat, 
  MapPin, Phone, ArrowLeft, MessageCircle, Edit3,
  UserCheck, X, Send, Eye, BookOpenCheck, Smartphone
} from "lucide-react";
import Link from "next/link";

interface Militante {
  id: number;
  first_name: string;
  last_name_paternal: string;
  last_name_maternal?: string;
  birth_date?: string;
  sex?: string;
  curp: string;
  elector_key?: string;
  phone?: string;
  postal_code?: string;
  section_number?: string | number;
  neighborhood?: string;
  street?: string;
  ext_number?: string;
  int_number?: string;
  reference_text?: string;
  notes?: string;
  status?: string;
  user_role?: string; // Rol proveniente del Join con la tabla users
}

export default function LeaderMilitantsList() {
  const [militants, setMilitants] = useState<Militante[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [coloniasEdit, setColoniasEdit] = useState<any[]>([]);
  
  const [showEditModal, setShowEditModal] = useState(false);
  const [showReviewModal, setShowReviewModal] = useState(false);
  const [selectedMilitant, setSelectedMilitant] = useState<Militante | null>(null);
  const [reviewText, setReviewText] = useState("");
  const [openMenuId, setOpenMenuId] = useState<number | null>(null);

  const inputClass = "w-full rounded-2xl border border-gray-800 bg-[#0d0d0d] p-3 text-[11px] text-white placeholder-gray-600 focus:border-blue-500 outline-none transition-all";

  const fetchMilitants = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/leader/militants`);
      const data = await res.json();
      setMilitants(Array.isArray(data) ? data : []);
    } catch (err) { console.error("Error al cargar:", err); }
    finally { setLoading(false); }
  };

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

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

  const handleEditChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setSelectedMilitant((prev: any) => ({ ...prev, [name]: value }));
  };

  const handleUpdate = async () => {
    try {
      const res = await fetch(`/api/brigadist/update`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(selectedMilitant),
      });
      if (res.ok) {
        setShowEditModal(false);
        fetchMilitants();
      }
    } catch (error) { console.error(error); }
  };

  const handleSendToReview = async () => {
    if (!selectedMilitant) return;
    try {
      const res = await fetch("/api/brigadist/review", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: selectedMilitant.id, notes: reviewText, status: "review" }),
      });
      if (res.ok) {
        setReviewText("");
        setShowReviewModal(false);
        fetchMilitants();
      }
    } catch (error) { console.error(error); }
  };

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

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

  return (
    <div className="min-h-screen bg-[#050505] text-white p-10 font-sans">
      <header className="mb-10 flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div className="space-y-4">
          <div className="flex items-center gap-2 text-blue-500">
            <Link href="/leader/dashboard" className="hover:bg-blue-500/10 p-1 rounded-lg transition-all">
              <ArrowLeft size={18} />
            </Link>
            <span className="text-[10px] font-black uppercase tracking-widest text-gray-500">Regresar al Panel</span>
          </div>
          <h1 className="text-4xl font-black uppercase tracking-tighter italic">MIS MILITANTES</h1>
        </div>

        <div className="relative group">
          <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 por Nombre o CURP..." 
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="bg-[#0a0a0a] border border-gray-800 rounded-2xl py-3 pl-12 pr-6 text-sm focus:border-blue-500 outline-none w-full md:w-80 transition-all shadow-2xl"
          />
        </div>
      </header>

      {/* TABLA */}
      <div className="bg-[#0a0a0a] border border-gray-900 rounded-[32px] overflow-visible shadow-2xl mb-8">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-[#0d0d0d] text-[10px] font-black uppercase tracking-[0.2em] text-gray-500 border-b border-gray-900">
                <th className="p-6">Militante</th>
                <th className="p-6">Nivel</th>
                <th className="p-6">Estatus</th>
                <th className="p-6">Territorio</th>
                <th className="p-6 text-right">Acciones</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-900">
              {loading ? (
                <tr><td colSpan={5} className="p-20 text-center animate-pulse italic text-gray-600 uppercase text-[10px] tracking-widest">Sincronizando Estructura...</td></tr>
              ) : filteredData.map((m) => (
                <tr key={m.id} className="hover:bg-blue-600/[0.02] transition-colors group">
                  <td className="p-6">
                    <div className="flex flex-col">
                      <span className="font-bold text-white text-[14px] uppercase">{m.first_name} {m.last_name_paternal}</span>
                      <span className="text-[10px] font-mono text-gray-500 mt-0.5">{m.curp}</span>
                    </div>
                  </td>
                  <td className="p-6">
                    {getLevelBadge(m.user_role || 'militant')}
                  </td>
                  <td className="p-6">
                    <span className={`px-3 py-1 rounded-full text-[8px] font-black uppercase border ${m.status === 'review' ? 'bg-yellow-500/10 text-yellow-500 border-yellow-500/20' : 'bg-blue-500/10 text-blue-500 border-blue-500/20'}`}>
                      {m.status === 'review' ? 'Revisión' : 'Activo'}
                    </span>
                  </td>
                  <td className="p-6 text-xs text-gray-400">
                    <div className="flex items-center gap-1.5"><MapPin size={12} className="text-blue-500"/> {m.neighborhood}</div>
                  </td>
                  <td className="p-6 text-right relative">
                    <button 
                      onClick={() => setOpenMenuId(openMenuId === m.id ? null : m.id)} 
                      className="p-3 text-gray-600 hover:text-white transition-colors relative z-[101]"
                    >
                      <MoreVertical size={20}/>
                    </button>

                    {openMenuId === m.id && (
                      <>
                        <div className="fixed inset-0 z-[100] cursor-default" onClick={() => setOpenMenuId(null)} />
                        <div className="absolute right-12 top-16 z-[101] w-52 bg-[#0d0d0d] border border-gray-800 rounded-2xl shadow-2xl p-2 animate-in fade-in zoom-in duration-150">
                          <button onClick={() => { setSelectedMilitant(m); setShowEditModal(true); setOpenMenuId(null); }} className="w-full flex items-center gap-3 p-3 text-[9px] font-black uppercase hover:bg-blue-600 rounded-xl transition-all">
                            <Edit3 size={14}/> Editar Datos
                          </button>
                          <button onClick={() => { setSelectedMilitant(m); setShowReviewModal(true); setOpenMenuId(null); }} className="w-full flex items-center gap-3 p-3 text-[9px] font-black uppercase hover:bg-yellow-600 rounded-xl transition-all">
                            <Eye size={14}/> Enviar a Revisión
                          </button>
                          <div className="h-[1px] bg-gray-800 my-1 mx-2"></div>
                          <a href={`tel:${m.phone}`} className="w-full flex items-center gap-3 p-3 text-[9px] font-black uppercase hover:bg-green-600 rounded-xl transition-all">
                            <Phone size={14}/> Llamar
                          </a>
                          <a href={`https://wa.me/52${m.phone}`} target="_blank" className="w-full flex items-center gap-3 p-3 text-[9px] font-black uppercase hover:bg-emerald-600 rounded-xl transition-all">
                            <MessageCircle size={14}/> WhatsApp
                          </a>
                        </div>
                      </>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* MODAL EDITAR COMPLETO */}
      {showEditModal && selectedMilitant && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/95 backdrop-blur-md overflow-y-auto">
          <div className="bg-[#050505] border border-gray-900 w-full max-w-lg rounded-[2.5rem] p-8 shadow-2xl my-auto relative">
            <header className="flex justify-between items-center mb-8">
              <h3 className="text-2xl font-black italic uppercase tracking-tighter">Ficha de <span className="text-blue-500">Militante</span></h3>
              <button onClick={() => setShowEditModal(false)} className="bg-red-950/20 text-red-500 p-3 rounded-full border border-red-900/20 hover:bg-red-500 hover:text-white transition-all"><X size={20}/></button>
            </header>

            <div className="space-y-6 max-h-[65vh] overflow-y-auto pr-3 custom-scrollbar pb-6">
               <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 space-y-4">
                  <div className="flex items-center gap-2 text-blue-500 mb-2"><User size={18}/><span className="text-[10px] font-black uppercase text-white">Identidad Personal</span></div>
                  <input name="first_name" value={selectedMilitant.first_name || ""} onChange={handleEditChange} className={inputClass} placeholder="Nombre(s)" />
                  <div className="grid grid-cols-2 gap-4">
                    <input name="last_name_paternal" value={selectedMilitant.last_name_paternal || ""} onChange={handleEditChange} className={inputClass} placeholder="Paterno" />
                    <input name="last_name_maternal" value={selectedMilitant.last_name_maternal || ""} onChange={handleEditChange} className={inputClass} placeholder="Materno" />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <input type="date" name="birth_date" value={selectedMilitant.birth_date?.split("T")[0] || ""} onChange={handleEditChange} className={inputClass} />
                    <select name="sex" value={selectedMilitant.sex || ""} onChange={handleEditChange} className={inputClass}>
                      <option value="M">HOMBRE</option>
                      <option value="F">MUJER</option>
                    </select>
                  </div>
               </div>

               <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 space-y-4">
                  <div className="flex items-center gap-2 text-blue-500 mb-2"><BookOpenCheck size={18}/><span className="text-[10px] font-black uppercase text-white">Documentación</span></div>
                  <input name="curp" value={selectedMilitant.curp || ""} onChange={handleEditChange} className={`${inputClass} font-mono text-blue-400`} placeholder="CURP" />
                  <input name="elector_key" value={selectedMilitant.elector_key || ""} onChange={handleEditChange} className={inputClass} placeholder="Clave Elector" />
                  <input name="phone" value={selectedMilitant.phone || ""} onChange={handleEditChange} className={inputClass} placeholder="Teléfono" />
               </div>
               
               <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 space-y-4">
                  <div className="flex items-center gap-2 text-purple-500 mb-2"><MapPin size={18}/><span className="text-[10px] font-black uppercase text-white">Territorio</span></div>
                  <div className="grid grid-cols-2 gap-4">
                    <input name="postal_code" value={selectedMilitant.postal_code || ""} onChange={handleEditChange} className={inputClass} placeholder="C.P." />
                    <input name="section_number" value={selectedMilitant.section_number || ""} onChange={handleEditChange} className={inputClass} placeholder="Sección" />
                  </div>
                  <select name="neighborhood" value={selectedMilitant.neighborhood || ""} onChange={handleEditChange} className={inputClass}>
                    <option value="">Seleccionar Colonia...</option>
                    {coloniasEdit.map((c, i) => (<option key={i} value={c.colonia}>{c.colonia}</option>))}
                  </select>
                  <input name="street" value={selectedMilitant.street || ""} onChange={handleEditChange} className={inputClass} placeholder="Calle" />
                  <div className="grid grid-cols-2 gap-4">
                    <input name="ext_number" value={selectedMilitant.ext_number || ""} onChange={handleEditChange} className={inputClass} placeholder="Exterior" />
                    <input name="int_number" value={selectedMilitant.int_number || ""} onChange={handleEditChange} className={inputClass} placeholder="Interior" />
                  </div>
                  <textarea name="reference_text" value={selectedMilitant.reference_text || ""} onChange={handleEditChange} className={`${inputClass} h-20 resize-none`} placeholder="Referencia domicilio..." />
                  <textarea name="notes" value={selectedMilitant.notes || ""} onChange={handleEditChange} className={`${inputClass} h-20 resize-none`} placeholder="Notas..." />
               </div>
            </div>
            <button onClick={handleUpdate} className="w-full mt-6 bg-white text-black h-16 rounded-2xl font-black uppercase text-[11px] italic tracking-[0.2em] shadow-2xl active:scale-95 transition-all">Sincronizar cambios</button>
          </div>
        </div>
      )}

      {/* MODAL REVISIÓN */}
      {showReviewModal && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-6 bg-black/90 backdrop-blur-md">
          <div className="bg-[#0a0a0a] border border-gray-900 w-full max-w-sm rounded-[2.5rem] p-8 shadow-2xl">
            <div className="flex justify-between items-center mb-6 text-yellow-500">
              <h3 className="text-lg font-black uppercase italic tracking-tighter">Orden de <span className="text-white">Revisión</span></h3>
              <button onClick={() => setShowReviewModal(false)} className="text-gray-500 hover:text-white"><X size={20}/></button>
            </div>
            <textarea value={reviewText} onChange={(e) => setReviewText(e.target.value)} placeholder="Motivo..." className="w-full bg-[#050505] border border-gray-800 rounded-2xl p-5 text-[11px] text-white h-44 outline-none focus:border-yellow-600 mb-6 resize-none" />
            <button onClick={handleSendToReview} className="w-full bg-yellow-600 text-black h-14 rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-lg shadow-yellow-600/20 active:scale-95 transition-all"><Send size={16} className="inline mr-2" /> Enviar a Estatus Review</button>
          </div>
        </div>
      )}
    </div>
  );
}