import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import http from "../../lib/https";
import { toast } from "sonner";
interface StationDetails {
	id: string;
	stationAddress: string;
	stationName: string;
	managerId?: number;
	stationId?: number;
	connectorType: string;
	power: number;
	price: number;
	available: boolean;
}

interface StationDetailState {
	stationDetails: StationDetails[];
	loading: boolean;
	error: string | null;
}

const initialState: StationDetailState = {
	stationDetails: [],
	loading: false,
	error: null,
};

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

		const response = await http.get("/get-station-details");
		if (!response.data?.data) throw new Error("Invalid API response");
		return response.data.data;
	} catch (error: any) {
		toast.error("Error Fetching Station Details: " + error.message);
		return rejectWithValue(
			error?.response?.data?.message || "An error occurred"
		);
	}
});

// Create Manager (Async Thunk)
export const addStationDetails = createAsyncThunk<
	StationDetails,
	{
		connectorType: string;
		power: number; // Changed to number
		price: number; // Changed to number
		available: boolean;
	},
	{ rejectValue: string }
>("addManager", async (data, { rejectWithValue }) => {
	try {
		const response = await http.post("add-station-details", data);
		toast.success("Station details created successfully");
		return response.data?.data;
	} catch (error: any) {
		toast.error(
			"Error creating Station details: " + error.response?.data?.message
		);
		return rejectWithValue(
			error.response?.data?.message || "An error occurred"
		);
	}
});

// Update Manager (Async Thunk)
export const updateStationDetails = createAsyncThunk<
	StationDetails,
	{
		id: string;
		connectorType: string;
		power: number;
		price: number;
		available: boolean;
	},
	{ rejectValue: string }
>(
	"updateManagerStationDetails",
	async ({ id, ...managerStationData }, { rejectWithValue }) => {
		try {
			const response = await http.patch(
				`/update-station-details/${id}`,
				managerStationData,

			);
			toast.success("Station Details updated successfully");
			return response.data; // Return the updated data
		} catch (error: any) {
			toast.error("Error updating station details: " + error.message);
			return rejectWithValue(
				error.response?.data?.message || "An error occurred"
			);
		}
	}
);

// Delete Manager (Async Thunk)
export const deleteStationDetails = createAsyncThunk<
	string,
	string,
	{ rejectValue: string }
>("deleteManagerStationDetails", async (id, { rejectWithValue }) => {
	try {
		await http.delete(`/remove-station-details/${id}`);
		toast.success("Station details 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 managerStationSlice = createSlice({
	name: "manager-station",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			// Fetch Station Details
			.addCase(stationDetailList.pending, (state) => {
				state.loading = true;
				state.error = null;
			})
			.addCase(
				stationDetailList.fulfilled,
				(state, action: PayloadAction<StationDetails[]>) => {
					state.loading = false;
					state.stationDetails = action.payload;
				}
			)
			.addCase(stationDetailList.rejected, (state, action) => {
				state.loading = false;
				state.error =
					action.payload || "Failed to fetch station details";
			})

			// Add Station Details
			.addCase(addStationDetails.pending, (state) => {
				state.loading = true;
			})
			.addCase(
				addStationDetails.fulfilled,
				(state, action: PayloadAction<StationDetails>) => {
					state.loading = false;
					state.stationDetails.push(action.payload);
				}
			)
			.addCase(addStationDetails.rejected, (state, action) => {
				state.loading = false;
				state.error = action.payload || "Failed to add station details";
			})

			// Update Station Details
			.addCase(updateStationDetails.pending, (state) => {
				state.loading = true;
			})
			.addCase(
				updateStationDetails.fulfilled,
				(state, action: PayloadAction<StationDetails>) => {
					state.loading = false;

					// Update the station details in the array
					const index = state.stationDetails.findIndex(
						(station) => station.id === action.payload.id
					);

					if (index !== -1) {
						// Only update the fields that have changed
						state.stationDetails[index] = action.payload; // Merge the updated fields
					}
				}
			)
			.addCase(updateStationDetails.rejected, (state, action) => {
				state.loading = false;
				state.error =
					action.payload || "Failed to update station details";
			})

			// Delete Station Details
			.addCase(deleteStationDetails.pending, (state) => {
				state.loading = true;
			})
			.addCase(
				deleteStationDetails.fulfilled,
				(state, action: PayloadAction<string>) => {
					state.loading = false;
					state.stationDetails = state.stationDetails.filter(
						(station) =>
							String(station.id) !== String(action.payload)
					);
					if (state.stationDetails) {
						state.stationDetails = state.stationDetails.filter(
							(station) =>
								String(station.id) !== String(action.payload)
						);
					}
				}
			)
			
			.addCase(deleteStationDetails.rejected, (state, action) => {
				state.loading = false;
				state.error =
					action.payload || "Failed to delete station details";
			});
	},
});

export default managerStationSlice.reducer;
