import { create } from 'zustand';
import { geolocEndpoints } from '../endpoints/geolocHistory';
import axiosInstance from '@/utils/axios';
import {
  GeolocHistoryFilterParams,
  IGeolocHistory,
  IGeolocHistoryPageable,
} from '@/shared/types/geoloc';

type GeolocHistoryStore = {
  geolocData: IGeolocHistory | null;
  geolocDataTrips: IGeolocHistory | null;
  geolocsData: IGeolocHistoryPageable | null;
  loading: boolean;
  error: string | null;

  getGeolocData: (params?: GeolocHistoryFilterParams) => Promise<void>;
  getGeolocDataById: (id: number) => Promise<IGeolocHistory | null>;
  resetGeolocData: () => void;
};

export const useGeolocHistoryStore = create<GeolocHistoryStore>((set) => ({
  geolocData: null,
  geolocDataTrips: null,
  geolocsData: null,
  loading: false,
  error: null,

  getGeolocData: async (params = {}) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<IGeolocHistoryPageable>(
        geolocEndpoints.geoloc.getGeolocDataHistory,
        { params }
      );
      set({ geolocsData: response.data, loading: false });
    } catch (error: any) {
      set({
        error:
          error?.response?.data?.message ||
          error.message ||
          'Erreur lors du chargement de l’historique',
        loading: false,
      });
    }
  },

  getGeolocDataById: async (id: number) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<IGeolocHistory>(
        geolocEndpoints.geoloc.getGeolocDataById(id)
      );
      set({ geolocDataTrips: response.data, loading: false });
      return response.data;
    } catch (error: any) {
      set({
        error:
          error?.response?.data?.message || error.message || 'Erreur lors du chargement du trajet',
        loading: false,
      });
      return null;
    }
  },

  resetGeolocData: () => {
    set({
      geolocData: null,
      geolocDataTrips: null,
      error: null,
    });
  },
}));
