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

interface HistoryState {
  items: ContentItem[];
  isLoading: boolean;
  isLoadingMore: boolean;
  error: string | null;
  currentPage: number;
  hasMore: boolean;
  activeContentType: number;
  totalRows: number;
}

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

export const fetchHistory = createAsyncThunk(
  "history/fetch",
  async ({ contentType, pageNo }: { contentType: number; pageNo: number }, { rejectWithValue }) => {
    try {
      const res = await historyService.getHistory(contentType, pageNo);
      if (res.status !== 200) return rejectWithValue(res.message);
      return {
        items: res.result.map(historyService.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 history");
    }
  },
);

const historySlice = createSlice({
  name: "history",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchHistory.pending, (state, action) => {
        state.error = null;
        if (action.meta.arg.pageNo === 1) { state.isLoading = true; state.items = []; }
        else state.isLoadingMore = true;
      })
      .addCase(fetchHistory.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.totalRows = action.payload.totalRows;
        if (action.payload.currentPage === 1) state.items = action.payload.items;
        else state.items.push(...action.payload.items);
      })
      .addCase(fetchHistory.rejected, (state, action) => {
        state.isLoading = false; state.isLoadingMore = false;
        state.error = action.payload as string;
      });
  },
});

export const removeHistoryItem = createAsyncThunk(
  "history/removeItem",
  async (params: { contentType: number; contentId: string; episodeId?: string }, { rejectWithValue }) => {
    try {
      await historyService.removeFromHistory(params);
      return params;
    } catch (err: unknown) {
      return rejectWithValue(err instanceof Error ? err.message : "Failed to remove");
    }
  },
);

// Wire into the existing slice via a new export — slice extraReducers are above, so patch via the reducer
const historySliceWithDelete = {
  ...historySlice,
  reducer: (state: HistoryState | undefined, action: { type: string; payload?: unknown }) => {
    if (action.type === removeHistoryItem.fulfilled.type) {
      const s = historySlice.reducer(state, action as Parameters<typeof historySlice.reducer>[1]);
      const p = action.payload as { contentId: string };
      return { ...s, items: s.items.filter((i) => i.id !== p.contentId), totalRows: Math.max(0, s.totalRows - 1) };
    }
    return historySlice.reducer(state, action as Parameters<typeof historySlice.reducer>[1]);
  },
};

export default historySliceWithDelete.reducer;
