import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { TripCircuitDetails, TripCircuitDTO, TripDTO, TripListParams, ExportTripParams } from '@/shared/types/circuit';
import { circuitEndpoints } from '../../endpoints/circuit';

type TripCircuitStore = {
  loading: boolean;
  loadingTripsWithTripPoints:boolean;
  loadingPersonalizedTrips:boolean;
  loadingDetailsRegular: boolean;
  loadingDetailsCustomized: boolean;
  error: string | null;
  tripCircuits: TripCircuitDetails[];
  totalElements: number;
  tripCircuitById: TripCircuitDetails | null;
  tripList: TripDTO[];
  tripListTotalElements: number;
  tripsWithTripPoints: TripCircuitDTO[];
  personalizedTrips: TripCircuitDTO[];
  getTripCircuitById: (id: string, componentType?: 'regular' | 'customized') => Promise<TripCircuitDetails | null>;
  getAllTrips: (params?: TripListParams) => Promise<{ content: TripDTO[]; totalElements: number }>;
  getTripsWithTripPoints: (circuitId: string) => Promise<TripCircuitDTO[]>;
  getAmendmentTripsWithTripPoints: (amendmentCircuitId: string) => Promise<TripCircuitDTO[]>;
  getPersonalizedTrips: (circuitId: string) => Promise<TripCircuitDTO[]>;
  exportTrips: (params: ExportTripParams) => Promise<void>;
};

export const useTripCircuitStore = create<TripCircuitStore>((set) => ({
  loading: false,
  loadingTripsWithTripPoints:false,
  loadingPersonalizedTrips:false,
  loadingDetailsRegular: false,
  loadingDetailsCustomized: false,
  error: null,
  tripCircuits: [],
  totalElements: 0,
  tripCircuitById: null,
  tripList: [],
  tripListTotalElements: 0,
  tripsWithTripPoints: [],
  personalizedTrips: [],

  getTripCircuitById: async (id: string, componentType: 'regular' | 'customized' = 'regular') => {
    const loadingKey = componentType === 'regular' ? 'loadingDetailsRegular' : 'loadingDetailsCustomized';
    set({ [loadingKey]: true, error: null });
    try {
      const response = await axiosInstance.get<TripCircuitDetails>(
        circuitEndpoints.circuit.trip.getTripDetails(id)
      );
      set({
        [loadingKey]: false,
        tripCircuitById: response.data,
      });
      return response.data;
      } catch (error: any) {
      set({
        [loadingKey]: false,
        error: error.message || 'Erreur lors de la récupération du trip circuit par id',

      });
      throw error;
    }
  },

  getAllTrips: async (params?: TripListParams) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<{ content: TripDTO[]; totalElements: number }>(
        circuitEndpoints.circuit.trip.getAllTrips,
        { params }
      );
      set({
        loading: false,
        tripList: response.data.content,
        tripListTotalElements: response.data.totalElements,
      });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Erreur lors de la récupération des trips',
        loading: false,
      });
      throw error;
    }
  },
  getTripsWithTripPoints: async (circuitId: string) => {
    set({ loadingTripsWithTripPoints: true, error: null, tripsWithTripPoints: [] });
    try {
      const response = await axiosInstance.get<TripCircuitDTO[]>(
        circuitEndpoints.circuit.trip.getTrips(circuitId)
      );
      set({
        loadingTripsWithTripPoints: false,
        tripsWithTripPoints: response.data,
      });
      return response.data;
    } catch (error: any) {
      set({
        loadingTripsWithTripPoints: false,
        error: error.message || 'Erreur lors de la récupération des trajets temporaires',
      });
      throw error;
    }
  },

  getAmendmentTripsWithTripPoints: async (amendmentCircuitId: string) => {
    set({ loadingTripsWithTripPoints: true, error: null, tripsWithTripPoints: [] });
    try {
      const response = await axiosInstance.get<TripCircuitDTO[]>(
        circuitEndpoints.circuit.trip.getAmendmentTrips(amendmentCircuitId)
      );
      set({
        loadingTripsWithTripPoints: false,
        tripsWithTripPoints: response.data,
      });
      return response.data;
    } catch (error: any) {
      set({
        loadingTripsWithTripPoints: false,
        error: error.message || 'Erreur lors de la récupération des trajets d\'avenant',
      });
      throw error;
    }
  },

  getPersonalizedTrips: async (circuitId: string) => {
    set({ loadingPersonalizedTrips: true, error: null, tripsWithTripPoints: [] });
    try {
      const response = await axiosInstance.get<TripCircuitDTO[]>(
        circuitEndpoints.circuit.trip.getPersonalizedTrips(circuitId)
      );
      set({
        loadingPersonalizedTrips: false,
        personalizedTrips: response.data,
      });
      return response.data;
    } catch (error: any) {
      set({
        loadingPersonalizedTrips: false,
        error: error.message || 'Erreur lors de la récupération des trajets personnalisés',
      });
      throw error;
    }
  },

  exportTrips: async (params: ExportTripParams) => {
    set({ error: null });
    try {
      const response = await axiosInstance.post(
        circuitEndpoints.circuit.trip.export,
        null,
        { params }
      );

      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Erreur lors de l\'exportation des trajets',
        loading: false,
      });
      throw error;
    }
  },
}));
