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

// Define the Manager interface based on the payload

interface Manager {
	id: number;
	name: string;
	email: string;
	phone: string;
	stationId: string;
	chargingStation:{name:string, registeredAddress:string};
}

interface ManagerState {
	managers: Manager[];
	loading: boolean;
	error: string | null;
}

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

// Fetch Manager List (Async Thunk)
export const managerList = createAsyncThunk<
	Manager[],
	void,
	{ rejectValue: string }
>("fetchManagers", async (_, { rejectWithValue }) => {
	try {
		const token = localStorage?.getItem("authToken");
		if (!token) throw new Error("No token found");

		const response = await http.get("/manager-list");
		if (!response.data?.data) throw new Error("Invalid API response");
		return response.data.data;
	} catch (error: any) {
		toast.error("Error Fetching Managers: " + error.message);
		return rejectWithValue(
			error?.response?.data?.message || "An error occurred"
		);
	}
});
export const AllmanagerList = createAsyncThunk<
	Manager[],
	void,
	{ rejectValue: string }
>("fetchAllManagers", async (_, { rejectWithValue }) => {
	try {
		const token = localStorage?.getItem("authToken");
		if (!token) throw new Error("No token found");

		const response = await http.get("/all-manager-list");
		if (!response.data?.data) throw new Error("Invalid API response");
		return response.data.data;
	} catch (error: any) {
		toast.error("Error Fetching Managers: " + error.message);
		return rejectWithValue(
			error?.response?.data?.message || "An error occurred"
		);
	}
});
// Create Manager (Async Thunk)
export const addManager = createAsyncThunk<
	Manager,
	{
		name: string;
		email: string;
		phone: string;
		stationId: string;
	},
	{ rejectValue: string }
>("addManager", async (data, { rejectWithValue }) => {
	try {
		const response = await http.post("create-manager", data);
		toast.success("Manager created successfully");
		return response.data?.data;
	} catch (error: any) {
		toast.error("Error creating manager: " + error.response?.data?.message);
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

// Update Manager (Async Thunk)
export const updateManager = createAsyncThunk<
	Manager,
	{ id: number; managerData: Manager },
	{ rejectValue: string }
>("updateManager", async ({ id, managerData }, { rejectWithValue }) => {
	if (!id) {
		return rejectWithValue("Manager ID is required.");
	}
	try {
		const response = await http.put(`/update-manager/${id}`, managerData);
		toast.success("Manager updated successfully");
		return response?.data;
	} catch (error: any) {
		toast.error("Error updating manager: " + error.message);
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

// Delete Manager (Async Thunk)
export const deleteManager = createAsyncThunk<
	string,
	string,
	{ rejectValue: string }
>("deleteManager", async (id, { rejectWithValue }) => {
	try {
		await http.delete(`/delete-manager/${id}`);
		toast.success("Manager deleted successfully!");
		return id;
	} catch (error: any) {
		toast.error("Error deleting manager: " + error.message);
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

// Create Slice
const managerSlice = createSlice({
	name: "manager",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			// Fetch Managers
			.addCase(managerList.pending, (state) => {
				state.loading = true;
				state.error = null;
			})
			.addCase(
				managerList.fulfilled,
				(state, action: PayloadAction<Manager[]>) => {
					state.loading = false;
					state.managers = action.payload;
				}
			)
			.addCase(managerList.rejected, (state, action) => {
				state.loading = false;
				state.error = action.payload || "Failed to fetch managers";
			})
			.addCase(AllmanagerList.pending, (state) => {
				state.loading = true;
				state.error = null;
			})
			.addCase(
				AllmanagerList.fulfilled,
				(state, action: PayloadAction<Manager[]>) => {
					state.loading = false;
					state.managers = action.payload;
				}
			)
			.addCase(AllmanagerList.rejected, (state, action) => {
				state.loading = false;
				state.error = action.payload || "Failed to fetch managers";
			})

			// Add Manager
			.addCase(addManager.pending, (state) => {
				state.loading = true;
			})
			.addCase(
				addManager.fulfilled,
				(state, action: PayloadAction<Manager>) => {
					state.loading = false;
					state.managers.push(action.payload);
				}
			)
			.addCase(addManager.rejected, (state, action) => {
				state.loading = false;
				state.error = action.payload || "Failed to add manager";
			})

			// Update Manager
			.addCase(updateManager.pending, (state) => {
				state.loading = true;
			})
			.addCase(updateManager.fulfilled, (state, action) => {
				state.loading = false;
				const updatedManager = action.payload;
				const index = state.managers.findIndex(
					(manager) => manager.id === updatedManager.id
				);
				if (index !== -1) {
					state.managers[index] = updatedManager; // Update the manager in the state
				}
			})
			.addCase(updateManager.rejected, (state, action) => {
				state.loading = false;
				state.error = action.payload || "Failed to update manager";
			})

			// Delete Manager
			.addCase(deleteManager.pending, (state) => {
				state.loading = true;
			})
			.addCase(deleteManager.fulfilled, (state, action) => {
				state.loading = false;
				state.managers = state.managers.filter(
					(manager) => String(manager.id) !== String(action.payload)
				);
			})
			.addCase(deleteManager.rejected, (state, action) => {
				state.loading = false;
				state.error = action.payload || "Failed to delete manager";
			});
	},
});

export default managerSlice.reducer;
