"use client";

import { MapContainer, TileLayer, Marker, Popup, useMapEvents } from "react-leaflet";
import { useEffect, useState, useCallback } from "react";
import L from "leaflet";
import markerIcon2x from "leaflet/dist/images/marker-icon-2x.png";
import markerIcon from "leaflet/dist/images/marker-icon.png";
import markerShadow from "leaflet/dist/images/marker-shadow.png";
import { createClient } from "@/utils/supabase/client";

const DefaultIcon = L.icon({
    iconRetinaUrl: (markerIcon2x as unknown as { src: string }).src || (markerIcon2x as unknown as string),
    iconUrl: (markerIcon as unknown as { src: string }).src || (markerIcon as unknown as string),
    shadowUrl: (markerShadow as unknown as { src: string }).src || (markerShadow as unknown as string),
    iconSize: [25, 41],
    iconAnchor: [12, 41],
    popupAnchor: [1, -34],
    shadowSize: [41, 41],
});

L.Marker.prototype.options.icon = DefaultIcon;

interface ServiceProvider {
    id: string;
    name: string;
    address: string;
    category: string;
    phone?: string;
    email?: string;
    website?: string;
    latitude?: number;
    longitude?: number;
}

interface MapBounds {
    north: number;
    south: number;
    east: number;
    west: number;
}

function MapBoundsTracker({ 
    onBoundsChange, 
    userLocation 
}: { 
    onBoundsChange: (bounds: MapBounds) => void;
    userLocation?: { lat: number; lng: number } | null;
}) {
    const map = useMapEvents({
        moveend: () => {
            const bounds = map.getBounds();
            onBoundsChange({
                north: bounds.getNorth(),
                south: bounds.getSouth(),
                east: bounds.getEast(),
                west: bounds.getWest()
            });
        },
        zoomend: () => {
            const bounds = map.getBounds();
            onBoundsChange({
                north: bounds.getNorth(),
                south: bounds.getSouth(),
                east: bounds.getEast(),
                west: bounds.getWest()
            });
        }
    });

    // Center map on user location when it becomes available
    useEffect(() => {
        if (userLocation && map) {
            console.log("🎯 Centering map on user location:", userLocation);
            map.setView([userLocation.lat, userLocation.lng], 13);
        }
    }, [userLocation, map]);

    return null;
}

export default function Map(props: any) {
    const [visibleProviders, setVisibleProviders] = useState<ServiceProvider[]>([]);
    const [loading, setLoading] = useState(false);
    const [userLocation, setUserLocation] = useState<{ lat: number; lng: number } | null>(null);
    const [mapCenter, setMapCenter] = useState<[number, number]>([46.1512, 14.9955]); // Default to Slovenia center
    const [locationPermissionRequested, setLocationPermissionRequested] = useState(false);

    const fetchProvidersInBounds = useCallback(async (bounds: MapBounds) => {
        console.log("🗺️ Fetching providers for bounds:", bounds);
        setLoading(true);
        try {
            const supabase = createClient();
            
            // Fetch all providers with coordinates, then filter by bounds
            const { data: allProviders, error } = await supabase
                .from("service_providers")
                .select("*");
            
            console.log("🔍 Supabase query result:", { data: allProviders?.length, error });
            
            if (error) {
                console.error("❌ Supabase error:", error);
                setVisibleProviders([]);
                return;
            }
            
            // Filter to only providers with coordinates
            const providersWithCoords = allProviders?.filter(provider => 
                provider.latitude != null && provider.longitude != null
            ) || [];

            console.log("📊 Total providers with coordinates:", providersWithCoords?.length);

            // Filter by bounds on the client side for now
            const serviceProviders = providersWithCoords?.filter(provider => 
                provider.latitude >= bounds.south &&
                provider.latitude <= bounds.north &&
                provider.longitude >= bounds.west &&
                provider.longitude <= bounds.east
            ) || [];

            console.log("📊 Providers in bounds:", serviceProviders?.length);

            setVisibleProviders(serviceProviders);
        } catch (error) {
            console.error("Error fetching providers:", error);
            setVisibleProviders([]);
        } finally {
            setLoading(false);
        }
    }, []);

    const handleBoundsChange = useCallback((bounds: MapBounds) => {
        fetchProvidersInBounds(bounds);
    }, [fetchProvidersInBounds]);

    // Request user location on component mount
    useEffect(() => {
        if (!locationPermissionRequested && navigator.geolocation) {
            setLocationPermissionRequested(true);
            
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const { latitude, longitude } = position.coords;
                    console.log("📍 User location detected:", { latitude, longitude });
                    const userLoc = { lat: latitude, lng: longitude };
                    setUserLocation(userLoc);
                    setMapCenter([latitude, longitude]);
                    
                    // Fetch providers around user location (wider area)
                    const userBounds: MapBounds = {
                        north: latitude + 2.0,
                        south: latitude - 2.0,
                        east: longitude + 2.0,
                        west: longitude - 2.0
                    };
                    console.log("👤 User location bounds:", userBounds);
                    fetchProvidersInBounds(userBounds);
                },
                (error) => {
                    console.warn("Geolocation error:", error.message);
                    // Fall back to Slovenia bounds
                    const sloveniaInitialBounds: MapBounds = {
                        north: 46.9,
                        south: 45.4,
                        east: 16.6,
                        west: 13.4
                    };
                    fetchProvidersInBounds(sloveniaInitialBounds);
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 300000 // 5 minutes
                }
            );
        }
    }, [locationPermissionRequested, fetchProvidersInBounds, setUserLocation, setMapCenter, setLocationPermissionRequested]);

    return (
        <MapContainer
            center={mapCenter}
            zoom={8}
            scrollWheelZoom={true}
            style={{width: "100%", height: "100%"}}
        >
            <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <MapBoundsTracker onBoundsChange={handleBoundsChange} userLocation={userLocation} />
            
            {/* User location marker */}
            {userLocation && (
                <Marker position={[userLocation.lat, userLocation.lng]}>
                    <Popup>
                        <div>
                            <h3 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: "bold" }}>
                                📍 Your Location
                            </h3>
                            <p style={{ margin: "0", fontSize: "12px" }}>
                                You are here
                            </p>
                        </div>
                    </Popup>
                </Marker>
            )}
            
            {!loading && visibleProviders.map((provider: ServiceProvider) => {
                if (provider.latitude && provider.longitude) {
                    return (
                        <Marker 
                            key={provider.id} 
                            position={[provider.latitude, provider.longitude]}
                        >
                            <Popup>
                                <div>
                                    <h3 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: "bold" }}>
                                        {provider.name}
                                    </h3>
                                    {provider.category && (
                                        <p style={{ margin: "0 0 4px 0", fontSize: "12px", color: "#666" }}>
                                            {provider.category}
                                        </p>
                                    )}
                                    {provider.address && (
                                        <p style={{ margin: "0 0 8px 0", fontSize: "12px" }}>
                                            📍 {provider.address}
                                        </p>
                                    )}
                                    {provider.phone && (
                                        <p style={{ margin: "0 0 4px 0", fontSize: "12px" }}>
                                            📞 <a href={`tel:${provider.phone}`}>{provider.phone}</a>
                                        </p>
                                    )}
                                    {provider.website && (
                                        <p style={{ margin: "0", fontSize: "12px" }}>
                                            🌐 <a href={provider.website} target="_blank" rel="noopener noreferrer">
                                                Website
                                            </a>
                                        </p>
                                    )}
                                </div>
                            </Popup>
                        </Marker>
                    );
                }
                return null;
            })}
        </MapContainer>
    )
}