import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { circuitEndpoints } from '../../endpoints/circuit';
import { IAddPointRequest } from '@/shared/types/trajet';
import { useCircuitStore } from './circuitStore';

type TripPointStore = {
    loading: boolean;
    error: string | null;
    addPointLoading: boolean;
    addPoint: (request: IAddPointRequest) => Promise<string>;
    swapSequenceOrder: (
        tripId: string,
        firstTripPointId: string,
        secondTripPointId: string
    ) => Promise<void>;
    updateArrivalTime: (tripPointId: string, newDepartureTime: string) => Promise<void>;
};

export const useTripPointStore = create<TripPointStore>((set) => ({
    loading: false,
    error: null,
    addPointLoading: false,
    addPoint: async (request: IAddPointRequest) => {
        set({ addPointLoading: true, error: null });
        try {
            const response = await axiosInstance.post(
                circuitEndpoints.circuit.tripPoint.addPoint,
                request
            );
            set({ addPointLoading: false });
            const updateTripsInBackground = async () => {
                try {
                    const { getTrips, lastUsedTripParams } = useCircuitStore.getState();
                    if (lastUsedTripParams) {
                        await getTrips(lastUsedTripParams);
                    }   
                } catch (error) {
                    console.error('Erreur mise à jour liste trajets:', error);
                }
            };
            
            updateTripsInBackground();
            return response.data.id;
        } catch (error: any) {
            set({
                addPointLoading: false,
                error: error.message || 'Erreur lors de l\'ajout du point',
            });
            throw error;
        }
    },

    swapSequenceOrder: async (tripId, firstTripPointId, secondTripPointId) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(
                circuitEndpoints.circuit.tripPoint.swapSequenceOrder(
                    tripId,
                    firstTripPointId,
                    secondTripPointId
                )
            );
            set({ loading: false });
        } catch (error: any) {
            set({
                loading: false,
                error: error.message || 'Erreur lors de la permutation des points de trajet',
            });
            throw error;
        }
    },

    updateArrivalTime: async (tripPointId, newArrivalTime) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(
                circuitEndpoints.circuit.tripPoint.updateArrivalTime(tripPointId, newArrivalTime)
            );
            set({ loading: false });
        } catch (error: any) {
            set({
                loading: false,
                error: error.message || 'Erreur lors de la mise à jour du temps de départ',
            });
            throw error;
        }
    },
}));
