import { Flex } from '@chakra-ui/react';
import QuizAnswer from './QuizAnswer';
import { __, sprintf } from '@wordpress/i18n';
import { Span } from '@chakra-ui/react';

export const getFormikQuizSteps = (
	questions,
	qstOrder,
	totalAttempts,
	currentQuiz
) => {
	if ( ! questions?.length ) {
		return [ { component: QuizAnswer } ];
	}

	const qstShallowCopy = [ ...questions ];
	let newQstOrder = [];

	if ( qstOrder === 'asc' ) {
		newQstOrder = qstShallowCopy.sort(
			( a, b ) => a.question_id - b.question_id
		);
	} else if ( qstOrder === 'desc' ) {
		newQstOrder = qstShallowCopy.sort(
			( a, b ) => b.question_id - a.question_id
		);
	} else if ( qstOrder === 'random' ) {
		newQstOrder = qstShallowCopy.sort( () => Math.random() - 0.5 );
	}

	return newQstOrder.map( ( question, index, self ) => ( {
		component: () => (
			<QuizAnswer
				question={ question }
				stepIndex={ index }
				self={ self }
				totalAttempts={ totalAttempts }
				currentQuiz={ currentQuiz }
			/>
		),
		question,
	} ) );
};

export const renderQuizTime = ( currentQuiz ) => {
	const time = currentQuiz?.meta?.quizpress_quiz_time;

	if ( time === Number( 0 ) ) {
		return (
			<Flex
				gap={ 2 }
				alignItems="center"
				fontSize="sm"
				m={ 0 }
				fontWeight="500"
			>
				<Span className="quizpress-icon quizpress-icon--clock" />
				<Span color="var(--quizpress-warn-muted)">
					{ __( 'Time Limit:', 'quizpress' ) }
				</Span>
				<Span>{ __( `No Limit`, 'quizpress' ) }</Span>
			</Flex>
		);
	}

	switch ( currentQuiz?.meta?.quizpress_quiz_time_unit ) {
		case 'seconds':
			return (
				<Flex
					gap={ 2 }
					alignItems="center"
					fontSize="sm"
					m={ 0 }
					fontWeight="500"
				>
					<Span className="quizpress-icon quizpress-icon--clock" />
					<Span color="var(--quizpress-warn-muted)">
						{ __( 'Time Limit', 'quizpress' ) }
					</Span>
					<Span>
						{ sprintf( __( `%s secs`, 'quizpress' ), time ) }
					</Span>
				</Flex>
			);
		case 'minutes':
			return (
				<Flex
					gap={ 2 }
					alignItems="center"
					fontSize="sm"
					m={ 0 }
					fontWeight="500"
				>
					<Span className="quizpress-icon quizpress-icon--clock" />
					<Span color="var(--quizpress-warn-muted)">
						{ __( 'Time Limit', 'quizpress' ) }
					</Span>
					<Span>
						{ sprintf( __( `%s mins`, 'quizpress' ), time ) }
					</Span>
				</Flex>
			);
		case 'hours':
			return (
				<Flex
					gap={ 2 }
					alignItems="center"
					fontSize="sm"
					m={ 0 }
					fontWeight="500"
				>
					<Span className="quizpress-icon quizpress-icon--clock" />
					<Span color="var(--quizpress-warn-muted)">
						{ __( 'Time Limit', 'quizpress' ) }
					</Span>
					<Span>
						{ sprintf( __( `%s hrs`, 'quizpress' ), time ) }
					</Span>
				</Flex>
			);
	}
};

export const extractFillBlanks = ( parts, userAnswer ) => {
	const values = [];
	let temp = userAnswer;

	if ( ! temp ) {
		return values;
	}

	for ( let i = 0; i < parts.length - 1; i++ ) {
		const start = parts[ i ];
		const end = parts[ i + 1 ];

		// Remove leading fixed part
		if ( temp.startsWith( start ) ) {
			temp = temp.slice( start.length );
		}

		// Extract the text until next fixed part
		const idx = temp.indexOf( end );
		const value = temp.slice( 0, idx );

		values.push( value.trim() );
		temp = temp.slice( idx ); // cut consumed part
	}

	return values;
};

export const buildSubmitableAnswers = ( question, values ) => {
	const allAnswers = question.answers ?? [];
	const userAnswer = values?.answers?.[ question.question_id ];

	if ( question.question_type === 'fill_in_the_blanks' ) {
		const parts = allAnswers[ 0 ]?.answer_title.split( '{dash}' );
		const blanks = extractFillBlanks( parts, userAnswer );
		const blanksAnswers = blanks.map( ( ans, idx ) => ( {
			id: idx,
			value: ans,
		} ) );

		return [
			{
				answer_id: allAnswers[ 0 ]?.answer_id ?? 0,
				answer: JSON.stringify( blanksAnswers ),
			},
		];
	} else if ( question.question_type === 'file_upload' ) {
		return [
			{
				answer_id: 0,
				answer: JSON.stringify( userAnswer[ 0 ] ),
			},
		];
	} else if ( allAnswers.length > 0 ) {
		const selected = allAnswers.filter( ( ans ) =>
			userAnswer?.some?.(
				( id ) => Number( id ) === Number( ans.answer_id )
			)
		);

		return selected.map( ( ans ) => ( {
			answer_id: ans.answer_id ?? 0,
			answer: ans.answer_title ?? '',
		} ) );
	} else if ( userAnswer ) {
		return [
			{
				answer_id: 0,
				answer: userAnswer,
			},
		];
	}
	return [];
};
