import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { subscriberService, SubscriberChannel } from "@/services/subscriberService";

interface SubscriberState {
  channels: SubscriberChannel[];
  isLoading: boolean;
  isLoadingMore: boolean;
  error: string | null;
  currentPage: number;
  hasMore: boolean;
  totalRows: number;
}

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

export const fetchSubscribeList = createAsyncThunk(
  "subscriber/fetch",
  async (pageNo: number, { rejectWithValue }) => {
    try {
      const res = await subscriberService.getSubscribeList(pageNo);
      if (res.status !== 200) return rejectWithValue(res.message);
      return {
        channels: res.result.map(subscriberService.mapChannel),
        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 subscriptions");
    }
  },
);

const subscriberSlice = createSlice({
  name: "subscriber",
  initialState,
  reducers: {
    /* Optimistic unsubscribe — removes card from list */
    removeSubscription(state, action: PayloadAction<string>) {
      state.channels = state.channels.filter((c) => c.id !== action.payload);
      state.totalRows = Math.max(0, state.totalRows - 1);
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchSubscribeList.pending, (state, action) => {
        state.error = null;
        if (action.meta.arg === 1) { state.isLoading = true; state.channels = []; }
        else state.isLoadingMore = true;
      })
      .addCase(fetchSubscribeList.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.channels = action.payload.channels;
        else state.channels.push(...action.payload.channels);
      })
      .addCase(fetchSubscribeList.rejected, (state, action) => {
        state.isLoading = false;
        state.isLoadingMore = false;
        state.error = action.payload as string;
      });
  },
});

export const { removeSubscription } = subscriberSlice.actions;
export default subscriberSlice.reducer;
