import { isArray, makeRequest } from '@QPUtils/helper';

export const getInitialAnswerValue = {
	quiz_id: 0,
	answer_points: 1,
	question_id: '',
	answer_title: '',
	answer_content: '',
	is_correct: false,
	image_id: 0,
	view_format: '',
	answer_order: 0,
};

export const getInitialQuestionValue = ( settings, qstOrder = null ) => {
	return {
		question_title: '',
		question_name: '',
		question_content: '',
		question_explanation: '',
		question_status: 'publish',
		question_level: '',
		question_type:
			settings?.data?.quizpress_questions_default_type ?? 'single_choice',
		answer_type: 'plain_text',
		question_score: 1,
		question_negative_score: 0,
		question_settings: {
			display_points: false,
			answer_required: true,
			random_answer: true,
		},
		question_order: qstOrder ?? 0,
		answers: [],
	};
};

export const quizFormInitialValues = ( id = null, data = null, settings ) => {
	if ( id && data && data.length > 0 ) {
		data = data.find( ( item ) => Number( item.id ) === Number( id ) );

		const commonMeta = {
			quizpress_quiz_type: data.meta.quizpress_quiz_type ?? 'quiz',
			quizpress_quiz_time: data.meta.quizpress_quiz_time ?? 0,
			quizpress_quiz_time_unit:
				data.meta.quizpress_quiz_time_unit ?? 'minutes',
			quizpress_quiz_hide_quiz_time:
				data.meta.quizpress_quiz_hide_quiz_time ?? false,
			quizpress_quiz_auto_start:
				data.meta.quizpress_quiz_auto_start ?? false,
			quizpress_quiz_schedule_enabled:
				data.meta.quizpress_quiz_schedule_enabled ?? false,
			quizpress_quiz_start_datetime:
				data.meta.quizpress_quiz_start_datetime ?? '',
			quizpress_quiz_end_datetime:
				data.meta.quizpress_quiz_end_datetime ?? '',
			quizpress_quiz_passing_grade:
				data.meta.quizpress_quiz_passing_grade ?? 80,
			quizpress_quiz_grade_system:
				data.meta.quizpress_quiz_grade_system ?? 'percentage',
			quizpress_quiz_max_attempts_allowed:
				data.meta.quizpress_quiz_max_attempts_allowed ?? 10,
			quizpress_quiz_max_questions_for_answer:
				data.meta.quizpress_quiz_max_questions_for_answer ?? 0,
			quizpress_quiz_questions_order:
				data.meta.quizpress_quiz_questions_order ?? 'random',
			quizpress_quiz_hide_question_number:
				data.meta.quizpress_quiz_hide_question_number ?? false,
			quizpress_quiz_short_answer_characters_limit:
				data.meta.quizpress_quiz_short_answer_characters_limit ?? 10,
			quizpress_quiz_feedback_mode:
				data.meta.quizpress_quiz_feedback_mode ?? 'default',
			quizpress_quiz_show_correct_answers:
				data.meta.quizpress_quiz_show_correct_answers ?? false,
			quizpress_quiz_allow_review:
				data.meta.quizpress_quiz_allow_review ?? true,
			quizpress_quiz_show_score:
				data.meta.quizpress_quiz_show_score ?? true,
			quizpress_quiz_anonymous:
				data.meta.quizpress_quiz_anonymous ?? false,
			quizpress_quiz_layout: data.meta.quizpress_quiz_layout ?? 'classic',
			quizpress_quiz_start_button_label:
				data.meta.quizpress_quiz_start_button_label ?? 'Start Quiz',
			quizpress_quiz_submit_button_label:
				data.meta.quizpress_quiz_submit_button_label ?? 'Submit Answer',
			quizpress_quiz_questions: data.meta.quizpress_quiz_questions ?? [],
			quizpress_quiz_force_all_questions_required:
				data.meta.quizpress_quiz_force_all_questions_required ?? false,
			quizpress_quiz_hint_text: data.meta.quizpress_quiz_hint_text ?? '',
			quizpress_quiz_pass_reattempt:
				data.meta.quizpress_quiz_pass_reattempt ?? false,
			quizpress_quiz_explanation_enabled:
				data.meta.quizpress_quiz_explanation_enabled ?? false,
		};

		return {
			...data,
			title: data.title.rendered,
			content: data.content.rendered,
			meta: {
				...data.meta,
				...commonMeta,
			},
		};
	}
	return {
		title: '',
		slug: '',
		content: '',
		quizpress_quiz_category: [],
		quizpress_quiz_tags: [],
		status: 'draft',
		meta: {
			quizpress_quiz_type: 'quiz',
			quizpress_quiz_time: 0,
			quizpress_quiz_time_unit: 'minutes',
			quizpress_quiz_hide_quiz_time: false,
			quizpress_quiz_auto_start: false,
			quizpress_quiz_schedule_enabled: false,
			quizpress_quiz_start_datetime: '',
			quizpress_quiz_end_datetime: '',
			quizpress_quiz_passing_grade: 80,
			quizpress_quiz_grade_system: 'percentage',
			quizpress_quiz_max_attempts_allowed: 10,
			quizpress_quiz_max_questions_for_answer: 0,
			quizpress_quiz_questions_order: 'random',
			quizpress_quiz_hide_question_number: false,
			quizpress_quiz_short_answer_characters_limit: 10,
			quizpress_quiz_feedback_mode: 'default',
			quizpress_quiz_show_correct_answers: false,
			quizpress_quiz_allow_review: true,
			quizpress_quiz_show_score: true,
			quizpress_quiz_anonymous: false,
			quizpress_quiz_layout: 'classic',
			quizpress_quiz_start_button_label: 'Start Quiz',
			quizpress_quiz_submit_button_label: 'Submit Answer',
			quizpress_quiz_questions: [],
			quizpress_quiz_force_all_questions_required: false,
			quizpress_quiz_hint_text: '',
			quizpress_quiz_pass_reattempt: false,
			quizpress_quiz_explanation_enabled: false,
		},
		questions: [],
	};
};

export const handleUpdateQuestionOrder = async ( quizValues, questions ) => {
	await makeRequest( 'admin/update_quiz_question_order', {
		quiz_id: quizValues.id,
		questions: JSON.stringify( questions ),
	} );
};

export const sortByOrder = ( arr ) =>
	[ ...arr ].sort(
		( a, b ) => Number( a.question_order ) - Number( b.question_order )
	);

export const getPaginatedItems = ( items, page, perPage ) =>
	items.slice( ( page - 1 ) * perPage, page * perPage );

export const makeQstMeta = ( questions ) =>
	questions.map( ( q ) => ( {
		id: q.question_id,
		title: q.question_title,
	} ) );

const state = {};
const listeners = new Set();

export const toggleStore = {
	subscribe: ( listener ) => {
		listeners.add( listener );
		return () => listeners.delete( listener );
	},

	getSnapshot: ( quizId ) => {
		if ( ! state[ quizId ] ) {
			state[ quizId ] = new Set();
		}
		return state[ quizId ];
	},

	updateStore: ( quizId, anchorIndex, operation ) => {
		if ( ! [ 'insert', 'delete' ].includes( operation ) ) {
			console.error( 'Invalid operation type passed to updateStore.' );
			return;
		}

		if ( ! state[ quizId ] ) {
			state[ quizId ] = new Set();
		}
		const next = new Set();
		const anchorId = `qst-${ anchorIndex }`;
		const shiftAmount = operation === 'insert' ? 1 : -1;

		state[ quizId ].forEach( ( item ) => {
			const numericalIndex = Number( item.split( '-' )[ 1 ] );
			let newIndex = numericalIndex;

			if ( operation === 'delete' ) {
				if ( item === anchorId ) {
					return;
				}
				if ( numericalIndex > anchorIndex ) {
					newIndex += shiftAmount;
				}
			} else if ( operation === 'insert' ) {
				if ( numericalIndex >= anchorIndex ) {
					newIndex += shiftAmount;
				}
			}

			next.add( `qst-${ newIndex }` );
		} );

		state[ quizId ] = next;
		listeners.forEach( ( l ) => l() );
	},

	toggle: ( quizId, item ) => {
		if ( ! state[ quizId ] ) {
			state[ quizId ] = new Set();
		}
		const next = new Set( state[ quizId ] );
		if ( next.has( item ) ) {
			next.delete( item );
		} else {
			next.add( item );
		}
		state[ quizId ] = next;
		listeners.forEach( ( l ) => l() );
	},

	isOpen: ( quizId, item ) => {
		if ( ! state[ quizId ] ) {
			state[ quizId ] = new Set();
		}
		return state[ quizId ].has( item );
	},
};
