import { ref, type Ref } from 'vue';
import * as LeafLet from 'leaflet';
import type { LeafletMouseEvent } from 'leaflet';
import { reverseGeocodeRateLimited } from 'functions/reverseGeocodeSocket';

type RouteSet = {
  start?: LeafLet.LatLng | null | undefined;
  end?: LeafLet.LatLng | null | undefined;
};

type RouteSetLike = {
  start?: unknown;
  end?: unknown;
  [key: string]: unknown;
};

export function useMarkerContextMenu(
  routeSet: Ref<RouteSetLike>,
  updateRoute: () => void,
  closeAllPopups: () => void,
) {
  const clickedLatLng = ref<LeafLet.LatLng | null>(null);
  const isFavorite = ref(false);

  const handleMarkerClick = async (event: LeafletMouseEvent) => {
    console.log('marker clicked', event);
    closeAllPopups();
    clickedLatLng.value = event.latlng;
    const resp = await reverseGeocodeRateLimited(Number(event.latlng.lat), Number(event.latlng.lng));
    isFavorite.value = !!resp.favorite;
    LeafLet.DomEvent.stopPropagation(event.originalEvent);
  };

  const setStartRoute = () => {
    if (!clickedLatLng.value) return;
    closeAllPopups();
    (routeSet.value as RouteSet).start = clickedLatLng.value;
    console.log('setStartRoute: ', routeSet.value.start);
  };

  const setEndRoute = () => {
    if (!clickedLatLng.value) return;
    (routeSet.value as RouteSet).end = clickedLatLng.value;
    closeAllPopups();
    console.log('setEndRoute: ', routeSet.value.end);
    updateRoute();
    console.log('updating Route');
  };

  return {
    isFavorite,
    clickedLatLng,
    handleMarkerClick,
    setStartRoute,
    setEndRoute,
  };
}
