import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { watchLaterService } from "@/services/watchLaterService";
import { ContentItem } from "@/types/content";

interface WatchLaterState {
  items: ContentItem[];
  isLoading: boolean;
  isLoadingMore: boolean;
  error: string | null;
  currentPage: number;
  hasMore: boolean;
  activeContentType: number;
  totalRows: number;
  /* legacy alias kept for existing selectors */
  videos: ContentItem[];
  activeCategoryId: number;
}

const initialState: WatchLaterState = {
  items: [], videos: [], isLoading: false, isLoadingMore: false,
  error: null, currentPage: 1, hasMore: false,
  activeContentType: 1, totalRows: 0, activeCategoryId: 1,
};

export const fetchWatchLaterList = createAsyncThunk(
  "watchlaterlist/fetch",
  async ({ contentType, pageNo }: { contentType: number; pageNo: number }, { rejectWithValue }) => {
    try {
      const res = await watchLaterService.getWatchLaterContent(contentType, pageNo);
      if (res.status !== 200) return rejectWithValue(res.message);
      return {
        items: res.result.map(watchLaterService.mapItem),
        hasMore: res.more_page,
        currentPage: res.current_page,
        contentType,
        totalRows: res.total_rows,
      };
    } catch (err: unknown) {
      return rejectWithValue(err instanceof Error ? err.message : "Failed to load watch later");
    }
  },
);

const watchLaterSlice = createSlice({
  name: "watchLater",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchWatchLaterList.pending, (state, action) => {
        state.error = null;
        if (action.meta.arg.pageNo === 1) { state.isLoading = true; state.items = []; state.videos = []; }
        else state.isLoadingMore = true;
      })
      .addCase(fetchWatchLaterList.fulfilled, (state, action) => {
        state.isLoading = false; state.isLoadingMore = false;
        state.hasMore = action.payload.hasMore;
        state.currentPage = action.payload.currentPage;
        state.activeContentType = action.payload.contentType;
        state.activeCategoryId = action.payload.contentType;
        state.totalRows = action.payload.totalRows;
        if (action.payload.currentPage === 1) {
          state.items = action.payload.items;
          state.videos = action.payload.items;
        } else {
          state.items.push(...action.payload.items);
          state.videos.push(...action.payload.items);
        }
      })
      .addCase(fetchWatchLaterList.rejected, (state, action) => {
        state.isLoading = false; state.isLoadingMore = false;
        state.error = action.payload as string;
      });
  },
});

export default watchLaterSlice.reducer;
