import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { getLeaderboard } from './service';
import { LeaderboardMyRank, LeaderboardPeriod, LeaderboardRoleOption, LeaderboardSection } from './interface';

interface LeaderboardState {
  periodType: 'month' | 'year';
  scope: 'city' | 'pan_india';
  selectedRoleId: number | null;
  availableRoles: LeaderboardRoleOption[];
  section: LeaderboardSection | null;
  cityLabel: string | null;
  myRank: LeaderboardMyRank | null;
  period: LeaderboardPeriod | null;
  status: 'idle' | 'loading' | 'succeeded' | 'failed';
  error: string | null;
}

const initialState: LeaderboardState = {
  periodType: 'month',
  scope: 'pan_india',
  selectedRoleId: null,
  availableRoles: [],
  section: null,
  cityLabel: null,
  myRank: null,
  period: null,
  status: 'idle',
  error: null,
};

export const fetchLeaderboard = createAsyncThunk(
  'leaderboard/fetch',
  async(_: void, { getState }) => {
    const state = getState() as { leaderboard: LeaderboardState };
    const { periodType, scope, selectedRoleId } = state.leaderboard;
    const params: { period: 'month' | 'year'; scope: 'city' | 'pan_india'; role?: number } = { period: periodType, scope };
    if (selectedRoleId) {
      params.role = selectedRoleId;
    }
    const response = await getLeaderboard(params);
    return response.data;
  }
);

const leaderboardSlice = createSlice({
  name: 'leaderboard',
  initialState,
  reducers: {
    setPeriodType: (state, action: PayloadAction<'month' | 'year'>) => {
      state.periodType = action.payload;
    },
    setScope: (state, action: PayloadAction<'city' | 'pan_india'>) => {
      state.scope = action.payload;
    },
    setSelectedRoleId: (state, action: PayloadAction<number>) => {
      state.selectedRoleId = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchLeaderboard.pending, (state) => {
        state.status = 'loading';
        state.error = null;
      })
      .addCase(fetchLeaderboard.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.section = action.payload?.data?.section || null;
        state.availableRoles = action.payload?.data?.available_roles || [];
        state.selectedRoleId = action.payload?.data?.selected_role_id ?? null;
        state.scope = action.payload?.data?.scope || 'pan_india';
        state.cityLabel = action.payload?.data?.city_label ?? null;
        state.myRank = action.payload?.data?.my_rank ?? null;
        state.period = action.payload?.period || null;
      })
      .addCase(fetchLeaderboard.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message || 'Failed to load leaderboard';
      });
  },
});

export const { setPeriodType, setScope, setSelectedRoleId } = leaderboardSlice.actions;
export default leaderboardSlice.reducer;
