import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { homeService } from "@/services/homeService";
import { HomeSection, HomeTab } from "@/types/home";
import { generateMockSections } from "@/utils/mockData";

interface HomeState {
  sections: HomeSection[];
  activeTab: HomeTab;
  isLoading: boolean;
  error: string | null;
}

const initialState: HomeState = {
  sections: [],
  activeTab: "all",
  isLoading: false,
  error: null,
};

export const fetchHomeSections = createAsyncThunk(
  "home/fetchSections",
  async (tab: HomeTab, { rejectWithValue }) => {
    try {
      const res = await homeService.getSections(tab);
      if (res.status === 0) return rejectWithValue(res.message);
      return res.result;
    } catch {
      return generateMockSections(tab);
    }
  },
);

const homeSlice = createSlice({
  name: "home",
  initialState,
  reducers: {
    setActiveTab: (state, action: PayloadAction<HomeTab>) => {
      state.activeTab = action.payload;
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchHomeSections.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchHomeSections.fulfilled, (state, action) => {
        state.isLoading = false;
        state.sections = action.payload;
      })
      .addCase(fetchHomeSections.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
        state.sections = generateMockSections("all");
      });
  },
});

export const { setActiveTab, clearError } = homeSlice.actions;
export default homeSlice.reducer;
