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

interface FollowStatsState {
  followingCount: number;
  followedUsers: { [key: string]: boolean };
}

const initialState: FollowStatsState = {
  followingCount: 0,
  followedUsers: {},
};

const followStatsSlice = createSlice({
  name: "followStats",
  initialState,
  reducers: {
    setFollowingCount: (state, action: PayloadAction<number>) => {
      state.followingCount = Math.max(0, action.payload);
    },
    incrementFollowing: (state) => {
      state.followingCount += 1;
    },
    decrementFollowing: (state) => {
      state.followingCount = Math.max(0, state.followingCount - 1);
    },
    setFollowedUsers: (state, action: PayloadAction<{ [key: string]: boolean }>) => {
      state.followedUsers = action.payload;
    },
    toggleFollow: (state, action: PayloadAction<string>) => {
      const userId = action.payload;
      const isCurrentlyFollowing = state.followedUsers[userId];
      state.followedUsers[userId] = !isCurrentlyFollowing;
      
      // Update count when toggling
      if (!isCurrentlyFollowing) {
        state.followingCount += 1;
      } else {
        state.followingCount = Math.max(0, state.followingCount - 1);
      }
    },
    updateFollowStatus: (state, action: PayloadAction<{ userId: string; isFollowing: boolean }>) => {
      const { userId, isFollowing } = action.payload;
      const wasPreviouslyFollowing = state.followedUsers[userId];
      state.followedUsers[userId] = isFollowing;
      
      // Update count based on change
      if (isFollowing && !wasPreviouslyFollowing) {
        state.followingCount += 1;
      } else if (!isFollowing && wasPreviouslyFollowing) {
        state.followingCount = Math.max(0, state.followingCount - 1);
      }
    },
  },
});

export const { 
  setFollowingCount, 
  incrementFollowing, 
  decrementFollowing,
  setFollowedUsers,
  toggleFollow,
  updateFollowStatus
} = followStatsSlice.actions;
export default followStatsSlice.reducer;