import { createSlice } from "@reduxjs/toolkit";
import { RootState } from "redux/store";

interface ThemeState {
  themeName: string;
}

// Theme persistence utilities
const THEME_STORAGE_KEY = "theme";

const getInitialTheme = (): string => {
  if (typeof window !== "undefined") {
    try {
      const savedTheme = localStorage.getItem(THEME_STORAGE_KEY);
      // Validate theme value
      if (savedTheme === "light" || savedTheme === "dark") {
        return savedTheme;
      }
    } catch (error) {
      console.warn("Failed to read theme from localStorage:", error);
    }
  }
  return "light";
};

const saveThemeToStorage = (theme: string): void => {
  if (typeof window !== "undefined") {
    try {
      localStorage.setItem(THEME_STORAGE_KEY, theme);
    } catch (error) {
      console.warn("Failed to save theme to localStorage:", error);
    }
  }
};

const initialState: ThemeState = {
  themeName: getInitialTheme(),
};

const themeSlice = createSlice({
  name: "theme",
  initialState,
  reducers: {
    toggleTheme: (state: ThemeState) => {
      state.themeName = state.themeName === "light" ? "dark" : "light";
      saveThemeToStorage(state.themeName);
    },
    setTheme: (state: ThemeState, action: { payload: string }) => {
      // Validate theme value
      if (action.payload === "light" || action.payload === "dark") {
        state.themeName = action.payload;
        saveThemeToStorage(state.themeName);
      }
    },
  },
});

export const { toggleTheme, setTheme } = themeSlice.actions;

export const selectTheme = (state: RootState) => state.theme;

export default themeSlice.reducer;
