import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { reelsListService, MappedReel } from "@/services/reelsListService";

interface ReelsListState {
  reels: MappedReel[];
  isLoading: boolean;
  isLoadingMore: boolean;
  error: string | null;
  currentPage: number;
  hasMore: boolean;
}

const initialState: ReelsListState = {
  reels: [],
  isLoading: false,
  isLoadingMore: false,
  error: null,
  currentPage: 1,
  hasMore: false,
};

export const fetchReelsList = createAsyncThunk(
  "reelsList/fetch",
  async (pageNo: number, { rejectWithValue }) => {
    try {
      const res = await reelsListService.getReelsList(pageNo);
      if (res.status !== 200) return rejectWithValue(res.message);
      return {
        reels: res.result.map(reelsListService.mapReel),
        hasMore: res.more_page,
        currentPage: res.current_page,
      };
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Failed to load reels";
      return rejectWithValue(msg);
    }
  },
  {
    // Skip page-1 fetch if reels are already cached — prevents re-fetching on every home navigation
    condition: (pageNo, { getState }) => {
      if (pageNo !== 1) return true;
      const { reelsList } = getState() as { reelsList: ReelsListState };
      return reelsList.reels.length === 0 && !reelsList.isLoading;
    },
  },
);

const reelsListSlice = createSlice({
  name: "reelsList",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchReelsList.pending, (state, action) => {
        state.error = null;
        if (action.meta.arg === 1) {
          state.isLoading = true;
          state.reels = [];
        } else {
          state.isLoadingMore = true;
        }
      })
      .addCase(fetchReelsList.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isLoadingMore = false;
        state.hasMore = action.payload.hasMore;
        state.currentPage = action.payload.currentPage;
        if (action.payload.currentPage === 1) {
          state.reels = action.payload.reels;
        } else {
          state.reels.push(...action.payload.reels);
        }
      })
      .addCase(fetchReelsList.rejected, (state, action) => {
        state.isLoading = false;
        state.isLoadingMore = false;
        state.error = action.payload as string;
      });
  },
});

export default reelsListSlice.reducer;
