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

// Interfaces
interface User {
	id: string;
	name: string;
	email: string;
	role: string;
	phone: string;
	registeredAddress: string;
}

interface Admin {
	Admins: any;
	id: string;
	name: string;
	userType: string;
	email: string;
	phone: string;
	registeredAddress: string;
}

interface AuthState {
	user: User | null;
	admins: Admin[];
	isAuthenticated: boolean;
	isLoading: boolean;
	// error: string | null;
	token: string | null;
}

// Fetch Admin List
export const adminList = createAsyncThunk<
	Admin[],
	void,
	{ rejectValue: string }
>("FetchAdminList", async (_, { rejectWithValue }) => {
	try {
		const response = await http.get("/admin-list");
		return response?.data?.data;
	} catch (error: any) {
		toast.error("Error fetching users list" + error);

		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

// Delete Admin
export const deleteAdmin = createAsyncThunk<
	string,
	string,
	{ rejectValue: string }
>("deleteAdmin", async (id, { rejectWithValue }) => {
	try {
		const response = await http.delete(`/delete-admin/${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"
		);
	}
});

export const createAdmin = createAsyncThunk<
	User,
	{
		name: string;
		email: string;
		phone: string;
		registeredAddress: string;
	},
	{ rejectValue: string }
>("/create-admin", async (data, { rejectWithValue }) => {
	try {
		const response = await http.post("/create-admin", data);
		toast.success("Admin created successfully");
		return response.data;
	} catch (error: any) {
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

// Update Admin
export const updateAdmin = createAsyncThunk(
	"updateAdmin",
	async ({ id, ...userData }: User, { rejectWithValue }) => {
		try {
			const response = await http.put(`/update-admin/${id}`, userData);
			toast.success("Admin 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 initialState: AuthState = {
	user: null,
	admins: [],
	isAuthenticated: false,
	isLoading: false,
	// error: null,
	token: null,
};

const adminSlice = createSlice({
	name: "admin",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			.addCase(adminList.pending, (state) => {
				state.isLoading = true;
				// state.error = null;
			})
			.addCase(
				adminList.fulfilled,
				(state, action: PayloadAction<Admin[]>) => {
					state.isLoading = false;
					state.admins = action.payload;
				}
			)
			.addCase(adminList.rejected, (state) => {
				state.isLoading = false;
				// state.error = action.payload || "An error occurred";
			})
			.addCase(deleteAdmin.pending, (state) => {
				state.isLoading = true;
			})
			.addCase(deleteAdmin.fulfilled, (state, action) => {
				state.isLoading = false;
				state.admins = state.admins.filter(
					(admin) => String(admin.id) !== String(action.payload)
				);
			})
			.addCase(deleteAdmin.rejected, (state) => {
				state.isLoading = false;
			})
			.addCase(updateAdmin.pending, (state) => {
				state.isLoading = true;
			})
			.addCase(updateAdmin.fulfilled, (state, action) => {
				
				state.isLoading = false;
			})
			.addCase(updateAdmin.rejected, (state) => {
				state.isLoading = false;
			})
			.addCase(createAdmin.pending, (state) => {
				state.isLoading = true;
				// state.error = null;
			})
			.addCase(
				createAdmin.fulfilled,
				(state, action: PayloadAction<User>) => {
					state.isLoading = false;
					state.admins.push(action.payload);
				}
			)
			.addCase(
				createAdmin.rejected,
				(state, action: PayloadAction<string | undefined>) => {
					state.isLoading = false;
				}
			);
	},
});

export default adminSlice.reducer;
