import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Dimensions } from "react-native";

import type { RootState } from "../index";

export interface ScreenSizeState {
  width: number;
  height: number;
  isMobile: boolean;
  sidebarCollapsed: boolean;
}

const initialDimensions = Dimensions.get("window");

const initialState: ScreenSizeState = {
  width: initialDimensions.width,
  height: initialDimensions.height,
  isMobile: initialDimensions.width < 768,
  sidebarCollapsed: false,
};

export const screenSizeSlice = createSlice({
  name: "screenSize",
  initialState,
  reducers: {
    setScreenSize: (
      state,
      action: PayloadAction<{ width: number; height: number }>
    ) => {
      state.width = action.payload.width;
      state.height = action.payload.height;
      state.isMobile = action.payload.width < 768;
    },
    setSidebarCollapsed: (state, action: PayloadAction<boolean>) => {
      state.sidebarCollapsed = action.payload;
    },
  },
});

export const { setScreenSize, setSidebarCollapsed } = screenSizeSlice.actions;

export const selectScreenSize = (state: RootState) => state.screenSize;
export const selectIsMobile = (state: RootState) => state.screenSize.isMobile;
export const selectWidth = (state: RootState) => state.screenSize.width;
export const selectHeight = (state: RootState) => state.screenSize.height;
export const selectSidebarCollapsed = (state: RootState) => state.screenSize.sidebarCollapsed;

export default screenSizeSlice.reducer;
