"use client";

import { useState, useEffect } from "react";
import { ArrowLeft, Globe, UserCheck } from "lucide-react";
import Link from "next/link";
// Importación dinámica para evitar errores de SSR con Leaflet
import dynamic from 'next/dynamic';

// Importación de estilos obligatoria para que el mapa no se rompa
import "leaflet/dist/leaflet.css";

const MapContainer = dynamic(() => import('react-leaflet').then(mod => mod.MapContainer), { ssr: false });
const TileLayer = dynamic(() => import('react-leaflet').then(mod => mod.TileLayer), { ssr: false });
const CircleMarker = dynamic(() => import('react-leaflet').then(mod => mod.CircleMarker), { ssr: false });
const Popup = dynamic(() => import('react-leaflet').then(mod => mod.Popup), { ssr: false });

// Componente para forzar el redibujado y centrado
function MapRefresher({ points }: { points: any[] }) {
    const { useMap } = require('react-leaflet');
    const map = useMap();
    useEffect(() => {
        const timer = setTimeout(() => { map.invalidateSize(); }, 500);
        if (points.length > 0 && points[0].lat) {
            map.flyTo([points[0].lat, points[0].lng], 13, { animate: true });
        }
        return () => clearTimeout(timer);
    }, [points, map]);
    return null;
}

export default function MapPage() {
  const [points, setPoints] = useState<any[]>([]);
  const [scope, setScope] = useState<"all" | "mine">("all");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/militants/map?scope=${scope}`)
      .then(res => res.json())
      .then(data => {
        const rawPoints = Array.isArray(data) ? data : [];
        
        // --- LÓGICA DE AGRUPACIÓN (MISMA QUE EN REPORTS) ---
        const grouped = rawPoints.reduce((acc: any, current: any) => {
            const lat = parseFloat(current.latitude);
            const lng = parseFloat(current.longitude);
            if (isNaN(lat) || isNaN(lng)) return acc;

            const key = `${lat}_${lng}`;
            const name = `${current.first_name} ${current.last_name_paternal}`;

            if (!acc[key]) {
                acc[key] = { 
                    lat, 
                    lng, 
                    neighborhood: current.neighborhood,
                    residents: [name] 
                };
            } else {
                acc[key].residents.push(name);
            }
            return acc;
        }, {});

        setPoints(Object.values(grouped));
        setLoading(false);
      });
  }, [scope]);

  return (
    <div className="min-h-screen bg-[#050505] text-white p-10 font-sans">
      
      {/* HEADER UNIFICADO JAMPA */}
      <header className="mb-8 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="/admin/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 italic">Regresar al Panel Principal</span>
          </div>
          <h1 className="text-4xl font-black uppercase tracking-tighter italic">Mapa de Despliegue <span className="text-blue-600">JAMPA</span></h1>
          
          <div className="flex bg-[#0a0a0a] p-1 rounded-2xl border border-gray-900 w-fit shadow-2xl">
            <button onClick={() => setScope("all")} className={`flex items-center gap-2 px-5 py-2 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} /> Vista Global
            </button>
            <button onClick={() => setScope("mine")} className={`flex items-center gap-2 px-5 py-2 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 Registros
            </button>
          </div>
        </div>

        {/* LEYENDA ACTUALIZADA POR DENSIDAD */}
        <div className="bg-[#0a0a0a] border border-gray-900 p-4 rounded-2xl flex flex-wrap gap-6 shadow-xl">
            <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-blue-500"></div>
                <span className="text-[9px] font-black uppercase text-gray-400 italic">Individual</span>
            </div>
            <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-amber-500"></div>
                <span className="text-[9px] font-black uppercase text-gray-400 italic">Hogar (2-4)</span>
            </div>
            <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-red-600"></div>
                <span className="text-[9px] font-black uppercase text-gray-400 italic">Fortaleza (5+)</span>
            </div>
        </div>
      </header>

      {/* CONTENEDOR DEL MAPA (Leaflet en Blanco) */}
      <div className="border border-gray-900 rounded-[2.5rem] overflow-hidden shadow-2xl bg-[#0a0a0a] h-[600px] relative z-0">
        {!loading ? (
          <MapContainer 
            center={[18.8447, -99.1855]} 
            zoom={13} 
            scrollWheelZoom={true} 
            style={{ height: "100%", width: "100%", background: "#f0f0f0" }}
          >
            <MapRefresher points={points} />
            {/* TileLayer en Blanco (Light Mode) */}
            <TileLayer
              url="https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"
              attribution='&copy; OpenStreetMap contributors'
            />
            
            {points.map((p, i) => {
                const count = p.residents.length;
                let color = '#3b82f6'; // Azul default
                let radius = 7;

                if (count >= 5) {
                    color = '#ef4444'; // Rojo
                    radius = 12;
                } else if (count > 1) {
                    color = '#f59e0b'; // Naranja
                    radius = 10;
                }

                return (
                    <CircleMarker 
                        key={i} 
                        center={[p.lat, p.lng]}
                        radius={radius}
                        pathOptions={{ 
                            color: color, 
                            fillColor: color, 
                            fillOpacity: 0.7,
                            weight: count > 1 ? 3 : 1
                        }}
                    >
                        <Popup>
                            <div className="p-1 font-sans min-w-[150px]">
                                <p className={`text-[10px] font-black uppercase mb-2 italic border-b pb-1 ${count > 1 ? 'text-amber-600 border-amber-100' : 'text-blue-600 border-blue-100'}`}>
                                    {count > 1 ? `🏠 ${count} Militantes en este punto` : `👤 Registro Individual`}
                                </p>
                                <div className="max-h-[100px] overflow-y-auto mb-2 pr-1 custom-scrollbar">
                                    {p.residents.map((name: string, idx: number) => (
                                        <p key={idx} className="text-[9px] font-bold text-gray-800 uppercase leading-tight mb-1">• {name}</p>
                                    ))}
                                </div>
                                <p className="text-[8px] font-black text-gray-500 uppercase italic m-0">📍 {p.neighborhood}</p>
                            </div>
                        </Popup>
                    </CircleMarker>
                );
            })}
          </MapContainer>
        ) : (
          <div className="h-full flex flex-col items-center justify-center gap-4 bg-[#080808]">
             <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
             <p className="text-blue-500 font-black uppercase tracking-[0.3em] text-[10px]">Cargando Cartografía Zapata...</p>
          </div>
        )}
      </div>
      
      <footer className="mt-6 text-center">
         <p className="text-[9px] font-bold text-gray-700 uppercase tracking-widest italic">
            Visualización estratégica de fuerza territorial • JAMPA 2026
         </p>
      </footer>
    </div>
  );
}