import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

import {
	API,
	current_user_can,
	current_user_id,
	namespace,
	is_admin,
	handleSliceSuccess,
	handleSliceError,
} from '@QPUtils/helper';

//Fetch ALl category
export const fetchCategories = createAsyncThunk(
	'quizpress/fetchCategories',
	async (
		{ status = 'all', page = 1, per_page = 10, search = '' },
		thunkAPI
	) => {
		let params = {
			status: status === 'all' ? 'any' : status,
			page,
			per_page,
			context: 'edit',
		};
		if ( search ) {
			params = { ...params, search };
		}

		return await API.get( namespace + 'quizpress_quiz_category', {
			params,
		} )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					return {
						data: res.data,
						totalItems: Number( res.headers[ 'x-wp-total' ] ),
						currentPage: page,
						itemPerPage: per_page,
						status,
					};
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

//Create New Category
export const createCategory = createAsyncThunk(
	'quizpress/createCategory',
	async ( data, thunkAPI ) => {
		return await API.post( namespace + 'quizpress_quiz_category', data )
			.then( ( res ) => {
				if ( res.status === 201 ) {
					handleSliceSuccess( thunkAPI, res.data.message );
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

//Get Single category
export const getCategory = createAsyncThunk(
	'quizpress/getCategory',
	async ( ID, thunkAPI ) => {
		// const queryString = is_plain_permalink ? '&' : '?';
		return await API.post(
			// namespace + 'quizpress_quiz/' + ID + queryString + 'context=edit'
			namespace + 'quizpress_quiz_category/' + ID + '?' + 'context=edit'
		)
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess( thunkAPI, res.data.message );
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

//Delete Category
export const deleteCategory = createAsyncThunk(
	'quizpress/deleteCategory',
	async ( ID, thunkAPI ) => {
		return await API.post(
			`${ namespace }quizpress_quiz_category/${ ID }`,
			{ force: true },
			{
				headers: {
					'X-HTTP-Method-Override': 'DELETE',
				},
			}
		)
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess( thunkAPI, res.data.message );
					return res.data.previous;
				}
			} )
			.catch( ( err ) => handleSliceError( thunkAPI, err ) );
	}
);

//Update category
export const updateCategory = createAsyncThunk(
	'quizpress/updateCategory',
	async ( params, thunkAPI ) => {
		return await API.post(
			namespace + 'quizpress_quiz_category/' + params.id,
			params
		)
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess( thunkAPI, res.data.message );
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

const categorySlice = createSlice( {
	name: 'categories',
	initialState: {
		data: [],
		totalItems: 0,
		currentPage: 1,
		loading: false,
		itemPerPage: 10,
	},
	reducers: {
		updateCategoryCurrentPage: ( state, actions ) => {
			state.currentPage = actions.payload;
		},
		updateCategoryItemPerPage: ( state, actions ) => {
			state.itemPerPage = actions.payload;
		},
		// clearCategoryState: (state) => {
		// 	state.data = false;
		// },
	},
	extraReducers: ( builder ) => {
		builder
			// create new category
			.addCase( createCategory.fulfilled, ( state, action ) => {
				state.data = [ action.payload, ...state.data ];
			} )

			//fetch all categories
			.addCase( fetchCategories.fulfilled, ( state, action ) => {
				const { data, totalItems, status, currentPage, itemPerPage } =
					action.payload;
				state.data = data;
				state.totalItems = totalItems;
				state.currentPage = currentPage;
				state.itemPerPage = itemPerPage;
			} )

			//Get Single category
			.addCase( getCategory.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = [ action.payload ];
			} )

			//Update Category
			.addCase( updateCategory.fulfilled, ( state, action ) => {
				state.data = state.data.map( ( item ) => {
					if ( Number( item.id ) === Number( action.payload.id ) ) {
						return { ...item, ...action.payload };
					}
					return item;
				} );
			} )

			//Delete Category directly
			.addCase( deleteCategory.fulfilled, ( state, action ) => {
				state.loading = false;
				const prepareData = state.data.reduce( ( acc, item ) => {
					if (
						Number( item.parent ) === Number( action.payload.id )
					) {
						item.parent = 0;
					}
					acc.push( item );
					return acc;
				}, [] );
				state.data = prepareData.filter(
					( item ) =>
						Number( item.id ) !== Number( action.payload.id )
				);
			} );
	},
} );

export const { updateCategoryCurrentPage, updateCategoryItemPerPage } =
	categorySlice.actions;
export default categorySlice.reducer;
