import React, { useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { useDispatch, useSelector } from 'react-redux';
import {
	downloadMediaFileById,
	hideHtmlTags,
	questionTypeOptions,
	sliceString,
	useQuery,
} from '@QPUtils/helper';
import {
	attemptReviewSubmit,
	fetchAttemptById,
	getQuizAttemptDetails,
} from '@QPRedux/Slices/quizInsightsSlice/quizInsightsSlice';
import { Button, Flex, Span } from '@chakra-ui/react';
import ListTable from '@QPComponents/ListTable';
import { Heading } from '@chakra-ui/react';

export default function AttemptAnswerDetails() {
	const attempts = useSelector( ( state ) => state.quizInsights );
	const [ attemptDetails, setAttemptDetails ] = useState( [] );

	const [ dataFetchingStatus, setDataFetchingStatus ] = useState( false );

	const dispatch = useDispatch();

	const location = useQuery();
	const id = location.get( 'id' );

	const handleFetch = ( attempt ) => {
		setDataFetchingStatus( true );
		dispatch(
			getQuizAttemptDetails( {
				attempt_id: id,
				user_id: attempt?._user?.ID,
			} )
		)
			.then( ( { payload } ) => {
				setAttemptDetails( payload );
			} )
			.finally( () => {
				setDataFetchingStatus( false );
			} );
	};

	useEffect( () => {
		const currentAttempt = attempts.data.find(
			( item ) => Number( item.attempt_id ) === Number( id )
		);
		if ( currentAttempt ) {
			handleFetch( currentAttempt );
		}
	}, [ attempts.data ] );

	const columns = [
		{
			name: __( 'Type', 'quizpress' ),
			cell: ( row ) => {
				const option = questionTypeOptions
					.flatMap( ( item ) => item.options )
					?.find( ( i ) => i.value === row?.question_type );
				return (
					<Span>
						{
							//translate: %s
							sprintf( __( '%s', 'quizpress' ), option?.label )
						}
					</Span>
				);
			},
		},
		{
			name: __( 'Question', 'quizpress' ),
			cell: ( row ) => (
				<Span
					className="quizpress-tooltip quizpress-tooltip--top"
					data-tooltip={ hideHtmlTags(
						sprintf( __( `%s`, 'quizpress' ), row?.question_title )
					) }
					dangerouslySetInnerHTML={ {
						__html: sliceString(
							sprintf(
								__( `%s`, 'quizpress' ),
								row?.question_title
							)
						),
					} }
				/>
			),
		},
		{
			name: __( 'Correct Answer', 'quizpress' ),
			cell: ( row ) => {
				const correctAnswers = ! row?.correct_answer
					? []
					: row?.correct_answer.map( ( i ) => i.answer_title );
				return (
					<Span
						className="quizpress-tooltip quizpress-tooltip--top"
						data-tooltip={ hideHtmlTags(
							correctAnswers.length > 0
								? sprintf(
										__( '%s', 'quizpress' ),
										correctAnswers.join( ', ' )
								  )
								: null
						) }
						dangerouslySetInnerHTML={ {
							__html: sliceString(
								correctAnswers.length > 0
									? sprintf(
											__( '%s', 'quizpress' ),
											correctAnswers.join( ', ' )
									  )
									: null
							),
						} }
					/>
				);
			},
		},
		{
			name: __( 'Given Answer', 'quizpress' ),
			cell: ( row ) => {
				const givenAnswers = ! row?.given_answer
					? []
					: row?.given_answer.map( ( i ) => i.answer_title );

				const option = questionTypeOptions
					.flatMap( ( item ) => item.options )
					?.find( ( i ) => i.value === row?.question_type );

				const fileUploadQuestionType = option?.value === 'file_upload';

				if ( fileUploadQuestionType ) {
					const fileId = Number(
						row?.given_answer?.[ 0 ]?.answer_title
					);

					return (
						<Button
							border="none"
							bg="transparent"
							color="var(--quizpress-primary)"
							cursor="pointer"
							textDecoration="underline"
							fontSize="14px"
							fontWeight="500"
							p={ 0 }
							h={ 0 }
							onClick={ () => downloadMediaFileById( fileId ) }
						>
							{ __( 'Download File', 'quizpress' ) }
						</Button>
					);
				}

				return (
					<Span
						className="quizpress-tooltip quizpress-tooltip--top"
						data-tooltip={ hideHtmlTags(
							givenAnswers.length > 0
								? sprintf(
										__( '%s', 'quizpress' ),
										givenAnswers.join( ', ' )
								  )
								: null
						) }
						dangerouslySetInnerHTML={ {
							__html: sliceString(
								givenAnswers.length > 0
									? sprintf(
											__( '%s', 'quizpress' ),
											givenAnswers.join( ', ' )
									  )
									: null
							),
						} }
					/>
				);
			},
		},
		{
			name: __( 'Answer', 'quizpress' ),
			cell: ( row ) => (
				<Span
					m={ 0 }
					fontSize="md"
					className={ `quizpress-status quizpress-status--${
						row?.is_correct ? 'passed' : 'failed'
					}` }
				>
					{ row?.is_correct
						? __( 'correct', 'quizpress' )
						: __( 'incorrect', 'quizpress' ) }
				</Span>
			),
		},
		{
			name: __( 'Review', 'quizpress' ),
			cell: ( row ) => (
				<Flex alignItems="center" gap={ 3 }>
					<Button
						color="#24a148"
						bg="#e9f5ec"
						variant="solid"
						size="sm"
						onClick={ () => {
							dispatch(
								attemptReviewSubmit( {
									attempt_answer_id: row.attempt_answer_id,
									attempt_id: id,
									question_id: row.question_id,
									quiz_id: row.quiz_id,
									user_id: row.user_id,
									mark_as: 'correct',
								} )
							).then( () => {
								dispatch( fetchAttemptById( id ) );
							} );
						} }
					>
						<Span className="quizpress-icon quizpress-icon--check quizpress-success" />
					</Button>
					<Button
						bg="#fedbdb"
						variant="solid"
						size="sm"
						onClick={ () => {
							dispatch(
								attemptReviewSubmit( {
									attempt_answer_id: row.attempt_answer_id,
									attempt_id: id,
									question_id: row.question_id,
									quiz_id: row.quiz_id,
									user_id: row.user_id,
									mark_as: 'incorrect',
								} )
							).then( () => {
								dispatch( fetchAttemptById( id ) );
							} );
						} }
					>
						<Span className="quizpress-icon quizpress-icon--close quizpress-danger" />
					</Button>
				</Flex>
			),
		},
	];

	return (
		<Flex direction="column" gap={ 3 }>
			<Heading m={ 0 }>
				{ __( 'Attempt Answer Details', 'quizpress' ) }
			</Heading>

			<ListTable
				columns={ columns }
				data={ attemptDetails ?? [] }
				showSubHeader={ false }
				subHeaderComponent={ false }
				isRowSelectable={ false }
				showColumnFilter={ false }
				noDataText={ __(
					'Please, complete Quizzes to see the available list here.',
					'quizpress'
				) }
				getSelectRowValue={ ( selectedRow ) => {} }
				showPagination={ false }
				totalItems={ attemptDetails?.length ?? 0 }
				dataFetchingStatus={ dataFetchingStatus }
				suffix="quiz-insight-details-table"
			/>
		</Flex>
	);
}
