import React from 'react';
import { __ } from '@wordpress/i18n';
import { Button, Circle, Flex, Span, Text } from '@chakra-ui/react';
import { FieldArray, useFormikContext } from 'formik';
import UploadImage from '@QPComponents/UploadImage';
import CustomSwitch from '@QPComponents/CustomSwitch';
import { getInitialAnswerValue } from '../../containers/BackendDashboard/pages/Quizzes/newQuiz/helper';
import GstText from '@QPComponents/GstText.js';

const ImageAnswer = ( { ansName, ansVal, type } ) => {
	const { setFieldValue } = useFormikContext();

	const isSingleChoice =
		type === 'single_choice' || type === 'single_choice_horizontal';

	const renderLayout = ( { item, index: ansIndex, self, remove } ) => (
		<Flex gap={ 3 } alignItems="flex-start" width="100%">
			<Flex border={ '1px dashed var(--quizpress-secondary-color)' }>
				<UploadImage
					saveValueHandler={ setFieldValue }
					value={ item?.image_id }
					name={ `${ ansName }.${ ansIndex }.image_id` }
				/>
			</Flex>
			<Flex
				gap={ 2 }
				alignItems="center"
				p={ 2 }
				border="1px solid var(--quizpress-border-color)"
				borderRadius="4px"
			>
				<Text fontWeight={ 500 } className="quizpress-title">
					{ __( 'Correct', 'quizpress' ) }
				</Text>
				<CustomSwitch
					name={ `${ ansName }.${ ansIndex }.is_correct` }
					value={ Boolean( item.is_correct ) }
					onChange={ ( e ) => {
						const checked = e.target.checked;

						if ( isSingleChoice ) {
							ansVal.forEach( ( _, i ) => {
								setFieldValue(
									`${ ansName }.${ i }.is_correct`,
									false
								);
							} );
						}

						setFieldValue(
							`${ ansName }.${ ansIndex }.is_correct`,
							checked
						);
					} }
				/>
			</Flex>
			<Button variant="ghost" onClick={ () => remove( ansIndex ) }>
				<Span className="quizpress-icon quizpress-icon--trash-danger" />
			</Button>
		</Flex>
	);

	return (
		<Flex direction="column" gap={ 3 } alignItems="center">
			<FieldArray name={ ansName }>
				{ ( { push, remove } ) => {
					return (
						<>
							{ ! ansVal?.length ? (
								<GstText
									type="warning"
									label={ __(
										'No answers found. Please add answers.',
										'quizpress'
									) }
									showBorder={ true }
								/>
							) : (
								ansVal?.map( ( item, ansIndex, self ) =>
									renderLayout( {
										item,
										index: ansIndex,
										self,
										remove,
									} )
								)
							) }
							<Button
								variant="outline"
								width="fit-content"
								color="var(--quizpress-primary)"
								borderColor="var(--quizpress-primary)"
								onClick={ () => push( getInitialAnswerValue ) }
							>
								<Span className="quizpress-icon quizpress-icon--plus quizpress-primary" />
								{ __( 'Add Answer', 'quizpress' ) }
							</Button>
						</>
					);
				} }
			</FieldArray>
		</Flex>
	);
};

export default ImageAnswer;
