import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import type { Plext } from "../types";

// Fix Leaflet marker icons
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
    iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
    iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
    shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
});

interface PlayerMapProps {
    plexts: Plext[];
}

export function PlayerMap({ plexts }: PlayerMapProps) {
    // Get player locations from plexts
    const playerLocations = plexts
        .map((plext) => {
            const player = plext.markup.find((item) => item.type === "PLAYER");
            if (player && player.plain && plext.coordinates && plext.coordinates.coordinates) {
                return {
                    name: player.plain,
                    team: player.team || "NEUTRAL",
                    coordinates: [plext.coordinates.coordinates[1], plext.coordinates.coordinates[0]] as [number, number], // [lat, lon]
                    eventType: plext.event_type,
                    timestamp: plext.timestamp,
                };
            }
            return null;
        })
        .filter(Boolean);

    return (
        <div className="map-container" style={{ height: "600px", width: "100%" }}>
            <MapContainer
                center={[45.57, 12.36]} // Default to Veneto region
                zoom={12}
                style={{ height: "100%", width: "100%" }}
                scrollWheelZoom={true}
            >
                <TileLayer
                    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                {playerLocations.map((location, index) => {
                    if (!location) return null;

                    const markerColor = location.team === "RESISTANCE" ? "blue" : "green";

                    return (
                        <Marker
                            key={index}
                            position={location.coordinates}
                            icon={new L.Icon({
                                iconUrl: `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${markerColor}.png`,
                                shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
                                iconSize: [25, 41],
                                iconAnchor: [12, 41],
                                popupAnchor: [1, -34],
                                shadowSize: [41, 41],
                            })}
                        >
                            <Popup>
                                <div className="marker-popup">
                                    <h4 style={{ color: location.team === "RESISTANCE" ? "#0066ff" : "#00cc00" }}>
                                        {location.name}
                                    </h4>
                                    <p><strong>Team:</strong> {location.team}</p>
                                    <p><strong>Event:</strong> {location.eventType}</p>
                                    <p><strong>Time:</strong> {new Date(location.timestamp).toLocaleString()}</p>
                                </div>
                            </Popup>
                        </Marker>
                    );
                })}
            </MapContainer>
        </div>
    );
}
