import React, { useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import { Button, Flex, Heading, Textarea } from '@chakra-ui/react';
import { primaryBtn } from '../../../../../assets/scss/chakra/recipe';
import { useDispatch } from 'react-redux';
import { makeRequest, useQuery } from '@QPUtils/helper';
import { updateAttemptFeedback } from '@QPRedux/Slices/quizInsightsSlice/quizInsightsSlice';

export default function InstructorFeedback() {
	const [ feedback, setFeedback ] = React.useState( '' );

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

	useEffect( () => {
		if ( id && ! feedback ) {
			makeRequest( 'admin/get_quiz_attempt_feedback', {
				attempt_id: id,
			} ).then( ( res ) => {
				setFeedback( res?.feedback );
			} );
		}
	}, [ id ] );

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

			<Textarea
				className="quizpress-textarea"
				onChange={ ( e ) => setFeedback( e.target.value ) }
				defaultValue={ feedback }
			/>

			<Button
				{ ...primaryBtn }
				width="fit-content"
				onClick={ () => {
					dispatch(
						updateAttemptFeedback( {
							attempt_id: id,
							feedback,
						} )
					);
				} }
				fontWeight="500"
			>
				{ __( 'Update Feedback', 'quizpress' ) }
			</Button>
		</Flex>
	);
}
