import { useEffect, useRef, useCallback } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

interface MapItem {
    type?: 'unit' | 'project';
    id: number;
    title: string;
    latitude?: number;
    longitude?: number;
    price?: string;
    image?: string;
}

interface InteractiveMapProps {
    items: MapItem[];
    selectedItem: MapItem | null;
    onSelectItem: (item: MapItem | null) => void;
    className?: string;
}

// Saudi Arabia Bounds
const KSA_BOUNDS: L.LatLngBoundsExpression = [
    [16.3965, 34.4861], // Southwest
    [32.2500, 55.7000]  // Northeast
];
const DEFAULT_CENTER: [number, number] = [23.8859, 45.0792];
const DEFAULT_ZOOM = 6;
const MIN_ZOOM = 5;

// Custom marker icon
const createCustomIcon = (isSelected: boolean, type?: 'unit' | 'project') => {
    let color = '#052531'; // Default Navy for Units
    if (isSelected) {
        color = '#F0B100'; // Gold for selected
    } else if (type === 'project') {
        color = '#10B981'; // Emerald for Projects
    }

    return L.divIcon({
        className: 'custom-marker',
        html: `
      <div style="
        width: 32px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        filter: drop-shadow(0px 2px 4px rgba(0,0,0,0.3));
        transition: transform 0.2s;
        ${isSelected ? 'transform: translate(-50%, -100%) scale(1.1); font-weight: bold;' : 'transform: translate(-50%, -100%);'}
      ">
        <svg width="32" height="40" viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M16 0C7.163 0 0 7.163 0 16C0 28 16 40 16 40C16 40 32 28 32 16C32 7.163 24.837 0 16 0Z" fill="${color}"/>
          <circle cx="16" cy="16" r="8" fill="white"/>
        </svg>
      </div>
    `,
        iconSize: [32, 40],
        iconAnchor: [16, 40],
        popupAnchor: [0, -40],
    });
};

export default function InteractiveMap({
    items,
    selectedItem,
    onSelectItem,
    className = ''
}: InteractiveMapProps) {
    const mapRef = useRef<L.Map | null>(null);
    const mapContainerRef = useRef<HTMLDivElement>(null);
    const markersRef = useRef<Map<number, L.Marker>>(new Map());

    const updateMarkers = useCallback(() => {
        if (!mapRef.current) return;

        // Clear existing markers
        markersRef.current.forEach(marker => marker.remove());
        markersRef.current.clear();

        // Filter items with valid coordinates
        const validItems = items.filter(
            item => item.latitude && item.longitude &&
                !isNaN(item.latitude) && !isNaN(item.longitude)
        );

        if (validItems.length === 0) return;

        // Add markers for each item
        validItems.forEach(item => {
            if (!item.latitude || !item.longitude) return;

            const isSelected = selectedItem?.id === item.id;
            const marker = L.marker([item.latitude, item.longitude], {
                icon: createCustomIcon(isSelected, item.type),
            });

            // Add popup with basic info
            marker.bindPopup(`
        <div style="text-align: right; direction: rtl; min-width: 150px;">
          <strong style="font-size: 14px;">${item.title}</strong>
          ${item.price ? `<br/><span style="color: #052531; font-weight: 600;">${item.price} ريال</span>` : ''}
        </div>
      `);

            // Handle click
            marker.on('click', (e) => {
                L.DomEvent.stopPropagation(e);

                // #region agent log
                fetch('http://127.0.0.1:7243/ingest/7c58cb0a-c59c-468a-b5c4-12a74e329d1e', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        sessionId: 'debug-session',
                        runId: 'pre-fix',
                        hypothesisId: 'H2',
                        location: 'InteractiveMap.tsx:marker-click',
                        message: 'Marker clicked',
                        data: { itemId: item.id },
                        timestamp: Date.now(),
                    }),
                }).catch(() => { });
                // #endregion

                onSelectItem(item);
            });

            marker.addTo(mapRef.current!);
            markersRef.current.set(item.id, marker);
        });

        // Fit bounds to show all markers if they exist
        if (validItems.length > 0) {
            const bounds = L.latLngBounds(
                validItems.map(item => [item.latitude!, item.longitude!] as [number, number])
            );
            // Only fit bounds if we don't have a selected item yet or if it's the first load of items
            if (!selectedItem) {
                mapRef.current.fitBounds(bounds, { padding: [50, 50], maxZoom: 10 });
            }
        }

        // Force map to recalculate size
        setTimeout(() => {
            mapRef.current?.invalidateSize();
        }, 100);
    }, [items, selectedItem, onSelectItem]);

    // Initialize map
    useEffect(() => {
        if (!mapContainerRef.current || mapRef.current) return;

        // Create map

        mapRef.current = L.map(mapContainerRef.current, {
            center: DEFAULT_CENTER,
            zoom: DEFAULT_ZOOM,
            minZoom: MIN_ZOOM,
            maxBounds: KSA_BOUNDS,
            maxBoundsViscosity: 1.0,
            zoomControl: true,
            attributionControl: false,
            // @ts-ignore - tap is a valid Leaflet option for mobile browsers
            tap: false,
        });


        // Handle map background click to dismiss selection

        mapRef.current.on('click', () => {
            // #region agent log
            fetch('http://127.0.0.1:7243/ingest/7c58cb0a-c59c-468a-b5c4-12a74e329d1e', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    sessionId: 'debug-session',
                    runId: 'pre-fix',
                    hypothesisId: 'H1',
                    location: 'InteractiveMap.tsx:map-click',
                    message: 'Leaflet map background clicked',
                    data: {},
                    timestamp: Date.now(),
                }),
            }).catch(() => { });
            // #endregion

            onSelectItem(null);

        });


        // Add OpenStreetMap tiles

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {

            attribution: '&copy; OpenStreetMap',

            maxZoom: 19,

        }).addTo(mapRef.current);

        updateMarkers();

        // Cleanup on unmount
        return () => {
            if (mapRef.current) {
                mapRef.current.remove();
                mapRef.current = null;
            }
        };
    }, []); // Only run once on mount

    // Update markers when items change
    useEffect(() => {
        updateMarkers();
    }, [items, updateMarkers]);

    // Update selected marker style and pan
    useEffect(() => {
        markersRef.current.forEach((marker, id) => {
            const item = items.find(i => i.id === id);
            const isSelected = selectedItem?.id === id;
            marker.setIcon(createCustomIcon(isSelected, item?.type));
            if (isSelected) {
                marker.openPopup();
            }
        });

        if (selectedItem?.latitude && selectedItem?.longitude && mapRef.current) {
            mapRef.current.panTo([selectedItem.latitude, selectedItem.longitude], {
                animate: true,
                duration: 0.5,
            });
        }
    }, [selectedItem]);

    return (
        <div
            ref={mapContainerRef}
            className={`w-full h-full min-h-[400px] rounded-xl overflow-hidden ${className}`}
            style={{ zIndex: 1 }}
        />
    );
}
