"use client";

import { useState, useEffect, useRef } from "react";
import {
  GoogleMap,
  Marker,
  DirectionsService,
  DirectionsRenderer,
  Libraries,
} from "@react-google-maps/api";

import home from "@/assets/icons/home.png";
import restaurant from "@/assets/icons/restaurant.svg";
import driver from "@/assets/icons/driver.png";

const libraries: Libraries = ["places", "geometry"];

const MapContainerDetail = ({
  resAdd,
  customerAdd,
  driverAdd: initialDriverAdd,
  status,
  socket,
  orderId,
  deliverType
}: {
  resAdd: any;
  customerAdd: any;
  driverAdd: any;
  status: string;
  socket: any;
  orderId: string;
  deliverType: string;
}) => {
  const [directions, setDirections] = useState<any>(null);
  const [distance, setDistance] = useState<number | null>(null);
  const [googleMapsLoaded, setGoogleMapsLoaded] = useState(false);
  const [driverLocation, setDriverLocation] = useState<{ coordinates: number[] } | null>(
    initialDriverAdd?.coordinates ? { coordinates: initialDriverAdd.coordinates } : null
  );

  const mapRef = useRef<google.maps.Map | null>(null);

  useEffect(() => {
    const checkGoogleMapsLoaded = () => {
      if (typeof window !== "undefined" && window.google && window.google.maps) {
        setGoogleMapsLoaded(true);
      } else {
        setTimeout(checkGoogleMapsLoaded, 100);
      }
    };
    checkGoogleMapsLoaded();
  }, []);

  useEffect(() => {
    if (initialDriverAdd?.coordinates) {
      setDriverLocation({ coordinates: initialDriverAdd.coordinates });
    }
  }, [initialDriverAdd]);

  useEffect(() => {
    setDirections(null);
  }, [driverLocation]);


  const handleDriverLocationUpdate = (data: any) => {
    if (
      data?.lat &&
      data?.long &&
      data?.order_id === orderId
    ) {
      const newLocation = {
        coordinates: [data.long, data.lat],
      };
      setDriverLocation(newLocation);
    } else {
      console.warn("Invalid data or unmatched orderId");
    }
  };

  useEffect(() => {
    if (!socket) return;

    socket.on("current_driver_location", handleDriverLocationUpdate);

    return () => {
      socket.off("current_driver_location", handleDriverLocationUpdate);
    };
  }, [socket, orderId]);

  useEffect(() => {
    if (
      (status === "ready_for_pickup" ||
        status === "picked_up" ||
        status === "out_for_delivery") &&
      socket
    ) {
      socket.emit("find-driver", { order_id: orderId });
      socket.on("current_driver_location", handleDriverLocationUpdate);
    }
  }, [status, socket, orderId]);

  const center = (() => {
    if (
      status === "ready_for_pickup" ||
      status === "picked_up" ||
      status === "out_for_delivery"
    ) {
      if (driverLocation?.coordinates) {
        return {
          lat: Number(driverLocation.coordinates[1]),
          lng: Number(driverLocation.coordinates[0]),
        };
      }
      return {
        lat: Number(resAdd?.lat),
        lng: Number(resAdd?.long),
      };
    }
    return {
      lat: Number(customerAdd?.lat),
      lng: Number(customerAdd?.long),
    };
  })();

  const destination =
    status === "ready_for_pickup"
      ? { lat: Number(resAdd?.lat), lng: Number(resAdd?.long) }
      : { lat: Number(customerAdd?.lat), lng: Number(customerAdd?.long) };

  const origin = driverLocation?.coordinates
    ? {
      lat: Number(driverLocation.coordinates[1]),
      lng: Number(driverLocation.coordinates[0]),
    }
    : {
      lat: Number(resAdd?.lat),
      lng: Number(resAdd?.long),
    };

  const handleDirectionsCallback = (response: any) => {
    if (response?.status === "OK") {
      setDirections(response);
      const routeLeg = response.routes[0].legs[0];
      setDistance(routeLeg.distance.value / 1000);
    } else {
      console.error("Directions request failed:", response);
    }
  };

  const onMapLoad = (map: google.maps.Map) => {
    mapRef.current = map;
  };

  useEffect(() => {
    if (!mapRef?.current) return;

    if (!center || isNaN(center.lat) || isNaN(center.lng)) {
      console.warn("Invalid center", center);
      return;
    }

    mapRef.current.panTo(center);
  }, [status, driverLocation, center]);


  const getIcon = (url: string) => {
    if (
      googleMapsLoaded &&
      typeof google !== "undefined" &&
      window.google?.maps?.Size
    ) {
      return {
        url,
        scaledSize: new window.google.maps.Size(30, 30),
      };
    }
    return undefined;
  };

  return (
    <div className="w-full h-full">
      <div className="flex flex-col gap-2">
        {/* {distance !== null && (
          <div className="text-sm text-gray-700 mb-2">
            Distance: {distance.toFixed(2)} km
          </div>
        )} */}

        <div className="map-wrapper w-full" style={{ height: "400px" }}>
          {googleMapsLoaded && (
            <GoogleMap
              center={center}
              zoom={12}
              mapContainerStyle={{ width: "100%", height: "100%" }}
              onLoad={onMapLoad}
            >
              {!directions && origin && destination && (
                <DirectionsService
                  options={{
                    origin,
                    destination,
                    travelMode: window.google.maps.TravelMode.DRIVING,
                  }}
                  callback={handleDirectionsCallback}
                />
              )}

              {directions && (
                <DirectionsRenderer
                  options={{
                    directions,
                    suppressMarkers: true,
                    polylineOptions: {
                      strokeColor: "#000000",
                      strokeOpacity: 0.8,
                      strokeWeight: 4,
                    },
                  }}
                />
              )}

              <Marker
                position={{ lat: Number(resAdd?.lat), lng: Number(resAdd?.long) }}
                icon={getIcon(restaurant.src)}
              />

              {deliverType !== "takeaway" && (
                <Marker
                  position={{ lat: Number(customerAdd?.lat), lng: Number(customerAdd?.long) }}
                  icon={getIcon(home.src)}
                />
              )}


              <Marker
                position={{ lat: Number(customerAdd?.lat), lng: Number(customerAdd?.long) }}
                icon={getIcon(home.src)}
              />

              {(status === "ready_for_pickup" ||
                status === "picked_up" ||
                status === "out_for_delivery") &&
                driverLocation && (
                  <Marker
                    position={{
                      lat: Number(driverLocation.coordinates[1]),
                      lng: Number(driverLocation.coordinates[0]),
                    }}
                    icon={getIcon(driver.src)}
                  />
                )}
            </GoogleMap>
          )}
        </div>
      </div>
    </div>
  );
};

export default MapContainerDetail;
