import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import APIs from '@src/api/APIs';
import { IArtist, IFilter, IHome } from 'metarare';

type HomeState = {
  isLoaded: boolean;
  data: IHome | null;
  dataArtists: IArtist[]
}

const homeState: HomeState = {
  isLoaded: false,
  data: null,
  dataArtists: []
};

export const fetchHome = createAsyncThunk(
  'home/fetchHome',
  async (_, thunkAPI) => {
    try {
      const response = await APIs.fetchHome();
      return response;
    } catch (err) {
      return thunkAPI.rejectWithValue('Something went wrong.');
    }
  }
);

export const fetchHomeArtists = createAsyncThunk<Promise<any>, IFilter>(
  'home/fetchHomeArtists',
  async (filter, thunkAPI) => {
    try {
      const response = await APIs.fetchHomeArtists(filter);
      return response;
    } catch (err) {
      return thunkAPI.rejectWithValue('Something went wrong.');
    }
  }
);


export const slice = createSlice({
  name: 'home',
  initialState: homeState,
  reducers: {
  },
  extraReducers: {
    [fetchHome.pending.type]: (state: HomeState, action) => {
      state.isLoaded = true;
    },
    [fetchHome.fulfilled.type]: (state: HomeState, action) => {
      const { payload } = action;

      state.data = payload;
      state.isLoaded = false;
    },
    [fetchHome.rejected.type]: (state: HomeState, action) => {
      state.isLoaded = false;
    },
    [fetchHomeArtists.pending.type]: (state: HomeState, action) => {
      state.isLoaded = true;
    },
    [fetchHomeArtists.fulfilled.type]: (state: HomeState, action) => {
      const { payload } = action;

      state.dataArtists = payload;
      state.isLoaded = false;
    },
    [fetchHomeArtists.rejected.type]: (state: HomeState, action) => {
      state.isLoaded = false;
    },
  },
});

export const {
} = slice.actions;

const HomeReducer = slice.reducer;
export default HomeReducer;
