/**
 * POI Map Component
 *
 * Interactive map visualization of POIs around bakery location
 * Uses Leaflet for mapping and displays POIs with color-coded markers
 */

import React, { useMemo } from 'react';
import { MapContainer, TileLayer, Marker, Circle, Popup, useMap } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import type { POIContext, POI } from '@/types/poi';
import { POI_CATEGORY_METADATA, formatDistance } from '@/types/poi';

// Fix for default marker icons in Leaflet
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
});

interface POIMapProps {
  poiContext: POIContext;
  selectedCategory?: string | null;
}

// Helper component to create custom colored icons
function createColoredIcon(color: string, emoji: string): L.DivIcon {
  return L.divIcon({
    className: 'custom-poi-marker',
    html: `<div style="background-color: ${color}; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 2px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.3); font-size: 18px;">${emoji}</div>`,
    iconSize: [32, 32],
    iconAnchor: [16, 16]
  });
}

function createBakeryIcon(): L.DivIcon {
  return L.divIcon({
    className: 'bakery-marker',
    html: `<div style="background-color: #dc2626; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 3px solid white; box-shadow: 0 3px 6px rgba(0,0,0,0.4); font-size: 24px;">🏪</div>`,
    iconSize: [40, 40],
    iconAnchor: [20, 20]
  });
}

// Component to recenter map when location changes
function MapRecenter({ center }: { center: [number, number] }) {
  const map = useMap();
  React.useEffect(() => {
    map.setView(center, map.getZoom());
  }, [center, map]);
  return null;
}

export const POIMap: React.FC<POIMapProps> = ({ poiContext, selectedCategory }) => {
  const center: [number, number] = [
    poiContext.location.latitude,
    poiContext.location.longitude
  ];

  // Filter POIs by selected category
  const poisToDisplay = useMemo(() => {
    const pois: Array<{ category: string; poi: POI }> = [];

    Object.entries(poiContext.poi_detection_results).forEach(([category, data]) => {
      if (selectedCategory && selectedCategory !== category) {
        return; // Skip if category filter is active and doesn't match
      }

      data.pois.forEach(poi => {
        pois.push({ category, poi });
      });
    });

    return pois;
  }, [poiContext, selectedCategory]);

  return (
    <div className="relative w-full h-full rounded-lg overflow-hidden border border-gray-200">
      <MapContainer
        center={center}
        zoom={15}
        style={{ height: '100%', width: '100%' }}
        scrollWheelZoom={true}
      >
        <MapRecenter center={center} />

        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

        {/* Bakery marker */}
        <Marker position={center} icon={createBakeryIcon()}>
          <Popup>
            <div className="text-center">
              <div className="font-semibold text-base">Your Bakery</div>
              <div className="text-sm text-gray-600 mt-1">
                {center[0].toFixed(6)}, {center[1].toFixed(6)}
              </div>
            </div>
          </Popup>
        </Marker>

        {/* Distance rings */}
        <Circle
          center={center}
          radius={100}
          pathOptions={{
            color: '#22c55e',
            fillColor: '#22c55e',
            fillOpacity: 0.05,
            weight: 2,
            dashArray: '5, 5'
          }}
        />
        <Circle
          center={center}
          radius={300}
          pathOptions={{
            color: '#f59e0b',
            fillColor: '#f59e0b',
            fillOpacity: 0.03,
            weight: 2,
            dashArray: '5, 5'
          }}
        />
        <Circle
          center={center}
          radius={500}
          pathOptions={{
            color: '#ef4444',
            fillColor: '#ef4444',
            fillOpacity: 0.02,
            weight: 2,
            dashArray: '5, 5'
          }}
        />

        {/* POI markers */}
        {poisToDisplay.map(({ category, poi }, index) => {
          const metadata = POI_CATEGORY_METADATA[category];
          if (!metadata) return null;

          return (
            <Marker
              key={`${category}-${poi.osm_id}-${index}`}
              position={[poi.lat, poi.lon]}
              icon={createColoredIcon(metadata.color, metadata.icon)}
            >
              <Popup>
                <div className="min-w-[200px]">
                  <div className="flex items-center gap-2 mb-2">
                    <span style={{ fontSize: '24px' }}>{metadata.icon}</span>
                    <div>
                      <div className="font-semibold">{poi.name}</div>
                      <div className="text-xs text-gray-600">{metadata.displayName}</div>
                    </div>
                  </div>
                  {poi.distance_m && (
                    <div className="text-sm text-gray-700 mt-1">
                      Distance: <span className="font-medium">{formatDistance(poi.distance_m)}</span>
                    </div>
                  )}
                  {poi.zone && (
                    <div className="text-sm text-gray-700">
                      Zone: <span className="font-medium capitalize">{poi.zone.replace('_', ' ')}</span>
                    </div>
                  )}
                  <div className="text-xs text-gray-500 mt-2">
                    OSM ID: {poi.osm_id}
                  </div>
                </div>
              </Popup>
            </Marker>
          );
        })}
      </MapContainer>

      {/* Legend */}
      <div className="absolute bottom-4 right-4 bg-white rounded-lg shadow-lg p-3 max-w-xs z-[1000]">
        <div className="font-semibold text-sm mb-2">Distance Rings</div>
        <div className="space-y-1 text-xs">
          <div className="flex items-center gap-2">
            <div className="w-4 h-0.5 border-t-2 border-green-500 border-dashed"></div>
            <span>100m - Immediate</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-0.5 border-t-2 border-orange-500 border-dashed"></div>
            <span>300m - Primary</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-0.5 border-t-2 border-red-500 border-dashed"></div>
            <span>500m - Secondary</span>
          </div>
        </div>
      </div>
    </div>
  );
};
