import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import {
	API,
	namespace,
	handleSliceSuccess,
	handleSliceError,
} from '@QPUtils/helper';
import { __ } from '@wordpress/i18n';
import { updateSettings } from '../settingsSlice/settingsSlice';

export const fetchAllCertificates = createAsyncThunk(
	'quizpress/fetchAllCertificates',
	async (
		{ status = 'all', page = 1, per_page = 10, search = '' },
		thunkAPI
	) => {
		let params = {
			status: status === 'all' ? 'any' : status,
			page,
			per_page,
		};

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

		return await API.get( namespace + 'qp_certificate', {
			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 );
			} );
	}
);

export const getCertificate = createAsyncThunk(
	'quizpress/getQuiz',
	async ( { ID, isEditable = false }, thunkAPI ) => {
		// const queryString = isEditable ? '?context=edit' : '';
		return await API.get( namespace + 'qp_certificate/' + ID )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess( thunkAPI, res.data.message );
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

export const updateCertificate = createAsyncThunk(
	'quizpress/updateCertificate',
	async ( { ID, formData }, thunkAPI ) => {
		try {
			const res = await API.post(
				`${ namespace }qp_certificate/${ Number( ID ) }`,
				formData
			);
			handleSliceSuccess( thunkAPI, 'Certificate updated successfully' );
			return res.data;
		} catch ( e ) {
			return handleSliceError( thunkAPI, e );
		}
	}
);

export const certificateStatusUpdate = createAsyncThunk(
	'quizpress/certificateStatusUpdate',
	( certificateFormData, thunkAPI ) => {
		try {
			return API.post(
				`${ namespace }qp_certificate/${ Number(
					certificateFormData.id
				) }`,
				certificateFormData
			).then( ( res ) => {
				if ( res.status === 200 ) {
					thunkAPI.dispatch(
						showNotification( {
							message: __( `Certificate Updated.`, 'quizpress' ),
							isShow: true,
							type: 'success',
						} )
					);
					return res.data;
				}
				thunkAPI.dispatch(
					showNotification( {
						message: __( 'Failed to update status', 'quizpress' ),
						isShow: true,
						type: 'error',
					} )
				);
				return thunkAPI.rejectWithValue( {
					message: __( 'Failed to update status.', 'quizpress' ),
					success: false,
				} );
			} );
		} catch ( error ) {
			thunkAPI.dispatch(
				showNotification( {
					message: error?.response?.data?.message ?? error?.message,
					isShow: true,
					type: 'error',
				} )
			);
			return thunkAPI.rejectWithValue( {
				message: error?.response?.data?.message ?? error?.message,
			} );
		}
	}
);

export const makePrimaryCertificate = createAsyncThunk(
	'quizpress/makePrimaryCertificate',
	( ID, thunkAPI ) => {
		const { settings } = thunkAPI.getState();
		try {
			thunkAPI.dispatch(
				updateSettings( {
					...settings.data,
					quizpress_primary_certificate_id: ID,
					prefix: 'quizpress',
					childObjectKey: '',
					isCertificate: true,
				} )
			);
			return ID;
		} catch ( error ) {
			return thunkAPI.rejectWithValue( {
				message: __(
					'failed to select primary certificate',
					'quizpress'
				),
			} );
		}
	}
);

export const moveCertificateToTrash = createAsyncThunk(
	'quizpress/moveCertificateToTrash',
	async ( id, thunkAPI ) => {
		try {
			const res = await API.post(
				`${ namespace }qp_certificate/${ Number( id ) }`,
				{ force: false },
				{
					headers: {
						'X-HTTP-Method-Override': 'DELETE',
					},
				}
			);
			handleSliceSuccess(
				thunkAPI,
				'Certificate moved to trash successfully'
			);
			return res.data;
		} catch ( e ) {
			return handleSliceError( thunkAPI, e );
		}
	}
);

export const restoreCertificate = createAsyncThunk(
	'quizpress/restoreCertificate',
	async ( certificateFormData, thunkAPI ) => {
		try {
			const res = await API.post(
				`${ namespace }qp_certificate/${ Number(
					certificateFormData?.id
				) }`,
				certificateFormData
			);
			handleSliceSuccess( thunkAPI, 'Certificate restored successfully' );
			return res.data;
		} catch ( e ) {
			return handleSliceError( thunkAPI, e );
		}
	}
);

export const deleteCertificate = createAsyncThunk(
	'quizpress/deleteCertificate',
	async ( id, thunkAPI ) => {
		try {
			const res = await API.post(
				`${ namespace }qp_certificate/${ Number( id ) }`,
				{ force: true },
				{
					headers: {
						'X-HTTP-Method-Override': 'DELETE',
					},
				}
			);

			if ( res?.data?.deleted ) {
				handleSliceSuccess(
					thunkAPI,
					'Certificate deleted successfully'
				);
				return res?.data?.previous;
			}

			return thunkAPI.rejectWithValue( {
				message: __( 'Failed to delete.', 'quizpress' ),
				success: false,
			} );
		} catch ( e ) {
			return handleSliceError( thunkAPI, e );
		}
	}
);

const certificate = createSlice( {
	name: 'certificates',
	initialState: {
		data: [],
		totalItems: 0,
		currentPage: 1,
		loading: false,
		itemPerPage: 10,
	},
	reducers: {
		updateCertificateCurrentPage: ( state, actions ) => {
			state.currentPage = actions.payload;
		},
		updateCertificateItemPerPage: ( state, actions ) => {
			state.itemPerPage = actions.payload;
		},
		clearCertificateState: ( state ) => {
			state.data = false;
		},
	},
	extraReducers: ( builder ) => {
		builder
			.addCase( fetchAllCertificates.fulfilled, ( state, action ) => {
				const { data, totalItems, status, currentPage, itemPerPage } =
					action.payload;
				state.data = data;
				state.totalItems = totalItems;
				state.currentPage = currentPage;
				state.itemPerPage = itemPerPage;
			} )
			// update Certificate
			.addCase( updateCertificate.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.map( ( item ) => {
					if ( Number( item.id ) === Number( action.payload.id ) ) {
						return { ...item, ...action.payload };
					}
					return item;
				} );
			} )
			// update Certificate status
			.addCase( certificateStatusUpdate.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.map( ( item ) => {
					if ( Number( item.id ) === Number( action.payload.id ) ) {
						return { ...item, ...action.payload };
					}
					return item;
				} );
			} )
			// Restore Certificate
			.addCase( restoreCertificate.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.map( ( item ) => {
					if ( Number( item.id ) === Number( action.payload.id ) ) {
						return { ...item, ...action.payload };
					}
					return item;
				} );
			} )
			// Move Certificate To Trash
			.addCase( moveCertificateToTrash.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.map( ( item ) => {
					if ( Number( item.id ) === Number( action.payload.id ) ) {
						return { ...item, ...action.payload };
					}
					return item;
				} );
			} )
			// Delete Certificate
			.addCase( deleteCertificate.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.filter(
					( item ) =>
						Number( item.id ) !== Number( action.payload.id )
				);
			} )
			.addCase( makePrimaryCertificate.fulfilled, ( state, action ) => {
				state.loading = false;
				state.data = state.data.map( ( item ) => {
					if ( Number( item.id ) === Number( action.payload ) ) {
						return { ...item, ...action.payload };
					}
					return item;
				} );
			} );
	},
} );

export const { updateQuizCurrentPage, updateQuizItemPerPage } =
	certificate.actions;
export default certificate.reducer;
certificate;
