"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { Datos } from "./types";
import { Button } from "../ui";
import { Telephone, Ubication } from "../ui/icons";

interface MapMarker {
  id: number;
  name: string;
  position: [number, number];
  phone: string;
  direction: string;
  especialidades: string[];
}

interface MapComponentProps {
  locations: Datos[];
  handleClick: (content: string[]) => void;
}

// Importar Leaflet solo en cliente
const LazyMapContainer = dynamic(() => import("react-leaflet").then((mod) => mod.MapContainer), { ssr: false });

const LazyTileLayer = dynamic(() => import("react-leaflet").then((mod) => mod.TileLayer), { ssr: false });

const LazyPopup = dynamic(() => import("react-leaflet").then((mod) => mod.Popup), { ssr: false });

const LazyMarker = dynamic(
  async () => {
    const { Marker } = await import("react-leaflet");
    const L = await import("leaflet");
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const CustomMarker = (props: any) => {
      const customIcon = L.divIcon({
        html: `
          <div style="
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            transform: translateY(-20px);
          ">
            <svg 
              width="30" 
              height="38" 
              viewBox="0 0 17 21" 
              fill="none" 
              xmlns="http://www.w3.org/2000/svg"
            >
              
              <path
                d="M8.49999 1C4.35206 1 1 4.19202 1 8.12504C1 10.4906 1.71161 11.4596 5.12921 16.0766C5.85954 17.0836 6.72097 18.2426 7.7322 19.6201C7.79774 19.7056 7.87265 19.7816 7.96628 19.8386C8.38763 20.1236 8.97752 20.0191 9.26778 19.6201C10.2697 18.2426 11.1311 17.0741 11.8708 16.0861C15.2884 11.4596 16 10.5001 16 8.13454C16.0093 4.19202 12.6573 1 8.51872 1H8.49999ZM8.49999 11.4501C6.94569 11.4501 5.69101 10.177 5.69101 8.60004C5.69101 7.02303 6.94569 5.75003 8.49999 5.75003C10.0543 5.75003 11.309 7.02303 11.309 8.60004C11.309 10.177 10.0543 11.4501 8.49999 11.4501Z"
                fill="#2FC191" 
                stroke="none"
                stroke-width="0"
              />
            </svg>
          </div>
        `,
        className: "custom-marker-icon",
        iconSize: [30, 40],
        iconAnchor: [15, 40],
        popupAnchor: [0, -35],
      });

      return <Marker {...props} icon={customIcon} />;
    };

    return CustomMarker;
  },
  { ssr: false },
);

/**
 *
 * @param locations
 * @component
 */
export const MapComponent = ({ locations, handleClick }: MapComponentProps) => {
  const [markers, setMarkers] = useState<MapMarker[]>([]);
  const [mapCenter, setMapCenter] = useState<[number, number]>([-34.6037, -58.3816]);
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);

    if (locations && Array.isArray(locations) && locations.length > 0) {
      const processedMarkers = locations
        .filter((loc) => {
          const latNum = parseFloat(loc.lat?.toString());
          const lngNum = parseFloat(loc.lng?.toString());
          return !isNaN(latNum) && !isNaN(lngNum);
        })
        .map((loc, index) => {
          return {
            id: index,
            name: loc.prestador || "Sin nombre",
            position: [parseFloat(loc.lat.toString()), parseFloat(loc.lng.toString())] as [number, number],
            phone: loc.telefono || "Sin teléfono",
            direction: loc.domicilio || "Sin domicilio",
            especialidades: loc.especialidades?.map((s) => s.especialidad) || [],
          };
        });

      setMarkers(processedMarkers);

      if (processedMarkers.length > 0) {
        const avgLat = processedMarkers.reduce((sum, m) => sum + m.position[0], 0) / processedMarkers.length;
        const avgLng = processedMarkers.reduce((sum, m) => sum + m.position[1], 0) / processedMarkers.length;
        setMapCenter([avgLat, avgLng]);
      }
    }
  }, [locations]);

  if (!isMounted) {
    return (
      <div className="w-full h-[500px] rounded-lg overflow-hidden shadow-lg bg-gray-200 animate-pulse">
        <div className="flex items-center justify-center h-full">
          <p className="text-gray-500">Cargando mapa...</p>
        </div>
      </div>
    );
  }

  if (!locations || locations.length === 0) {
    return (
      <div className="w-full h-[500px] rounded-lg overflow-hidden shadow-lg bg-gray-100">
        <div className="flex items-center justify-center h-full">
          <p className="text-gray-500">No hay ubicaciones disponibles</p>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full h-[31.25rem] rounded-lg overflow-hidden shadow-lg">
      <LazyMapContainer center={mapCenter} zoom={14} className="w-full h-full" scrollWheelZoom={true}>
        <LazyTileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

        {markers.map((marker) => (
          <LazyMarker key={marker.id} position={marker.position} title={marker.name}>
            <LazyPopup>
              <div className="px-4 min-w-[12.5rem] space-y-4">
                <h3 className="font-medium text-base mt-3">{marker.name}</h3>
                <div className="text-sm space-y-4">
                  <div className="flex gap-3 items-center">
                    <Telephone className="w-4 h-5 text-contigo-verde" />
                    <div className="flex-1">{marker.phone}</div>
                  </div>
                  <div className="flex gap-3 items-center">
                    <Ubication className="w-4 h-5 text-contigo-verde" />
                    <div className="flex-1">{marker.direction}</div>
                  </div>
                </div>
                <Button className="max-w-fit mx-auto" onClick={() => handleClick(marker.especialidades)}>
                  Ver especialidades
                </Button>
              </div>
            </LazyPopup>
          </LazyMarker>
        ))}
      </LazyMapContainer>
    </div>
  );
};
