import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import http from "../../lib/https";
import { toast } from "sonner";

interface Vehicle {
    id:number;
    name:string;
    brand:string;
    imageUrl:string;
    
}
interface VehicleState {
	vehicles:Vehicle[];
	loading: boolean;
	error: string | null;
}
const initialState: VehicleState = {
	vehicles: [],
	loading: false,
	error: null,
};

export const vehicleList = createAsyncThunk<Vehicle, void, { rejectValue: string }>(
	"fetchVehicles",
	async (_, { rejectWithValue }) => {
		try {
			const token = localStorage?.getItem("authToken");
			if (!token) throw new Error("No token found");

			const response = await http.get("/");

			if (!response.data?.data) throw new Error("Invalid API response");

			return response.data.data;
		} catch (error: any) {
			toast.error("Error Fetching Profile" + error);
			return rejectWithValue(
				error?.response?.data?.message || "An error occurred"
			);
		}
	}
);

//Add Vehicle
export const addVehicle = createAsyncThunk<
	Vehicle,
	{
		name: string;
		brand: string;
		imageUrl: string;
	},
	{ rejectValue: string }
>("/AddVehicle", async (data, { rejectWithValue }) => {
	try {
		const response = await http.post("/", data);
		return response.data;
	} catch (error: any) {
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});


// Update Vehicle details
export const updateVehicle = createAsyncThunk(
	"updateVehicle",
	async ({ id, ...vehicleData }: Vehicle, { rejectWithValue }) => {
		try {
			const response = await http.put(`/${id}`, vehicleData);
			toast.success("Vehicle Deatils updated successfully");
			return response?.data;
		} catch (error: any) {
			toast.error("Error updating the user: " + error);
			return rejectWithValue(
				error.response?.data?.message || "An error occurred"
			);
		}
	}
);
const vehicleSlice = createSlice({
	name: "vehicle",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			.addCase(vehicleList.pending, (state) => {
				state.loading = true;
				state.error = null;
			})
			.addCase(
				vehicleList.fulfilled,
				(state, action: PayloadAction<Vehicle[]>) => {
					state.loading = false;
					state.vehicles = action.payload;
				}
			)
			.addCase(vehicleList.rejected, (state, action) => {
				state.loading = false;
				state.error = action.error.message || "Failed to fetch users";
			})
			.addCase(addVehicle.pending, (state) => {
				state.loading = true;
				// state.error = null;
			})
			.addCase(
				addVehicle.fulfilled,
				(state, action: PayloadAction<Vehicle>) => {
					state.loading = false;
					state.vehicles.push(action.payload);
				}
			)
			.addCase(
				addVehicle.rejected,
				(state, action: PayloadAction<string | undefined>) => {
					state.loading = false;
				}
			)
			.addCase(updateVehicle.pending, (state) => {
				state.loading = true;
			})
			.addCase(updateVehicle.fulfilled, (state, action) => {
				state.loading = false;
				state.error = action.payload;
			})
			.addCase(updateVehicle.rejected, (state) => {
				state.loading = false;
			});
	},
});

export default vehicleSlice.reducer;
