import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import APIs from '@src/api/APIs';
import { IBidHistory, IFilter, ISale, ISaleRanking } from 'metarare';

type SaleState = {
  isDataLoaded: boolean;
  data: ISale | null;
  bid: IBidHistory[];
  dataRaking: ISaleRanking[]
}

const saleState: SaleState = {
  isDataLoaded: true,
  data: null,
  dataRaking: [],
  bid: [],
};

export const fetchSale = createAsyncThunk<Promise<any>, number>(
  'sale/fetchSale',
  async (id, thunkAPI) => {
    try {
      const response = await APIs.fetchSale(id);
      return response;
    } catch (err) {
      return thunkAPI.rejectWithValue('Something went wrong.');
    }
  }
);

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


export const fetchBid = createAsyncThunk<Promise<any>, number>(
  'sale/fetchBid',
  async (id, thunkAPI) => {
    try {
      const response = await APIs.fetchBid(id);
      return response;
    } catch (err) {
      return thunkAPI.rejectWithValue('Something went wrong.');
    }
  }
);

export const slice = createSlice({
  name: 'sale',
  initialState: saleState,
  reducers: {
  },
  extraReducers: {
    [fetchSale.pending.type]: (state: SaleState, action) => {
      state.isDataLoaded = false;
    },
    [fetchSale.fulfilled.type]: (state: SaleState, action) => {
      const { payload } = action;

      state.data = payload;
      state.isDataLoaded = true;
    },
    [fetchSale.rejected.type]: (state: SaleState, action) => {
      state.isDataLoaded = true;
    },
    [fetchSaleRanking.pending.type]: (state: SaleState, action) => {
      state.isDataLoaded = false;
    },
    [fetchSaleRanking.fulfilled.type]: (state: SaleState, action) => {
      const { payload } = action;
      const data = payload as ISaleRanking[]
      state.dataRaking = data.map((item, index) => {
        return {
          ...item,
          rank: index + 1,
        };
      });
      state.isDataLoaded = true;
    },
    [fetchSaleRanking.rejected.type]: (state: SaleState, action) => {
      state.isDataLoaded = true;
    },
    [fetchBid.fulfilled.type]: (state: SaleState, action) => {
      const { payload } = action;

      state.bid = payload;
    }
  },
});

export const {
} = slice.actions;

const SaleReducer = slice.reducer;
export default SaleReducer;
