"use client";
import { MapContainer, TileLayer, GeoJSON, useMap } from "react-leaflet";
import { useEffect, useState } from "react";
import L from "leaflet";
import "leaflet/dist/leaflet.css";

// Componente para manejar el re-enfoque del mapa
function MapRefocus({ center }: { center: [number, number] | null }) {
  const map = useMap();
  useEffect(() => {
    if (center) {
      map.setView(center, 15, { animate: true });
    }
  }, [center, map]);
  return null;
}

export default function HeatmapAdmin({ geojson, stats, seccionEnfocada }: any) {
  // Evitamos el error de hidratación de Next.js
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return <div className="h-full w-full bg-gray-100 animate-pulse" />;

  const getStyle = (feature: any) => {
    const sectionNum = feature.properties.seccion;
    const data = stats.find((s: any) => String(s.section) === String(sectionNum));
    const count = data ? data.count : 0;

    // Escala calorífica
    let color = "#cbd5e1"; // Gris para 0
    if (count > 0 && count <= 20) color = "#ef4444";      // Rojo
    else if (count > 20 && count <= 50) color = "#f97316"; // Naranja
    else if (count > 50) color = "#22c55e";               // Verde

    const isSelected = String(sectionNum) === String(seccionEnfocada);

    return {
      fillColor: color,
      weight: isSelected ? 3 : 1,
      opacity: 1,
      color: isSelected ? "#000" : "#fff",
      fillOpacity: isSelected ? 0.8 : 0.5,
    };
  };

  // Coordenadas de Zapata por defecto
  const position: [number, number] = [18.845, -99.184];

  return (
    <div className="h-full w-full relative bg-white">
      <MapContainer 
        center={position} 
        zoom={13} 
        scrollWheelZoom={true}
        className="h-full w-full"
        style={{ height: "100%", width: "100%" }}
        zoomControl={false}
      >
        <MapRefocus center={null} />
        
        <TileLayer
          url="https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png"
          attribution='&copy; CARTO'
        />

        {geojson && (
          <GeoJSON 
            data={geojson} 
            style={getStyle}
            onEachFeature={(feature, layer) => {
              const section = feature.properties.seccion;
              const data = stats.find((s: any) => String(s.section) === String(section));
              layer.bindPopup(`
                <div style="color: black;">
                  <b>Sección ${section}</b><br/>
                  ${data ? data.count : 0} Registros
                </div>
              `);
            }}
          />
        )}
      </MapContainer>
    </div>
  );
}