"use client";

import { useState, useEffect } from "react";
import { 
  AlertCircle, ArrowLeft, MapPin, User, 
  MessageSquare, ChevronRight, CheckCircle, Search,
  UserMinus, UserCheck, X, Edit3, BookOpenCheck, Smartphone 
} from "lucide-react";
import Link from "next/link";

interface ReviewItem {
  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;
  brigadist_name: string;
  updated_at: string;
}

export default function LeaderReviewsPage() {
  const [reviews, setReviews] = useState<ReviewItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [coloniasEdit, setColoniasEdit] = useState<any[]>([]);
  
  // Modales
  const [showEditModal, setShowEditModal] = useState(false);
  const [showStatusModal, setShowStatusModal] = useState(false);
  const [selectedMilitant, setSelectedMilitant] = useState<ReviewItem | null>(null);
  const [pendingStatus, setPendingStatus] = useState<"active" | "inactive" | 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-yellow-500 outline-none transition-all";

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

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

  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);
        fetchReviews();
      }
    } catch (error) { console.error(error); }
  };

  const confirmStatusChange = async () => {
    if (!selectedMilitant || !pendingStatus) return;
    try {
      const res = await fetch("/api/brigadist/review", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
          id: selectedMilitant.id, 
          status: pendingStatus,
          notes: pendingStatus === 'active' ? "Validado por Líder" : "Baja por Líder"
        }),
      });
      if (res.ok) {
        setShowStatusModal(false);
        setPendingStatus(null);
        fetchReviews();
      }
    } catch (error) { console.error(error); }
  };

  const filtered = reviews.filter(r => 
    `${r.first_name} ${r.last_name_paternal}`.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 justify-between items-end gap-6">
        <div className="space-y-4">
          <div className="flex items-center gap-2 text-yellow-500 font-black uppercase text-[10px] tracking-widest">
            <Link href="/leader/dashboard" className="hover:bg-yellow-500/10 p-1 rounded-lg"><ArrowLeft size={18} /></Link>
            <span>Revisiones Pendientes</span>
          </div>
          <h1 className="text-4xl font-black uppercase italic tracking-tighter">Gestión de <span className="text-yellow-500">Estructura</span></h1>
        </div>
        <div className="relative group w-full md:w-80">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-600 group-focus-within:text-yellow-500 transition-colors" size={16} />
          <input 
            type="text" 
            placeholder="Buscar por nombre..." 
            className="bg-[#0a0a0a] border border-gray-800 rounded-2xl py-3 pl-12 pr-6 text-xs focus:border-yellow-500 outline-none w-full transition-all shadow-2xl"
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </header>

      {loading ? (
        <div className="p-20 text-center animate-pulse italic text-gray-600 uppercase text-[10px] tracking-widest">Sincronizando...</div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {filtered.map((item) => (
            <div key={item.id} className="bg-[#0a0a0a] border border-gray-900 rounded-[2.5rem] p-8 relative overflow-hidden shadow-2xl shadow-black">
              <div className="absolute top-0 right-0 bg-yellow-500/10 border-l border-b border-yellow-500/20 px-6 py-2 rounded-bl-2xl">
                <span className="text-[8px] font-black text-yellow-500 uppercase tracking-widest">Brigadista: {item.brigadist_name}</span>
              </div>
              
              <h3 className="text-2xl font-bold uppercase mb-4 italic pt-4">{item.first_name} {item.last_name_paternal}</h3>
              
              <div className="bg-[#050505] border border-gray-800 rounded-2xl p-5 mb-8 italic text-xs text-gray-400">
                <div className="flex items-center gap-2 mb-2 text-gray-600"><MessageSquare size={14}/> <span className="text-[9px] font-black uppercase">Reporte:</span></div>
                "{item.notes || "Pendiente de validación."}"
              </div>

              <div className="flex gap-4">
                <button onClick={() => { setSelectedMilitant(item); setShowEditModal(true); }} className="flex-1 bg-white text-black text-[10px] font-black uppercase py-4 rounded-xl flex items-center justify-center gap-2 hover:bg-gray-200 transition-all">
                  <Edit3 size={14} /> Editar Datos
                </button>
                <button onClick={() => { setSelectedMilitant(item); setShowStatusModal(true); }} className="px-6 bg-yellow-600 text-black text-[10px] font-black uppercase py-4 rounded-xl hover:bg-yellow-500 transition-all">
                  Estatus
                </button>
              </div>
            </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">
          <div className="bg-[#050505] border border-gray-900 w-full max-w-lg rounded-[2.5rem] p-8 shadow-2xl relative overflow-hidden">
            <header className="flex justify-between items-center mb-8">
              <h3 className="text-xl font-black uppercase italic tracking-tighter italic">Ficha de <span className="text-yellow-500">Edición</span></h3>
              <button onClick={() => setShowEditModal(false)} className="text-red-500"><X size={20}/></button>
            </header>
            <div className="space-y-6 max-h-[60vh] overflow-y-auto pr-2 custom-scrollbar pb-4">
               <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"><User size={16}/><span className="text-[9px] font-black uppercase text-white">Identidad</span></div>
                  <input name="first_name" value={selectedMilitant.first_name || ""} onChange={handleEditChange} className={inputClass} placeholder="Nombre" />
                  <div className="grid grid-cols-2 gap-3">
                    <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>
                  <input type="date" name="birth_date" value={selectedMilitant.birth_date?.split("T")[0] || ""} onChange={handleEditChange} className={inputClass} />
               </div>
               <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 space-y-4">
                  <div className="flex items-center gap-2 text-yellow-500"><BookOpenCheck size={16}/><span className="text-[9px] font-black uppercase text-white">Documentación</span></div>
                  <input name="curp" value={selectedMilitant.curp || ""} onChange={handleEditChange} className={`${inputClass} font-mono text-yellow-500`} placeholder="CURP" />
                  <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"><MapPin size={16}/><span className="text-[9px] font-black uppercase text-white">Ubicación</span></div>
                  <div className="grid grid-cols-2 gap-3">
                    <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="">Colonia...</option>
                    {coloniasEdit.map((c, i) => (<option key={i} value={c.colonia}>{c.colonia}</option>))}
                  </select>
                  <textarea name="reference_text" value={selectedMilitant.reference_text || ""} onChange={handleEditChange} className={`${inputClass} h-20 resize-none`} placeholder="Referencias del domicilio..." />
               </div>
            </div>
            <button onClick={handleUpdate} className="w-full mt-6 bg-white text-black h-16 rounded-2xl font-black uppercase text-[10px] tracking-[0.2em] italic transition-all active:scale-95 shadow-2xl shadow-white/10">Sincronizar y Guardar</button>
          </div>
        </div>
      )}

      {/* MODAL ESTATUS + CONFIRMACIÓN */}
      {showStatusModal && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-6 bg-black/95 backdrop-blur-md">
          <div className="bg-[#0a0a0a] border border-gray-900 w-full max-w-sm rounded-[2.5rem] p-8 text-center shadow-2xl">
            {!pendingStatus ? (
              <div className="animate-in fade-in zoom-in">
                <h3 className="text-xl font-black uppercase mb-8 italic tracking-tighter tracking-widest">¿Qué acción <span className="text-yellow-500">deseas tomar?</span></h3>
                <div className="space-y-4">
                  <button onClick={() => setPendingStatus("active")} className="w-full p-5 bg-emerald-500/10 border border-emerald-500/20 rounded-2xl flex items-center justify-between hover:bg-emerald-500 hover:text-black transition-all group">
                    <span className="font-black uppercase text-[10px] tracking-widest">Activar Militante</span>
                    <UserCheck size={20} />
                  </button>
                  <button onClick={() => setPendingStatus("inactive")} className="w-full p-5 bg-red-500/10 border border-red-500/20 rounded-2xl flex items-center justify-between hover:bg-red-500 hover:text-black transition-all group">
                    <span className="font-black uppercase text-[10px] tracking-widest">Baja Definitiva</span>
                    <UserMinus size={20} />
                  </button>
                </div>
                <button onClick={() => setShowStatusModal(false)} className="mt-6 text-[10px] font-black uppercase text-gray-600 hover:text-white transition-colors">Cancelar</button>
              </div>
            ) : (
              <div className="animate-in slide-in-from-bottom-4 duration-300">
                <AlertCircle size={40} className="text-yellow-500 mx-auto mb-4" />
                <h3 className="text-lg font-black uppercase mb-2 italic tracking-tighter">¿Confirmar Acción?</h3>
                <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest mb-8 leading-relaxed px-4">
                  Moverás a {selectedMilitant?.first_name} al estado <span className={pendingStatus === 'active' ? 'text-emerald-500' : 'text-red-500'}>{pendingStatus?.toUpperCase()}</span>.
                </p>
                <div className="grid grid-cols-2 gap-4">
                  <button onClick={() => setPendingStatus(null)} className="py-4 bg-gray-900 rounded-xl text-[9px] font-black uppercase tracking-widest hover:bg-gray-800">Atrás</button>
                  <button onClick={confirmStatusChange} className="py-4 bg-yellow-500 text-black rounded-xl text-[9px] font-black uppercase tracking-widest hover:bg-yellow-400">Sí, Confirmar</button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}