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

import {
	API,
	namespace,
	handleSliceSuccess,
	handleSliceError,
	makeRequest,
} from '@QPUtils/helper';
import { __ } from '@wordpress/i18n';

export const fetchQuizInsights = createAsyncThunk(
	'quizpress/fetchQuizInsights',
	async (
		{ page = 1, per_page = 10, search = '', quiz_id = null, user = null },
		thunkAPI
	) => {
		let params = {
			page,
			per_page,
		};

		if ( search ) {
			params = { ...params, search };
		}
		if ( quiz_id ) {
			params = { ...params, quiz_id };
		}
		if ( user ) {
			params = { ...params, user };
		}

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

export const createAttempts = createAsyncThunk(
	'quizpress/createAttempts',
	async ( formdata, thunkAPI ) => {
		return await API.post( `${ namespace }attempts`, formdata )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					// handleSliceSuccess( thunkAPI, res.data.message );
					return res.data;
				}
			} )
			.catch( ( error ) => {
				handleSliceError( thunkAPI, error );
			} );
	}
);

export const fetchAttemptById = createAsyncThunk(
	'quizpress/fetchAttemptById',
	async ( id, thunkAPI ) => {
		return await API.get( `${ namespace }attempts/${ id }` )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					return res.data;
				}
			} )
			.catch( ( error ) => {
				handleSliceError( thunkAPI, error );
			} );
	}
);

export const updateAttempts = createAsyncThunk(
	'quizpress/updateAttempts',
	async ( formdata, thunkAPI ) => {
		return await API.post(
			`${ namespace }attempts/${ formdata?.attempt_id }`,
			formdata
		)
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess(
						thunkAPI,
						res.data.message ?? 'Attempt updated successfully'
					);
					return res.data;
				}
			} )
			.catch( ( error ) => {
				handleSliceError( thunkAPI, error );
			} );
	}
);

export const deleteAttempts = createAsyncThunk(
	'quizpress/deleteAttempts',
	async ( id, thunkAPI ) => {
		return await API.delete(
			`${ namespace }attempts/${ id }`,
			{ headers: { 'X-HTTP-Method-Override': 'DELETE' } },
			{ force: true }
		)
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess(
						thunkAPI,
						res.data.message ?? 'Attempts deleted successfully'
					);
					return id;
				}
			} )
			.catch( ( error ) => {
				handleSliceError( thunkAPI, error );
			} );
	}
);

export const getQuizAttemptDetails = createAsyncThunk(
	'quizpress/getQuizAttemptDetails',
	async ( payload, thunkAPI ) => {
		return await makeRequest(
			`admin/get_quiz_attempt_answers_details`,
			payload
		)
			.then( ( res ) => {
				return res;
			} )
			.catch( ( error ) => {
				handleSliceError( thunkAPI, error );
			} );
	}
);

export const attemptReviewSubmit = createAsyncThunk(
	'quizpress/attemptReviewSubmit',
	async ( payload, thunkAPI ) => {
		return await makeRequest(
			`admin/attempt_answer_manually_review`,
			payload
		)
			.then( ( res ) => {
				return res;
			} )
			.catch( ( error ) => {
				handleSliceError( thunkAPI, error );
			} );
	}
);

export const updateAttemptFeedback = createAsyncThunk(
	'quizpress/updateAttemptFeedback',
	async ( payload, thunkAPI ) => {
		return await makeRequest(
			`admin/update_quiz_attempt_manual_feedback`,
			payload
		)
			.then( ( res ) => {
				handleSliceSuccess( thunkAPI, 'Feedback updated successfully' );
				return res;
			} )
			.catch( ( error ) => {
				handleSliceError( thunkAPI, error );
			} );
	}
);

const quizSlice = createSlice( {
	name: 'quizInsights',
	initialState: {
		data: [],
		totalItems: 0,
		currentPage: 1,
		loading: false,
		itemPerPage: 10,
		attempt_questions: [],
	},
	reducers: {
		updateQuizInsightsCurrentPage: ( state, actions ) => {
			state.currentPage = actions.payload;
		},
		updateQuizInsightsItemPerPage: ( state, actions ) => {
			state.itemPerPage = actions.payload;
		},
		insertAttemptQuestion: ( state, actions ) => {
			state.attempt_questions = actions.payload;
		},
	},
	extraReducers: ( builder ) => {
		builder
			.addCase( fetchQuizInsights.fulfilled, ( state, action ) => {
				const { data, totalItems, status, currentPage, itemPerPage } =
					action.payload;
				state.data = data;
				state.totalItems = totalItems;
				state.currentPage = currentPage;
				state.itemPerPage = itemPerPage;
			} )

			//create attempts
			.addCase( createAttempts.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = [ action.payload, ...state.data ];
			} )
			//create attempts
			.addCase( fetchAttemptById.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = [ action.payload ];
			} )
			//update attempts
			.addCase( updateAttempts.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.map( ( item ) => {
					if (
						Number( item.attempt_id ) ===
						Number( action.payload.attempt_id )
					) {
						return { ...item, ...action.payload };
					}
					return item;
				} );
			} )
			//delete attempts
			.addCase( deleteAttempts.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.filter(
					( item ) =>
						Number( item.attempt_id ) !== Number( action.payload )
				);
			} );
	},
} );

export const {
	updateQuizInsightsCurrentPage,
	updateQuizInsightsItemPerPage,
	insertAttemptQuestion,
} = quizSlice.actions;
export default quizSlice.reducer;
