import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface NetworkState {
  isOnline: boolean;
  isConnected: boolean; // API server reachability
  lastOnlineTime: string | null;
  lastOfflineTime: string | null;
  connectionQuality: 'excellent' | 'good' | 'poor' | 'offline';
  latency: number | null;
}

const initialState: NetworkState = {
  isOnline: typeof navigator !== 'undefined' ? navigator.onLine : true,
  isConnected: true,
  lastOnlineTime: null,
  lastOfflineTime: null,
  connectionQuality: 'excellent',
  latency: null,
};

const networkSlice = createSlice({
  name: 'network',
  initialState,
  reducers: {
    setOnlineStatus: (state, action: PayloadAction<boolean>) => {
      const wasOnline = state.isOnline;
      state.isOnline = action.payload;

      if (action.payload && !wasOnline) {
        // Just came online
        state.lastOnlineTime = new Date().toISOString();
      } else if (!action.payload && wasOnline) {
        // Just went offline
        state.lastOfflineTime = new Date().toISOString();
      }
    },
    setServerConnection: (state, action: PayloadAction<boolean>) => {
      state.isConnected = action.payload;
    },
    setConnectionQuality: (state, action: PayloadAction<NetworkState['connectionQuality']>) => {
      state.connectionQuality = action.payload;
    },
    setLatency: (state, action: PayloadAction<number>) => {
      state.latency = action.payload;
      // Update connection quality based on latency
      if (action.payload < 100) {
        state.connectionQuality = 'excellent';
      } else if (action.payload < 300) {
        state.connectionQuality = 'good';
      } else {
        state.connectionQuality = 'poor';
      }
    },
  },
});

export const {
  setOnlineStatus,
  setServerConnection,
  setConnectionQuality,
  setLatency,
} = networkSlice.actions;

export default networkSlice.reducer;
