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

// Define interfaces for the dashboard data structure
interface CarPortCount {
	carPort: string;
	count: number;
}

interface TopStation {
	stationId: number;
	count: string;
	ChargingStation: {
		id: number;
		name: string;
	};
}

interface DashboardState {
	totalAdmins: number;
	totalManagers: number;
	totalUsers: number;
	totalStations: number;
	carPortCounts: CarPortCount[];
	topStations: TopStation[];
	totalBookings: number;
	loading: boolean;
	error: string | null;
}

const initialState: DashboardState = {
	totalAdmins: 0,
	totalManagers: 0,
	totalUsers: 0,
	totalStations: 0,
	carPortCounts: [],
	topStations: [],
	totalBookings: 0,
	loading: false,
	error: null,
};

// Async thunk for fetching dashboard data
export const fetchDashboardData = createAsyncThunk<
	DashboardState,
	{ startDateBookings?: string; endDateBookings?: string; startDateStations?: string; endDateStations?: string}, // Accept startDate and endDate as optional parameters
	{ rejectValue: string }
>("dashboard/fetchDashboardData", async (params, { rejectWithValue }) => {
	try {
		const response = await http.get("/dashboard", { params }); // Pass startDate and endDate as query params
		return response.data;
	} catch (error: any) {
		toast.error("Error Fetching Dashboard Data: " + error.message);
		return rejectWithValue(
			error?.response?.data?.message || "An error occurred"
		);
	}
});

// Redux slice for the dashboard
const dashboardSlice = createSlice({
	name: "dashboard",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			.addCase(fetchDashboardData.pending, (state) => {
				state.loading = true;
				state.error = null;
			})
			.addCase(
				fetchDashboardData.fulfilled,
				(state, action: PayloadAction<DashboardState>) => {
					state.loading = false;
					state.totalAdmins = action.payload.totalAdmins;
					state.totalManagers = action.payload.totalManagers;
					state.totalUsers = action.payload.totalUsers;
					state.totalStations = action.payload.totalStations;
					state.carPortCounts = action.payload.carPortCounts;
					state.topStations = action.payload.topStations;
					state.totalBookings = action.payload.totalBookings;
				}
               
			)
			.addCase(fetchDashboardData.rejected, (state, action) => {
				state.loading = false;
				state.error =
					action.payload || "Failed to fetch dashboard data";
			});
	},
});

export default dashboardSlice.reducer;
