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,
	bungeeAutoRouting: true,
	sound: bungeeLocalStore?.settings?.sound || false,
	autoSlippage: bungeeLocalStore?.settings?.autoSlippage ?? true,
	slippage: bungeeLocalStore?.settings?.slippage,
	language: bungeeLocalStore?.settings?.locale || DEFAULT_LOCALE,
	notifications: bungeeLocalStore?.settings?.notifications || 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;
		},
		setBungeeAutoRouting: (state, action) => {
			state.bungeeAutoRouting = action.payload;
		},
		setSound: (state, action) => {
			state.sound = action.payload;
			updateLocalStorage("settings", "sound", action.payload);
		},
		toggleAutoSlippage: (state, action) => {
			state.autoSlippage = action.payload;
			updateLocalStorage("settings", "autoSlippage", 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);
		},
	},
});

export interface SettingsParams {
	isSettingsVisible: boolean;
	bungeeAutoRouting: boolean; // @todo: how do we disable this entirey? or Put it behind flag?
	sound: boolean;
	autoSlippage: boolean;
	slippage: string;
	language: string;
	notifications: boolean;
}

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