import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { feedService, FeedPost } from "@/services/feedService";

interface FeedState {
  posts: FeedPost[];
  isLoading: boolean;
  isLoadingMore: boolean;
  error: string | null;
  currentPage: number;
  hasMore: boolean;
  totalRows: number;
}

const initialState: FeedState = {
  posts: [],
  isLoading: false,
  isLoadingMore: false,
  error: null,
  currentPage: 1,
  hasMore: false,
  totalRows: 0,
};

export const fetchFeed = createAsyncThunk(
  "feed/fetch",
  async (pageNo: number, { rejectWithValue }) => {
    try {
      const res = await feedService.getFeed(pageNo);
      if (res.status !== 200) return rejectWithValue(res.message);
      return {
        posts: res.result.map(feedService.mapPost),
        hasMore: res.more_page,
        currentPage: res.current_page,
        totalRows: res.total_rows,
      };
    } catch (err: unknown) {
      return rejectWithValue(err instanceof Error ? err.message : "Failed to load feed");
    }
  },
);

const feedSlice = createSlice({
  name: "feed",
  initialState,
  reducers: {
    toggleLike(state, action: PayloadAction<string>) {
      const post = state.posts.find((p) => p.id === action.payload);
      if (post) {
        post.isLiked = !post.isLiked;
        post.totalLikes += post.isLiked ? 1 : -1;
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchFeed.pending, (state, action) => {
        state.error = null;
        if (action.meta.arg === 1) { state.isLoading = true; state.posts = []; }
        else state.isLoadingMore = true;
      })
      .addCase(fetchFeed.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isLoadingMore = false;
        state.hasMore = action.payload.hasMore;
        state.currentPage = action.payload.currentPage;
        state.totalRows = action.payload.totalRows;
        if (action.payload.currentPage === 1) state.posts = action.payload.posts;
        else state.posts.push(...action.payload.posts);
      })
      .addCase(fetchFeed.rejected, (state, action) => {
        state.isLoading = false;
        state.isLoadingMore = false;
        state.error = action.payload as string;
      });
  },
});

export const { toggleLike } = feedSlice.actions;
export default feedSlice.reducer;
