import { DEFAULT_LOCALE } from "@providers/LocalizationProvider";
import { createSlice } from "@reduxjs/toolkit";

const bungeeLocalStore =
	typeof window !== "undefined"
		? JSON.parse(localStorage.getItem("bungee") || "{}")
		: {};

const initialState: SettingsParams = {
	isSettingsVisible: false,
	sound: bungeeLocalStore?.settings?.sound || false,
	dynamicSlippage: bungeeLocalStore?.settings?.dynamicSlippage ?? true,
	slippage: bungeeLocalStore?.settings?.slippage,
	language: bungeeLocalStore?.settings?.locale || DEFAULT_LOCALE,
	notifications: bungeeLocalStore?.settings?.notifications || false,
	manualMode: bungeeLocalStore?.settings?.manualMode || false,
};

export function updateLocalStorage(
	section: string,
	key: string,
	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	value: any,
) {
	let bungee =
		typeof window !== "undefined"
			? JSON.parse(localStorage.getItem("bungee") || "{}")
			: {};
	if (!bungee) bungee = {};
	if (!bungee[section]) bungee[section] = {};

	bungee = {
		...bungee,
		[section]: {
			...bungee[section],
			[key]: value,
		},
	};

	localStorage.setItem("bungee", JSON.stringify(bungee));
}

const settingsSlice = createSlice({
	name: "settings",
	initialState,
	reducers: {
		toggleSettingsModal: (state, action) => {
			state.isSettingsVisible = action.payload;
		},
		setSound: (state, action) => {
			state.sound = action.payload;
			updateLocalStorage("settings", "sound", action.payload);
		},
		toggleDynamicSlippage: (state, action) => {
			state.dynamicSlippage = action.payload;
			updateLocalStorage("settings", "dynamicSlippage", action.payload);
		},
		setSlippage: (state, action) => {
			state.slippage = action.payload;
			updateLocalStorage("settings", "slippage", action.payload);
		},
		setLanguage: (state, action) => {
			state.language = action.payload;
			updateLocalStorage("settings", "locale", action.payload);
		},
		enableNotifications: (state, action) => {
			state.notifications = action.payload;
			updateLocalStorage("settings", "notifications", action.payload);
		},
		toggleManualMode: (state, action) => {
			state.manualMode = action.payload;
			updateLocalStorage("settings", "manualMode", action.payload);
		},
	},
});

export interface SettingsParams {
	isSettingsVisible: boolean;
	sound: boolean;
	dynamicSlippage: boolean;
	slippage: string;
	language: string;
	notifications: boolean;
	manualMode: boolean;
}

export const {
	toggleSettingsModal,
	setSound,
	toggleDynamicSlippage,
	setSlippage,
	setLanguage,
	enableNotifications,
	toggleManualMode,
} = settingsSlice.actions;
export default settingsSlice.reducer;
