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

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

interface ManagerState {
	managers: Manager[];
	isLoading: boolean;
}

// Dummy API function placeholder
const dummyApiCall = async (response: any, delay = 500) =>
	new Promise((resolve) => setTimeout(() => resolve(response), delay));

// Fetch Manager List
export const fetchManagerList = createAsyncThunk<Manager[], void, { rejectValue: string }>(
	"fetchManagerList",
	async (_, { rejectWithValue }) => {
		try {
			const response: any = await dummyApiCall({ data: [{ id: "1", name: "John Doe", email: "john@example.com", role: "Manager", phone: "1234567890", registeredAddress: "Somewhere" }] });
			return response.data;
		} catch (error: any) {
			toast.error("Error fetching manager list: " + error);
			return rejectWithValue("An error occurred");
		}
	}
);

// Delete Manager
export const deleteManager = createAsyncThunk<string, string, { rejectValue: string }>(
	"deleteManager",
	async (id, { rejectWithValue }) => {
		try {
			await dummyApiCall(null);initialState
);

// Add Manager
export const addManager = createAsyncThunk<
	Manager,
	{ name: string; email: string; phone: string; registeredAddress: string },
	{ rejectValue: string }
>("addManager", async (data, { rejectWithValue }) => {
	try {
		const response: any = await dummyApiCall({ id: "2", ...data });
		return response;
	} catch (error: any) {
		return rejectWithValue("An error occurred");
	}
});

const initialState: ManagerState = {
	managers: [],
	isLoading: false,
};

const managerSlice = createSlice({
	name: "manager",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			.addCase(fetchManagerList.pending, (state) => {
				state.isLoading = true;
			})
			.addCase(fetchManagerList.fulfilled, (state, action: PayloadAction<Manager[]>) => {
				state.isLoading = false;
				state.managers = action.payload;
			})
			.addCase(fetchManagerList.rejected, (state) => {
				state.isLoading = false;
			})
			.addCase(deleteManager.pending, (state) => {
				state.isLoading = true;
			})
			.addCase(deleteManager.fulfilled, (state, action) => {
				state.isLoading = false;
				state.managers = state.managers.filter((manager) => manager.id !== action.payload);
			})
			.addCase(deleteManager.rejected, (state) => {
				state.isLoading = false;
			})
			.addCase(addManager.pending, (state) => {
				state.isLoading = true;
			})
			.addCase(addManager.fulfilled, (state, action) => {
				state.isLoading = false;
				state.managers.push(action.payload);
			})
			.addCase(addManager.rejected, (state) => {
				state.isLoading = false;
			});
	},
});

export default managerSlice.reducer;
