import axiosInstance from "@/utils/axios";
import { create } from "zustand";
import { userEndpoints } from "../endpoints/user";
import { IPassengerList, SearchPassengerParams } from "@/shared/types/passenger";
import { endpoints } from "../endpoints/admin-service";

type PassengerStore = {
    passengers: IPassengerList[];
    passenger: IPassengerList | null;
    loading: boolean;
    error: string | null;
    totalElements: number;
    searchPassengers: (params?: SearchPassengerParams) => Promise<void>;
    addPassenger: (passenger: IPassengerList) => Promise<void>;
    updatePassenger: (passenger: IPassengerList) => Promise<void>;
    toggleArchive: (id: string) => Promise<void>;
};

export const usePassengerStore = create<PassengerStore>((set) => ({
    passengers: [],
    passenger: null,
    loading: false,
    error: null,
    totalElements: 0,

    searchPassengers: async (params) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(userEndpoints.user.passenger.getAllPassengers, {
                params,
            });

            const { content, totalElements } = response.data;
            set({
                passengers: content,
                totalElements,
                loading: false,
            });
        } catch (error: any) {
            set({
                error: error.message || 'Failed to search passengers',
                loading: false,
            });
        }
    },

    addPassenger: async (passenger) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(userEndpoints.user.passenger.addPassenger, passenger);
            set({ loading: false });
        } catch (error: any) {
            set({
                error: error.message || 'Failed to add passenger',
                loading: false,
            });
        }
    },

    updatePassenger: async (passenger) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(userEndpoints.user.passenger.updatePassenger, passenger);
            set({ loading: false });
        } catch (error: any) {
            set({
                error: error.message || 'Failed to update passenger',
                loading: false,
            });
        }
    },

    toggleArchive: async (id: string) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post<boolean>(userEndpoints.user.passenger.toggleArchive(id));
            set((state) => ({
                passengers: state.passengers.map((c) => (c.id === id ? { ...c, archived: !c.archived } : c)),
                loading: false,
            }));
        } catch (error: any) {
            set({
                error: error.message || 'Failed to toggle archive',
                loading: false,
            });
        }
    },
}));
