import React, { useContext } from 'react';
import { Button, Flex, Text } from '@chakra-ui/react';
import { __, sprintf } from '@wordpress/i18n';
import { primaryBtn } from '../../../assets/scss/chakra/recipe';
import { useSelector } from 'react-redux';
import { user_id } from '@QPUtils/helper';
import Failed from './ResultCards/Failed';
import Congratulatory from './ResultCards/Congratulatory';
import Pending from './ResultCards/Pending';
import { QuizStatusContext } from './QuizContext';
import Preloader from '@QPComponents/Loader/Preloader';

const AttemptsStarter = ( {
	attemptsData,
	quizID,
	currentAttempt,
	handleStartQuiz,
} ) => {
	const { starterLoading, attemptsCount } = useContext( QuizStatusContext );
	const quizzes = useSelector( ( state ) => state.quizzes );
	const currentQuiz = quizzes.data[ 0 ];

	const isSurvey = currentQuiz?.meta?.quizpress_quiz_type === 'survey';
	const isPoll = currentQuiz?.meta?.quizpress_quiz_type === 'poll';
	const isExam = currentQuiz?.meta?.quizpress_quiz_type === 'exams';

	const allAttempts = attemptsData?.attempts ?? [];
	const submittedAttempt = currentAttempt
		? allAttempts.find(
				( att ) =>
					Number( att.attempt_id ) ===
					Number( currentAttempt?.attempt_id )
		  )
		: allAttempts[ allAttempts.length - 1 ];

	const status = attemptsData?.status;

	const renderTime = ( unit ) => {
		switch ( unit ) {
			case 'seconds':
				return 'sec';
			case 'minutes':
				return 'min';
			case 'hours':
				return 'hrs';
			default:
				return 'min';
		}
	};

	const cardProps = {
		attempts: allAttempts,
		quizID,
		handleStartQuiz,
		submittedAttempt,
		type: isSurvey ? 'survey' : 'quiz',
		status,
	};

	function activityType() {
		if ( isSurvey ) {
			return 'survey';
		} else if ( isPoll ) {
			return 'poll';
		} else if ( isExam ) {
			return 'exams';
		}
		return 'quiz';
	}

	const showWaitingText =
		! Boolean( status ) &&
		currentQuiz?.meta?.quizpress_quiz_auto_start &&
		! allAttempts.length &&
		! attemptsCount &&
		Number( user_id );
	const showStarter =
		( ! Boolean( status ) && ! allAttempts.length && ! attemptsCount ) ||
		! Number( user_id );

	if ( showWaitingText ) {
		return (
			<Text m={ 0 }>
				{ __( 'Please wait until the quiz starts…', 'quizpress' ) }
			</Text>
		);
	}

	if ( showStarter ) {
		return (
			<Starter
				currentQuiz={ currentQuiz }
				attempts={ allAttempts }
				handleStartQuiz={ handleStartQuiz }
				starterLoading={ starterLoading }
				renderTime={ renderTime }
				type={ activityType() }
			/>
		);
	}

	switch ( status ) {
		case 'pending':
			return <Pending { ...cardProps } />;

		case 'failed':
			return <Failed { ...cardProps } />;

		case 'passed':
			return <Congratulatory { ...cardProps } />;

		default:
			return <Preloader />;
	}
};

export default AttemptsStarter;

const Starter = ( {
	currentQuiz,
	attempts,
	renderTime,
	handleStartQuiz,
	starterLoading,
	type = 'quiz',
} ) => {
	function infoLabel() {
		switch ( type ) {
			case 'quiz':
				return 'Quiz';
			case 'survey':
				return 'Survey';
			case 'exams':
				return 'Exams';
			default:
				return 'Poll';
		}
	}
	const isQuiz = type === 'quiz' || type === 'exams';

	return (
		<React.Fragment>
			<Flex width="100%" maxW="420px" flexDirection="column" gap={ 6 }>
				<Flex
					flexDirection="column"
					background="#EFF6FF"
					borderRadius="6px"
					boxShadow="0 0 1px 0 rgba(20, 26, 36, 0.30), 0 2px 4px 0 rgba(20, 26, 36, 0.10)"
					padding={ 6 }
					gap={ 6 }
				>
					<Text
						color="var(--quizpress-primary)"
						fontSize="1.125rem"
						fontWeight="600"
					>
						{ sprintf( __( `%s Info`, 'quizpress' ), infoLabel() ) }
					</Text>
					<Flex flexDirection="column" gap={ 4 } paddingTop={ 6 }>
						<Flex
							alignItems="center"
							justifyContent="space-between"
						>
							<Text fontSize="0.875rem">
								{ __( 'Total Question', 'quizpress' ) }
							</Text>
							<Text fontSize="1rem" fontWeight="500">
								{ __(
									currentQuiz?.meta?.quizpress_quiz_questions
										.length,
									'quizpress'
								) }
							</Text>
						</Flex>
						{ isQuiz && (
							<Flex
								alignItems="center"
								justifyContent="space-between"
							>
								<Text fontSize="0.875rem">
									{ __( 'Passing Grade', 'quizpress' ) }
								</Text>

								<Text fontSize="1rem" fontWeight="500">
									{ __(
										`${ currentQuiz?.meta?.quizpress_quiz_passing_grade }%`,
										'quizpress'
									) }
								</Text>
							</Flex>
						) }
						{ Number( user_id ) ? (
							<Flex
								alignItems="center"
								justifyContent="space-between"
							>
								<Text fontSize="0.875rem">
									{ __( 'Total Attempted', 'quizpress' ) }
								</Text>
								<Text fontSize="1rem" fontWeight="500">
									{ __( attempts.length, 'quizpress' ) }
								</Text>
							</Flex>
						) : (
							''
						) }
						<Flex
							alignItems="center"
							justifyContent="space-between"
						>
							<Text fontSize="0.875rem">
								{ __( 'Quiz Time', 'quizpress' ) }
							</Text>
							<Text fontSize="1rem" fontWeight="500">
								{ Number(
									currentQuiz?.meta?.quizpress_quiz_time
								) === 0
									? __( 'Unlimited', 'quizpress' )
									: sprintf(
											__( `%s %s`, 'quizpress' ),
											currentQuiz?.meta
												?.quizpress_quiz_time,
											renderTime(
												currentQuiz?.meta
													?.quizpress_quiz_time_unit
											)
									  ) }
							</Text>
						</Flex>
					</Flex>
					{ Number( user_id ) ? (
						<Button
							{ ...primaryBtn }
							onClick={ handleStartQuiz }
							loading={ starterLoading }
							disabled={ starterLoading }
						>
							{ __( 'Start Quiz', 'quizpress' ) }
						</Button>
					) : (
						<Flex
							flexDirection="column"
							alignItems="center"
							gap={ 2 }
						>
							<Button
								{ ...primaryBtn }
								onClick={ handleStartQuiz }
								loading={ starterLoading }
								disabled={ starterLoading }
							>
								{ __( 'Login to Start Quiz', 'quizpress' ) }
							</Button>
							<Text color="#738496" fontSize="0.625rem">
								{ __(
									'Create a free account to track your quiz progress.',
									'quizpress'
								) }
							</Text>
						</Flex>
					) }
				</Flex>
			</Flex>
		</React.Fragment>
	);
};
