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;

	
}

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

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

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

export const updateUser = createAsyncThunk(
	"updateUser",
	async ({ id, ...userData }: User, { rejectWithValue }) => {
		try {
			const response = await http.put(`/update-user/${id}`, userData);
			toast.success("User updated successfully");
			return response?.data;
		} catch (error: any) {
			toast.error("Error updating the user: " + error);
			return rejectWithValue(
				error.response?.data?.message || "An error occurred"
			);
		}
	}
);

export const deleteUser = createAsyncThunk<
	string,
	string,
	{ rejectValue: string }
>("deleteUser", async (id, { rejectWithValue }) => {
	try {
		const response = await http.delete(`/delete-user/${id}`);
		toast.success(response.data?.message);
		return id;
	} catch (error: any) {
		toast.error("Error deleting the user" + error);

		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;
				}
			)
			.addCase(updateUser.pending, (state) => {
				state.loading = true;
			})
			.addCase(updateUser.fulfilled, (state, action) => {
				state.loading = false;
			})
			.addCase(updateUser.rejected, (state) => {
				state.loading = false;
			})
			.addCase(deleteUser.pending, (state) => {
				state.loading = true;
			})
			.addCase(deleteUser.fulfilled, (state, action) => {
				state.loading = false;
				state.users = state.users.filter(
					(user) => String(user.id) !== String(action.payload)
				);
			})
			.addCase(deleteUser.rejected, (state) => {
				state.loading = false;
			});
	},
});

export default userSlice.reducer;
