import { useEffect } from "react";
import { MapContainer, TileLayer, Marker, Popup, Polyline } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import { MapPinIcon, TruckIcon, PackageIcon } from "lucide-react";

// Fix for default marker icons in React-Leaflet
// @ts-expect-error - Leaflet internal modification
delete L.Icon.Default.prototype._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",
});

// Custom icons
const createCustomIcon = (color: string) => {
  return L.divIcon({
    className: "custom-icon",
    html: `<div style="background-color: ${color}; width: 30px; height: 30px; border-radius: 50%; border: 3px solid white; box-shadow: 0 2px 8px rgba(0,0,0,0.3);"></div>`,
    iconSize: [30, 30],
    iconAnchor: [15, 15],
  });
};

const originIcon = createCustomIcon("#22c55e"); // Green
const destinationIcon = createCustomIcon("#ef4444"); // Red
const currentIcon = createCustomIcon("#3b82f6"); // Blue

type TrackingPoint = {
  latitude: number;
  longitude: number;
  timestamp: number;
  status?: string;
  notes?: string;
};

type TrackingMapProps = {
  origin: {
    latitude?: number;
    longitude?: number;
    address: string;
    city: string;
    country: string;
  };
  destination: {
    latitude?: number;
    longitude?: number;
    address: string;
    city: string;
    country: string;
  };
  trackingPoints?: TrackingPoint[];
  className?: string;
};

export function TrackingMap({
  origin,
  destination,
  trackingPoints = [],
  className = "",
}: TrackingMapProps) {
  // Calculate center point between origin and destination
  const originLat = origin.latitude ?? 0;
  const originLng = origin.longitude ?? 0;
  const destLat = destination.latitude ?? 0;
  const destLng = destination.longitude ?? 0;

  const centerLat = (originLat + destLat) / 2;
  const centerLng = (originLng + destLng) / 2;

  // If no coordinates, use default center (Africa)
  const center: [number, number] = originLat && destLat 
    ? [centerLat, centerLng]
    : [0, 20]; // Center of Africa

  // Calculate zoom level based on distance
  const calculateZoom = () => {
    if (!originLat || !destLat) return 3;
    
    const latDiff = Math.abs(originLat - destLat);
    const lngDiff = Math.abs(originLng - destLng);
    const maxDiff = Math.max(latDiff, lngDiff);

    if (maxDiff > 20) return 3;
    if (maxDiff > 10) return 4;
    if (maxDiff > 5) return 5;
    if (maxDiff > 2) return 6;
    return 7;
  };

  // Create polyline coordinates (origin -> tracking points -> destination)
  const polylinePositions: [number, number][] = [];
  
  if (originLat && originLng) {
    polylinePositions.push([originLat, originLng]);
  }
  
  trackingPoints.forEach(point => {
    if (point.latitude && point.longitude) {
      polylinePositions.push([point.latitude, point.longitude]);
    }
  });
  
  if (destLat && destLng) {
    polylinePositions.push([destLat, destLng]);
  }

  // Get current position (last tracking point)
  const currentPosition = trackingPoints.length > 0 
    ? trackingPoints[trackingPoints.length - 1]
    : null;

  return (
    <div className={`rounded-lg overflow-hidden border ${className}`}>
      <MapContainer
        center={center}
        zoom={calculateZoom()}
        scrollWheelZoom={false}
        style={{ height: "500px", width: "100%" }}
        className="z-0"
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

        {/* Origin marker */}
        {originLat && originLng && (
          <Marker position={[originLat, originLng]} icon={originIcon}>
            <Popup>
              <div className="space-y-1">
                <div className="flex items-center gap-2 font-semibold">
                  <PackageIcon className="size-4 text-green-600" />
                  <span>Origine</span>
                </div>
                <div className="text-sm text-muted-foreground">
                  {origin.address}
                  <br />
                  {origin.city}, {origin.country}
                </div>
              </div>
            </Popup>
          </Marker>
        )}

        {/* Destination marker */}
        {destLat && destLng && (
          <Marker position={[destLat, destLng]} icon={destinationIcon}>
            <Popup>
              <div className="space-y-1">
                <div className="flex items-center gap-2 font-semibold">
                  <MapPinIcon className="size-4 text-red-600" />
                  <span>Destination</span>
                </div>
                <div className="text-sm text-muted-foreground">
                  {destination.address}
                  <br />
                  {destination.city}, {destination.country}
                </div>
              </div>
            </Popup>
          </Marker>
        )}

        {/* Current position marker */}
        {currentPosition && currentPosition.latitude && currentPosition.longitude && (
          <Marker 
            position={[currentPosition.latitude, currentPosition.longitude]} 
            icon={currentIcon}
          >
            <Popup>
              <div className="space-y-1">
                <div className="flex items-center gap-2 font-semibold">
                  <TruckIcon className="size-4 text-blue-600" />
                  <span>Position actuelle</span>
                </div>
                <div className="text-sm text-muted-foreground">
                  {currentPosition.status && (
                    <div className="font-medium">{currentPosition.status}</div>
                  )}
                  {currentPosition.notes && (
                    <div>{currentPosition.notes}</div>
                  )}
                  <div className="text-xs">
                    {new Date(currentPosition.timestamp).toLocaleString()}
                  </div>
                </div>
              </div>
            </Popup>
          </Marker>
        )}

        {/* Route polyline */}
        {polylinePositions.length >= 2 && (
          <Polyline
            positions={polylinePositions}
            color="#3b82f6"
            weight={3}
            opacity={0.7}
            dashArray="10, 10"
          />
        )}
      </MapContainer>
    </div>
  );
}