/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import { useEffect, useRef } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { Property } from '../types';
import { Compass, Maximize2 } from 'lucide-react';

interface MapContainerProps {
  properties: Property[];
  selectedPropertyId: string | null;
  onSelectProperty: (id: string | null) => void;
}

export default function MapContainer({
  properties,
  selectedPropertyId,
  onSelectProperty,
}: MapContainerProps) {
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<L.Map | null>(null);
  const markersRef = useRef<{ [key: string]: L.Marker }>({});

  // 1. Initialize Map
  useEffect(() => {
    if (!mapContainerRef.current) return;
    if (mapInstanceRef.current) return;

    // Default Sasaram center coordinates
    const defaultCenter: L.LatLngExpression = [24.9540, 84.0142];
    const map = L.map(mapContainerRef.current, {
      center: defaultCenter,
      zoom: 12.5,
      zoomControl: false, // will place custom clean zoom buttons or just use default zoom
    });

    // Add subtle, modern Map tile layer from CartoDB (Voyager style)
    L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
      maxZoom: 20,
    }).addTo(map);

    // Add custom small Zoom control in bottom right
    L.control.zoom({
      position: 'bottomright'
    }).addTo(map);

    mapInstanceRef.current = map;

    let initTimer: any = null;
    // Initial boundary fit
    const validProps = properties.filter(p => 
      p && p.location && 
      typeof p.location.lat === 'number' && !isNaN(p.location.lat) && 
      typeof p.location.lng === 'number' && !isNaN(p.location.lng)
    );
    if (validProps.length > 0) {
      initTimer = setTimeout(() => {
        if (mapInstanceRef.current) {
          const bounds = L.latLngBounds(validProps.map(p => [p.location.lat, p.location.lng]));
          mapInstanceRef.current.fitBounds(bounds, { padding: [40, 40] });
        }
      }, 100);
    }

    return () => {
      if (initTimer) clearTimeout(initTimer);
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
      }
    };
  }, []);

  // 2. Render Markers
  useEffect(() => {
    const map = mapInstanceRef.current;
    if (!map) return;

    // Clear previous markers
    Object.keys(markersRef.current).forEach(key => {
      const marker = markersRef.current[key];
      if (marker && map.hasLayer(marker)) {
        marker.remove();
      }
    });
    markersRef.current = {};

    const validProps = properties.filter(p => 
      p && p.location && 
      typeof p.location.lat === 'number' && !isNaN(p.location.lat) && 
      typeof p.location.lng === 'number' && !isNaN(p.location.lng)
    );

    validProps.forEach(prop => {
      const isSelected = prop.id === selectedPropertyId;
      
      // Determine modern glowing vector indicators based on type
      let markerHtml = '';
      if (prop.type === 'charging') {
        markerHtml = `
          <div class="relative flex items-center justify-center w-10 h-10 rounded-full border-2 shadow-lg transition-transform duration-300 hover:scale-125 hover:z-[1000] cursor-pointer
            ${isSelected 
              ? 'border-amber-500 bg-amber-500 shadow-amber-500/40 text-white font-semibold scale-110 z-[999]' 
              : 'border-emerald-600 bg-emerald-50 text-emerald-600'}"
          >
            <svg class="w-5 h-5 fill-none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
            ${isSelected ? '<span class="absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-30 animate-ping"></span>' : ''}
          </div>
        `;
      } else if (prop.type === 'parking') {
        markerHtml = `
          <div class="relative flex items-center justify-center w-10 h-10 rounded-full border-2 shadow-lg transition-transform duration-300 hover:scale-125 hover:z-[1000] cursor-pointer
            ${isSelected 
              ? 'border-amber-500 bg-amber-500 shadow-amber-500/40 text-white font-semibold scale-110 z-[999]' 
              : 'border-indigo-600 bg-indigo-50 text-indigo-700'}"
          >
            <span class="text-base font-extrabold tracking-widest">P</span>
            ${isSelected ? '<span class="absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-30 animate-ping"></span>' : ''}
          </div>
        `;
      } else { // both
        markerHtml = `
          <div class="relative flex items-center justify-center w-10 h-10 rounded-full border-2 shadow-lg transition-transform duration-300 hover:scale-125 hover:z-[1000] cursor-pointer
            ${isSelected 
              ? 'border-amber-500 bg-amber-500 shadow-amber-500/40 text-white font-semibold scale-110 z-[999]' 
              : 'border-teal-600 bg-teal-50 text-teal-700'}"
          >
            <div class="flex items-center gap-0.5">
              <span class="text-xs font-bold">P</span>
              <svg class="w-3.5 h-3.5 fill-none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                <path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            </div>
            ${isSelected ? '<span class="absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-30 animate-ping"></span>' : ''}
          </div>
        `;
      }

      const customIcon = L.divIcon({
        className: 'custom-element-marker',
        html: markerHtml,
        iconSize: [40, 40],
        iconAnchor: [20, 20],
        popupAnchor: [0, -15]
      });

      const marker = L.marker([prop.location.lat, prop.location.lng], { icon: customIcon })
        .addTo(map)
        .on('click', () => {
          onSelectProperty(prop.id);
        });

      // Customized clean leaflet tooltip/popup
      marker.bindPopup(`
        <div style="font-family: system-ui, sans-serif; line-height: 1.4; padding: 2px;">
          <div style="font-weight: 700; font-size: 13px; color: #1e293b;">${prop.title}</div>
          <div style="color: #64748b; font-size: 11px; margin-top: 2px;">${prop.location.address}</div>
          <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 6px; border-top: 1px solid #f1f5f9; padding-top: 6px;">
            <span style="font-weight: 700; color: #0284c7; font-size: 12px;">₹${prop.fare}/hr</span>
            <span style="color: #475569; font-size: 10px; background-color: #f1f5f9; padding: 1px 5px; border-radius: 4px;">
              ${prop.type === 'both' ? 'Parking & Charge' : prop.type === 'charging' ? 'Charging Port' : 'Parking Space'}
            </span>
          </div>
        </div>
      `, {
        closeButton: false,
        minWidth: 180,
        className: 'custom-popup-box'
      });

      markersRef.current[prop.id] = marker;
    });

    return () => {
      const currentMap = mapInstanceRef.current;
      if (currentMap) {
        Object.keys(markersRef.current).forEach(key => {
          const marker = markersRef.current[key];
          if (marker && currentMap.hasLayer(marker)) {
            marker.remove();
          }
        });
      }
      markersRef.current = {};
    };
  }, [properties, selectedPropertyId]);

  // 3. Pan/Zoom when selecting from card list
  useEffect(() => {
    const map = mapInstanceRef.current;
    if (!map || !selectedPropertyId) return;

    const selectedProp = properties.find(p => p.id === selectedPropertyId);
    if (selectedProp && 
        selectedProp.location && 
        typeof selectedProp.location.lat === 'number' && !isNaN(selectedProp.location.lat) && 
        typeof selectedProp.location.lng === 'number' && !isNaN(selectedProp.location.lng)) {
      map.flyTo([selectedProp.location.lat, selectedProp.location.lng], 15, {
        duration: 1.2,
      });

      // Access the corresponding marker and show its popup after flight/zoom
      const timer = setTimeout(() => {
        const currentMap = mapInstanceRef.current;
        if (!currentMap) return;
        const marker = markersRef.current[selectedPropertyId];
        if (marker && currentMap.hasLayer(marker)) {
          marker.openPopup();
        }
      }, 300);

      return () => {
        clearTimeout(timer);
      };
    }
  }, [selectedPropertyId, properties]);

  // 4. Manual Zoom / Recenter helper
  const fitAllMarkers = () => {
    const map = mapInstanceRef.current;
    if (!map) return;
    const validProps = properties.filter(p => 
      p && p.location && 
      typeof p.location.lat === 'number' && !isNaN(p.location.lat) && 
      typeof p.location.lng === 'number' && !isNaN(p.location.lng)
    );
    if (validProps.length === 0) return;
    const bounds = L.latLngBounds(validProps.map(p => [p.location.lat, p.location.lng]));
    map.fitBounds(bounds, { padding: [50, 50] });
    onSelectProperty(null);
  };

  return (
    <div className="relative w-full h-full rounded-2xl overflow-hidden border border-slate-200/80 shadow-md bg-slate-50">
      {/* Map Container Element */}
      <div id="leaflet-map-element" ref={mapContainerRef} className="w-full h-full z-10" />

      {/* Map Overlays & Floating Control UI */}
      <div className="absolute top-4 left-4 z-20 flex flex-col gap-2 pointer-events-none">
        <button
          onClick={fitAllMarkers}
          className="pointer-events-auto flex items-center justify-center gap-1.5 px-3 py-2 bg-white hover:bg-slate-50 text-slate-800 text-xs font-semibold rounded-lg shadow-md border border-slate-200 transition-colors duration-150"
          title="Recenter to show all slots"
          id="btn-recenter-map"
        >
          <Maximize2 className="w-3.5 h-3.5 text-sky-600" />
          <span>Show All ({properties.length})</span>
        </button>
      </div>

      <div className="absolute top-4 right-4 z-20 pointer-events-none">
        <div className="bg-white/95 backdrop-blur px-3 py-1.5 rounded-lg shadow-md border border-slate-100 text-[10px] font-semibold text-slate-600 flex items-center gap-3">
          <div className="flex items-center gap-1">
            <span className="w-2.5 h-2.5 bg-emerald-500 border border-emerald-700 rounded-full inline-block"></span>
            <span>Charging</span>
          </div>
          <div className="flex items-center gap-1">
            <span className="w-2.5 h-2.5 bg-indigo-500 border border-indigo-700 rounded-full inline-block"></span>
            <span>Parking</span>
          </div>
          <div className="flex items-center gap-1">
            <span className="w-2.5 h-2.5 bg-teal-500 border border-teal-700 rounded-full inline-block"></span>
            <span>Dual Venue</span>
          </div>
        </div>
      </div>
    </div>
  );
}
