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

// Define TypeScript types
interface User {
	id: number;
	name: string;
	email: string;
	phone?: string;
	// location?: string;
	// managerAssigned?: string;
	// vehicle?: string;
	password:string;
}

interface UserState {
	users: User[];
	loading: boolean;
	error: string | null;
}

// Initial state
const initialState: UserState = {
	users: [],
	loading: false,
	error: null,
};

// Async thunk to fetch user list
// export const userList = createAsyncThunk<User[]>("users/fetchUsers", async () => {
// 	try {
// 		const response = await axios.get<User[]>("/api/users"); // Adjust the API endpoint as needed
// 		return response.data;
// 	} catch (error: any) {
// 		throw new Error(error.response?.data?.message || "Failed to fetch users");
// 	}
// });
export const userList = createAsyncThunk<User, void, { rejectValue: string }>(
	"fetchUsers",
	async (_, { rejectWithValue }) => {
		try {
			const token = localStorage?.getItem("authToken");
			if (!token) throw new Error("No token found");

			const response = await http.get("users-list");

			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"
			);
		}
	}
);

//Create User
export const createUser = createAsyncThunk<
	User,
	{
		name: string;
		email: string;
		password: string;
		phone: string;
		
		// location?: string;
		// managerAssigned?: string;
		// vehicle?: string;
	},
	{ rejectValue: string }
>("/CreateUser", async (data, { rejectWithValue }) => {
	try {
		const response = await http.post("create-user", data);
		return response.data;
	} catch (error: any) {
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

const userSlice = createSlice({
	name: "fetchUsers",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			.addCase(userList.pending, (state) => {
				state.loading = true;
				state.error = null;
			})
			.addCase(
				userList.fulfilled,
				(state, action: PayloadAction<User[]>) => {
					state.loading = false;
					state.users = action.payload;
				}
			)
			.addCase(userList.rejected, (state, action) => {
				state.loading = false;
				state.error = action.error.message || "Failed to fetch users";
			})
			.addCase(createUser.pending, (state) => {
				state.loading = true;
				// state.error = null;
			})
			.addCase(
				createUser.fulfilled,
				(state, action: PayloadAction<User>) => {
					state.loading = false;
					state.users.push(action.payload);
				}
			)
			.addCase(
				createUser.rejected,
				(state, action: PayloadAction<string | undefined>) => {
					state.loading = false;
				}
			);
	},
});

export default userSlice.reducer;
