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

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

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

	const renderLayout = ( { item, index: ansIndex, self, remove } ) => {
		return (
			<Flex gap={ 3 } alignItems="center" width="100%">
				<Field
					as={ Textarea }
					padding="10px 12px"
					name={ `${ ansName }.${ ansIndex }.answer_title` }
					defaultValue={ item.answer }
					placeholder={ __( 'Enter answer', 'quizpress' ) }
					className="quizpress-input"
					rows={ 5 }
				/>
				<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" alignItems="center" gap={ 3 }>
			<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 SingleChoiceRich;
