import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { rentService, RentSection, RentItem } from "@/services/rentService";

interface RentState {
  sections: RentSection[];
  isLoading: boolean;
  error: string | null;
  selectedItem: RentItem | null;
}

const initialState: RentState = {
  sections: [],
  isLoading: false,
  error: null,
  selectedItem: null,
};

export const fetchRentSections = createAsyncThunk(
  "rent/fetchSections",
  async (pageNo: number, { rejectWithValue }) => {
    try {
      const res = await rentService.getSections(pageNo);
      if (res.status !== 200) return rejectWithValue(res.message);
      return res.result
        .map(rentService.mapSection)
        .filter((s) => s.items.length > 0); // skip empty sections
    } catch (err: unknown) {
      return rejectWithValue(err instanceof Error ? err.message : "Failed to load rent content");
    }
  },
);

const rentSlice = createSlice({
  name: "rent",
  initialState,
  reducers: {
    /* Store the clicked rent item so RentPlayPage can use it without an API call */
    selectRentItem(state, action: PayloadAction<RentItem>) {
      state.selectedItem = action.payload;
    },
    /* Optimistic purchase — marks an item as owned */
    markOwned(state, action: PayloadAction<{ sectionId: string; itemId: string }>) {
      const section = state.sections.find((s) => s.id === action.payload.sectionId);
      if (section) {
        const item = section.items.find((i) => i.id === action.payload.itemId);
        if (item) item.isOwned = true;
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchRentSections.pending, (state) => {
        state.isLoading = true;
        state.error = null;
        state.sections = [];
      })
      .addCase(fetchRentSections.fulfilled, (state, action) => {
        state.isLoading = false;
        state.sections = action.payload;
      })
      .addCase(fetchRentSections.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export const { markOwned, selectRentItem } = rentSlice.actions;
export default rentSlice.reducer;
