import React, { useContext, useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { Badge, Button, Flex, Text } from '@chakra-ui/react';
import { useSelector } from 'react-redux';
import QuizDetailsModal from './QuizDetailsModal';
import { Span } from '@chakra-ui/react';
import { formatDateTime, makeRequest } from '@QPUtils/helper';
import { InstructorFeedBack, isAllowReAttempt } from '../helper';
import { QuizStatusContext } from '../QuizContext';

const Failed = ( { attempts, handleStartQuiz, submittedAttempt } ) => {
	const { starterLoading } = useContext( QuizStatusContext );
	const quizzes = useSelector( ( state ) => state.quizzes );
	const currentQuiz = quizzes.data[ 0 ];
	const [ openDetailsModal, setOpenDetailsModal ] = useState( false );
	const [ feedback, setFeedback ] = useState( '' );

	const isOpen = () => {
		setOpenDetailsModal( true );
	};
	const onRequestClose = () => {
		setOpenDetailsModal( false );
	};

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

	const successfulAttempts = attempts.filter(
		( attempt ) => attempt.attempt_status === 'passed'
	);
	const failedAttempts = attempts.filter(
		( attempt ) => attempt.attempt_status === 'failed'
	);

	useEffect( () => {
		makeRequest( `frontend/get_user_attempt_feedback`, {
			attempt_id: submittedAttempt?.attempt_id,
		} ).then( ( res ) => {
			setFeedback( res );
		} );
	}, [] );

	const acceptReAttempt = isAllowReAttempt(
		currentQuiz?.meta?.quizpress_quiz_feedback_mode,
		currentQuiz?.meta?.quizpress_quiz_max_attempts_allowed,
		attempts?.length
	);

	return (
		<>
			<Flex width="100%" flexDirection="column" gap={ 6 }>
				<Flex
					gap={ 6 }
					flexDirection={ {
						base: 'column',
						sm: 'column',
						md: 'column',
						lg: 'row',
					} }
				>
					{ acceptReAttempt && (
						<Flex
							flexDirection="column"
							width={ {
								base: '100%',
								sm: '100%',
								md: '80%',
								lg: '45%',
							} }
							gap={ 3 }
						>
							<Flex
								flexDirection="column"
								borderRadius="6px"
								background="#EFF6FF"
								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"
								>
									{ __( 'Quiz Info', 'quizpress' ) }
								</Text>
								<Flex flexDirection="column" gap={ 4 }>
									<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>
									<Flex
										alignItems="center"
										justifyContent="space-between"
									>
										<Text fontSize="0.875rem">
											{ __( 'Quiz Time', 'quizepress' ) }
										</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
										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">
											{ __(
												'Successful Attempted',
												'quizpress'
											) }
										</Text>
										<Text fontSize="1rem" fontWeight="500">
											{ __(
												successfulAttempts.length,
												'quizpress'
											) }
										</Text>
									</Flex>
									<Flex
										alignItems="center"
										justifyContent="space-between"
									>
										<Text fontSize="0.875rem">
											{ __( 'Failed Attempted' ) }
										</Text>
										<Text fontSize="1rem" fontWeight="500">
											{ __(
												failedAttempts.length,
												'quizpress'
											) }
										</Text>
									</Flex>
									<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>
								</Flex>
							</Flex>
						</Flex>
					) }

					<Flex
						width={ {
							base: '100%',
							sm: '100%',
							md: '80%',
							lg: '55%',
						} }
						borderRadius="6px"
						background="#FFF2F2"
						boxShadow="0 0 1px 0 rgba(20, 26, 36, 0.30), 0 2px 4px 0 rgba(20, 26, 36, 0.10)"
						flexDirection="column"
						padding={ 6 }
						gap={ 8 }
					>
						<Flex justifyContent="space-between">
							<Flex alignItems="center" gap={ 2 }>
								<Text fontSize="1rem" fontWeight="500">
									{ sprintf(
										//translate: %s currentDate
										__( '%s', 'quizpress' ),
										formatDateTime(
											new Date(),
											'YYYY-MM-DD'
										)
									) }
								</Text>
							</Flex>
							<Badge
								background="#F15B50"
								fontSize="0.75rem"
								color="#FFF"
								borderRadius="25px"
							>
								<Span className="quizpress-icon quizpress-icon--close has-quizpress-blue-bg" />
								{ __( 'Failed' ) }
							</Badge>
						</Flex>

						<Flex justifyContent="space-between" paddingTop={ 3 }>
							<Flex flexDirection="column">
								<Text fontSize="0.875rem">
									{ __( 'Total Questions', 'quizpress' ) }
								</Text>
								<Text fontSize="1rem" fontWeight="500">
									{
										currentQuiz?.meta
											?.quizpress_quiz_questions.length
									}
								</Text>
							</Flex>
							<Flex flexDirection="column">
								<Text fontSize="0.875rem">
									{ __( 'Total Earned', 'quizpress' ) }
								</Text>
								<Text fontSize="1rem" fontWeight="500">
									{ __(
										`${ submittedAttempt?.earned_marks }`,
										'quizpress'
									) }
								</Text>
							</Flex>
						</Flex>

						<Flex justifyContent="space-between">
							<Flex flexDirection="column">
								<Text fontSize="0.875rem">
									{ __(
										'Total Answered Questions',
										'quizpress'
									) }
								</Text>
								<Text fontSize="1rem" fontWeight="500">
									{ __(
										`${ submittedAttempt?.total_answered_questions }`,
										'quizpress'
									) }
								</Text>
							</Flex>
						</Flex>

						<Flex justifyContent="space-between">
							{ acceptReAttempt && (
								<Button
									background="#F15B50"
									fontSize="0.875rem"
									color="#FFF"
									fontWeight="500"
									onClick={ handleStartQuiz }
									loading={ starterLoading }
									disabled={ starterLoading }
								>
									{ __( 'Re-attempt', 'quizpress' ) }
								</Button>
							) }
							<Button
								fontSize="0.875rem"
								border="1px solid #F15B50"
								color="#F15B50"
								background="transparent"
								fontWeight="500"
								onClick={ isOpen }
							>
								{ __( 'View Details', 'quizpress' ) }
							</Button>
						</Flex>
					</Flex>
				</Flex>

				<InstructorFeedBack feedback={ feedback } />
			</Flex>

			{ openDetailsModal && (
				<QuizDetailsModal
					isOpen={ isOpen }
					onRequestClose={ onRequestClose }
					attempts={ attempts }
					submittedAttempt={ submittedAttempt }
				/>
			) }
		</>
	);
};

export default Failed;
