import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import APIs from '@src/api/APIs';
import URLInfo from '@src/constants/URLInfo';
import { IActivity, ICollectionBaseInfo, IFilter, INFT } from 'metarare';

type CollectionState = {
  isBaseInfoLoaded: boolean;
  activity: IActivity[];
  item: INFT[];
  baseInfo: ICollectionBaseInfo | null;
}

const collectionState: CollectionState = {
  isBaseInfoLoaded: true,
  activity: [],
  item: [],
  baseInfo: null
};

export const fetchCollectionActivity = createAsyncThunk<Promise<any>, string>(
  'collection/fetchCollectionActivity',
  async (name, thunkAPI) => {
    try {
      const response = await APIs.fetchCollectionActivity(name);
      return response;
    } catch (err) {
      return thunkAPI.rejectWithValue('Something went wrong.');
    }
  }
);

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

export const fetchCollection = createAsyncThunk<Promise<any>, string>(
  'collection/fetchCollection',
  async (name, thunkAPI) => {
    try {
      const response = await APIs.fetchCollection(name);
      return response;
    } catch (err) {
      return thunkAPI.rejectWithValue('Something went wrong.');
    }
  }
);

export const slice = createSlice({
  name: 'collection',
  initialState: collectionState,
  reducers: {
    resetItem: (state: CollectionState) => {
      state.item = [];
    }
  },
  extraReducers: {
    [fetchCollectionActivity.fulfilled.type]: (state: CollectionState, action) => {
      const { payload } = action;

      state.activity = payload;
    },
    [fetchCollectionItem.fulfilled.type]: (state: CollectionState, action) => {
      const { payload } = action;

      state.item = [
        ...state.item,
        ...payload
      ];
    },
    [fetchCollection.pending.type]: (state: CollectionState, action) => {
      state.isBaseInfoLoaded = false;
    },
    [fetchCollection.fulfilled.type]: (state: CollectionState, action) => {
      const { payload } = action;

      state.baseInfo = payload;
      state.isBaseInfoLoaded = true;
    },
    [fetchCollection.rejected.type]: (state: CollectionState, action) => {
      state.baseInfo = null;
      state.isBaseInfoLoaded = true;
      window.location.href = URLInfo.ERROR;
    },
  },
});

export const {
  resetItem
} = slice.actions;

const CollectionReducer = slice.reducer;
export default CollectionReducer;
