import React, { createContext, useContext, useMemo } from 'react';
import { MapMarker } from '@/types/trip-ui';
import { TripDataContext } from './TripDataContext';
import { TripTimelineContext } from './TripTimelineContext';
import { TripUIContext } from './TripUIContext';

interface TripMapContextType {
  allMapMarkers: MapMarker[];
  activeDayMapMarkers: MapMarker[];
  onMarkerClick: (markerId: string) => void;
  onMarkerHover: (markerId: string | null) => void;
  highlightPlace: (placeId: string | null) => void;
}

export const TripMapContext = createContext<TripMapContextType | undefined>(undefined);

export const TripMapProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { trip } = useContext(TripDataContext) || {};
  const { activeDay } = useContext(TripTimelineContext) || {};
  const { setSelectedPlaceId, setHoveredPlaceId, setHighlightedPlaceId } = useContext(TripUIContext) || {};

  const allMapMarkers = useMemo((): MapMarker[] => {
    if (!trip) return [];
    
    const markers: MapMarker[] = [];
    trip.days.forEach((day, dayIndex) => {
      day.places.forEach((place) => {
        markers.push({
          id: place.id,
          lat: place.position.lat,
          lng: place.position.lng,
          dayId: day.id,
          dayIndex,
          orderIndex: place.order_index,
          title: place.name,
        });
      });
    });
    
    return markers;
  }, [trip]);

  const activeDayMapMarkers = useMemo((): MapMarker[] => {
    if (!activeDay || !trip) return [];
    
    const dayIndex = trip.days.findIndex(d => d.id === activeDay.id) || 0;
    
    return activeDay.places.map((place) => ({
      id: place.id,
      lat: place.position.lat,
      lng: place.position.lng,
      dayId: activeDay.id,
      dayIndex,
      orderIndex: place.order_index,
      title: place.name,
    }));
  }, [activeDay, trip]);

  const onMarkerClick = (markerId: string) => {
    setSelectedPlaceId?.(markerId);
  };

  const onMarkerHover = (markerId: string | null) => {
    setHoveredPlaceId?.(markerId);
  };

  const highlightPlace = (placeId: string | null) => {
    setHighlightedPlaceId?.(placeId);
  };

  return (
    <TripMapContext.Provider value={{
      allMapMarkers,
      activeDayMapMarkers,
      onMarkerClick,
      onMarkerHover,
      highlightPlace
    }}>
      {children}
    </TripMapContext.Provider>
  );
};
