import { create } from 'zustand';
import { RouteRecommendation } from '@/services/openai-service';
import { Place } from '@/utils/route-optimizer';

export interface POI {
  id: string;
  name: string;
  description?: string;
  latitude: number;
  longitude: number;
  category: 'restaurant' | 'attraction' | 'hotel' | 'activity' | 'nature' | 'shopping';
  rating?: number;
  imageUrl?: string;
}

interface RouteState {
  generatedRoute: RouteRecommendation | null;
  selectedPlaces: Place[];
  allPOIs: POI[];
  isGenerating: boolean;

  setGeneratedRoute: (route: RouteRecommendation) => void;
  addPlaceToRoute: (place: Place) => void;
  removePlaceFromRoute: (placeId: string) => void;
  updatePlaceLocation: (placeId: string, lat: number, lng: number) => void;
  reorderPlaces: (fromIndex: number, toIndex: number) => void;
  clearRoute: () => void;
  setAllPOIs: (pois: POI[]) => void;
}

export const useRouteStore = create<RouteState>((set) => ({
  generatedRoute: null,
  selectedPlaces: [],
  allPOIs: [],
  isGenerating: false,

  setGeneratedRoute: (route) => set({ generatedRoute: route }),

  addPlaceToRoute: (place) => set((state) => ({
    selectedPlaces: [...state.selectedPlaces, place]
  })),

  removePlaceFromRoute: (placeId) => set((state) => ({
    selectedPlaces: state.selectedPlaces.filter(p => p.id !== placeId)
  })),

  updatePlaceLocation: (placeId, lat, lng) => set((state) => ({
    selectedPlaces: state.selectedPlaces.map(p =>
      p.id === placeId ? { ...p, latitude: lat, longitude: lng } : p
    )
  })),

  reorderPlaces: (fromIndex, toIndex) => set((state) => {
    const places = [...state.selectedPlaces];
    const [removed] = places.splice(fromIndex, 1);
    places.splice(toIndex, 0, removed);
    return { selectedPlaces: places };
  }),

  clearRoute: () => set({ generatedRoute: null, selectedPlaces: [] }),

  setAllPOIs: (pois) => set({ allPOIs: pois })
}));
