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

interface OfflineAction {
  id: string;
  type: string;
  payload: any;
  timestamp: number;
  retryCount: number;
}

interface OfflineState {
  isOnline: boolean;
  pendingActions: OfflineAction[];
  syncing: boolean;
  lastSync: number | null;
  syncError: string | null;
}

const initialState: OfflineState = {
  isOnline: true,
  pendingActions: [],
  syncing: false,
  lastSync: null,
  syncError: null,
};

const offlineSlice = createSlice({
  name: 'offline',
  initialState,
  reducers: {
    setOnlineStatus: (state, action: PayloadAction<boolean>) => {
      state.isOnline = action.payload;
    },
    addPendingAction: (state, action: PayloadAction<Omit<OfflineAction, 'id' | 'timestamp' | 'retryCount'>>) => {
      const newAction: OfflineAction = {
        ...action.payload,
        id: `${Date.now()}-${Math.random()}`,
        timestamp: Date.now(),
        retryCount: 0,
      };
      state.pendingActions.push(newAction);
    },
    removePendingAction: (state, action: PayloadAction<string>) => {
      state.pendingActions = state.pendingActions.filter(
        action => action.id !== action.payload
      );
    },
    updatePendingAction: (state, action: PayloadAction<{ id: string; retryCount: number }>) => {
      const action = state.pendingActions.find(a => a.id === action.payload.id);
      if (action) {
        action.retryCount = action.payload.retryCount;
      }
    },
    setSyncing: (state, action: PayloadAction<boolean>) => {
      state.syncing = action.payload;
    },
    setLastSync: (state, action: PayloadAction<number>) => {
      state.lastSync = action.payload;
    },
    setSyncError: (state, action: PayloadAction<string | null>) => {
      state.syncError = action.payload;
    },
    clearPendingActions: (state) => {
      state.pendingActions = [];
    },
  },
});

export const {
  setOnlineStatus,
  addPendingAction,
  removePendingAction,
  updatePendingAction,
  setSyncing,
  setLastSync,
  setSyncError,
  clearPendingActions,
} = offlineSlice.actions;

export default offlineSlice.reducer; 