import { create } from "zustand";
import axiosInstance from "@/utils/axios";
import { AddPassengerToCircuit, AddPassengersToCircuitResponse, PassengerCircuitSearchDTO, GetPassengerDetailsRequestDTO, GetPassengerDetailsResponseDTO } from "@/shared/types/circuit";
import { circuitEndpoints } from "../../endpoints/circuit";
import { CircuitAssignmentRequest } from "@/shared/types/circuit";
import { userEndpoints } from "../../endpoints/user";

type PassengersCircuitStore = {
  loading: boolean;
  loadingPassengers: boolean;
  loadingPassengerDetails: boolean;
  error: string | null;
  addedPassengers: AddPassengersToCircuitResponse[];
  passengersWithNoCircuit: PassengerCircuitSearchDTO[];
  addPassengersToCircuit: (payload: AddPassengerToCircuit) => Promise<void>;
  getPassengersOfCircuit: (circuitId: string) => Promise<void>;
  searchPassengersWithNoCircuit: (keyword?: string) => Promise<void>;
  assignCircuitToRepresentatives: (request: CircuitAssignmentRequest) => Promise<string[]>;
  cancelCircuitAssignmentForRepresentatives: (passengerIds: number[]) => Promise<string>;
  removePassengerFromCircuit: (request: { circuitId: string; passengerId: number }) => Promise<void>;
  getPassengerDetails: (request: GetPassengerDetailsRequestDTO) => Promise<GetPassengerDetailsResponseDTO>;
};

export const usePassengersCircuitStore = create<PassengersCircuitStore>((set,get) => ({
  loading: false,
  loadingPassengers: false,
  error: null,
  addedPassengers: [],
  passengersWithNoCircuit: [],
  addPassengersToCircuit: async (payload) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post<AddPassengersToCircuitResponse[]>(
        circuitEndpoints.circuit.addPassengers,
        payload
      );
      const { getPassengersOfCircuit } = get();
      await getPassengersOfCircuit(payload.circuitId);
      set({ 
        loading: false, 
      });
    } catch (error: any) {
      set({
        error: error.message || "Erreur lors de l'ajout des usagers au circuit",
        loading: false,
      });
      throw error;
    }
  },
  getPassengersOfCircuit: async (circuitId: string) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<AddPassengersToCircuitResponse[]>(
        circuitEndpoints.circuit.ammendment.getPassengersOfCircuit(circuitId)
      );
      set({ 
        loading: false, 
        addedPassengers: response.data 
      });
    } catch (error: any) {
      set({
        error: error.message || "Erreur lors de la récupération des usagers du circuit",
        loading: false,
        addedPassengers: [],
      });
      throw error;
    }
  },
  searchPassengersWithNoCircuit: async (keyword?: string) => {
    set({ loadingPassengers: true, error: null });
    try {
      const response = await axiosInstance.get<PassengerCircuitSearchDTO[]>(
        userEndpoints.user.passenger.searchPassengersWithNoCircuit,
        {params: {keyword}}
      );
      set({ 
        loadingPassengers: false, 
        passengersWithNoCircuit: response.data 
      });
    } catch (error: any) {
      set({
        error: error.message || "Erreur lors de la recherche des usagers sans circuit",
        loadingPassengers: false,
      });
      throw error;
    }
  },
  assignCircuitToRepresentatives: async (request: CircuitAssignmentRequest) => {
    set({ loading: true, error: null });
    try {
        const response = await axiosInstance.post<string[]>(
            userEndpoints.user.passenger.assignCircuitToRepresentatives,
            request
        );
        set({ loading: false });
        return response.data;
    } catch (error: any) {
        set({
            error: error.message || 'Échec de l\'assignation du circuit aux représentants',
            loading: false,
        });
        throw error;
    }
  },

  cancelCircuitAssignmentForRepresentatives: async (passengerIds: number[]) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.post<string>(
                userEndpoints.user.passenger.cancelCircuitAssignmentForRepresentatives,
                passengerIds
            );
            set({ loading: false });
            return response.data;
        } catch (error: any) {
            set({
                error: error.message || 'Échec de l\'annulation de l\'assignation du circuit aux représentants',
                loading: false,
            });
            throw error;
        }
    },

  removePassengerFromCircuit: async (payload: { circuitId: string; passengerId: number }) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post<void>(
        circuitEndpoints.circuit.removePassengers,
        payload
      );
      set((state) => ({
        loading: false,
        addedPassengers: state.addedPassengers.filter((p) => p.passengerId !== payload.passengerId),
      }));
    } catch (error: any) {
      set({
        error: error.message || "Échec de la désaffectation de l'usager du circuit",
        loading: false,
      });
      throw error;
    }
  },
  loadingPassengerDetails: false,
  getPassengerDetails: async (request: GetPassengerDetailsRequestDTO) => {
    set({ loadingPassengerDetails: true, error: null });
    try {
      const response = await axiosInstance.post<GetPassengerDetailsResponseDTO>(
        userEndpoints.user.passenger.getPassengerDetails,
        request
      );
      
      set({ loadingPassengerDetails: false });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || "Erreur lors de la récupération des détails du passager",
        loadingPassengerDetails: false,
      });
      throw error;
    }
  },

}));