import { IDisplayMap } from "@/shared/types/map-type";
import axios from "axios";
import { create } from "zustand";

interface IMapStore {
  setLatLng: (latLng: { lat: number; lng: number }) => void;
  latLng: { lat: number; lng: number };
  getLocations: (query: string) => void;
  searchData: IDisplayMap[];
  setDisplayLocation: (display_location: string) => void;
  display_location: string;
}

export const useMapStore = create<IMapStore>((set) => ({
  searchData: [],
  display_location: "",
  latLng: {
    lat: 42.8746,
    lng: 74.606,
  },
  getLocations: async (query: string = "") => {
    const params: Record<string, any> = {
      q: query,
      format: "json",
      addressdetails: 1,
      polygon_geojson: 0,
    };
    const queryString = new URLSearchParams(params).toString();
    const url = `https://nominatim.openstreetmap.org/search?${queryString}`;

    const response = await axios.get<IDisplayMap[]>(url);

    const inKG = response.data.filter((location) => {
      return location.address.country_code.toLowerCase() === "kg";
    });

    set({ searchData: inKG });
  },
  setLatLng: (latLng: { lat: number; lng: number }) => {
    set({ latLng: latLng });
  },
  setDisplayLocation: (display_location: string) => {
    set({ display_location: display_location });
  },
}));
