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

// Define types for state
//Eknoor singh
//date:- 12-Feb-2025
//Token for the user has been declared
interface User {
	data: any;
	token: string | null;
	id: string;
	name: string;
	email: string;
	role: string;
	phone: string;
}

interface Admin {
	id: string;
	name: string;
	role: string;
	email: string;
	phone: string;
}

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

// Async thunk for login
export const loginUser = createAsyncThunk<
	User,
	{ email: string; password: string },
	{ rejectValue: string }
>("LoginUser", async ({ email, password }, { rejectWithValue }) => {
	try {
		// this is endpoint not action name
		//use below commented endpoint if using deployed backend........
		// const response = await http.post("admin/login", {

		const response = await http.post("/login", {
			email,
			password,
		});
		localStorage.setItem("authToken", response.data?.data?.token); // Save token
		toast.success(response.data?.message);
		return response.data;
	} catch (error: any) {
		console.log("Error logging in the user" + error);
		toast.error("LogIn Failed : User not Found!");
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

// Async thunk for register
export const registerUser = createAsyncThunk<
	User,
	{
		name: string;
		email: string;
		password: string;
		phone: string;
		// registeredAddress:string;
		role: string;
	},
	{ rejectValue: string }
>("SignUpUser", async (data, { rejectWithValue }) => {
	try {
		const response = await http.post("/signup", data);
		return response.data;
	} catch (error: any) {
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

const initialState: AuthState = {
	user: null,
	admins: [],
	isAuthenticated: false,
	isLoading: false,
	// error: null,
	token: null,
	role: null,
};

const authSlice = createSlice({
	name: "auth",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			// Login
			.addCase(loginUser.pending, (state) => {
				state.isLoading = true;
				// state.error = null;
			})
			.addCase(loginUser.fulfilled, (state, action) => {
				state.isLoading = false;
				state.isAuthenticated = true;
				state.user = action.payload.data;
				state.token = action.payload.data.token;
			})

			.addCase(
				loginUser.rejected,
				// (state, action: PayloadAction<string | undefined>) => {
				(state) => {
					state.isLoading = false;
					// state.error = action.payload || "An error occurred";
				}
			)
			// Register
			.addCase(registerUser.pending, (state) => {
				state.isLoading = true;
				// state.error = null;
			})
			.addCase(
				registerUser.fulfilled,
				(state, action: PayloadAction<User>) => {
					state.isLoading = false;
					state.isAuthenticated = true;
					state.user = action.payload;
				}
			)
			.addCase(
				registerUser.rejected,
				(state, action: PayloadAction<string | undefined>) => {
					state.isLoading = false;
					// state.error = action.payload || "An error occurred";
				}
			);
	},
});

export default authSlice.reducer;
