import React from 'react';
import { __ } from '@wordpress/i18n';
import { Button, Flex, Span, Text } from '@chakra-ui/react';
import Select from 'react-select';
import {
	capitalizeFirstLetter,
	plugin_root_url,
	reactDebounce,
} from '@QPUtils/helper';
import {
	getInitialQuestionValue,
	handleUpdateQuestionOrder,
	toggleStore,
} from '../../helper';
import { useSelector } from 'react-redux';
import { useFormikContext } from 'formik';
import Search from '@QPComponents/Search';
import OptionMenu from '@QPComponents/OptionMenu';

const QuestionsHeader = ( {
	originalQsts,
	setFilteredQsts,
	setCurrentIndex,
	toggleOpen,
	filterOpen,
	setFilterOpen,
	setOpenImportModal,
	setCurrentPageNumber,
	currentPageNumber,
	rowsPerPage,
	setIsQuestionImportModalOpen,
} ) => {
	const settings = useSelector( ( state ) => state.settings );
	const { setFieldValue, values } = useFormikContext();

	const qstTypeOptions = [
		...new Set(
			originalQsts.map( ( item ) => item.question_type ).filter( Boolean )
		),
	].map( ( item ) => ( {
		value: item,
		label: capitalizeFirstLetter( item ),
	} ) );

	const handleSearch = reactDebounce( ( searchText ) => {
		if ( ! searchText ) {
			return setFilteredQsts( null );
		}

		const filtered = originalQsts.filter( ( q ) =>
			q.question_title.toLowerCase().includes( searchText.toLowerCase() )
		);

		setFilteredQsts( filtered );
		setCurrentPageNumber( 1 );
	}, 200 );

	const handleQuestionTypeFilter = ( option ) => {
		if ( ! option ) {
			return setFilteredQsts( null );
		}

		setFilteredQsts(
			originalQsts.filter( ( q ) => q.question_type === option.value )
		);
		setCurrentPageNumber( 1 );
	};

	const handleAddQst = () => {
		let updated;

		const startIndex = ( currentPageNumber - 1 ) * rowsPerPage;
		const endIndex = startIndex + rowsPerPage;

		const newQuestion = getInitialQuestionValue( settings, startIndex + 1 );

		if ( currentPageNumber === 1 ) {
			const updatedExistingOrder = originalQsts.map( ( q ) => ( {
				...q,
				question_order: Number( q.question_order ) + 1,
			} ) );
			updated = [ newQuestion, ...updatedExistingOrder ];
		} else {
			const before = originalQsts.slice( 0, startIndex );
			const currentPage = originalQsts.slice( startIndex, endIndex );
			const after = originalQsts.slice( endIndex );

			const updatedCurrentPage = [ newQuestion, ...currentPage ].map(
				( q, i ) => ( {
					...q,
					question_order: startIndex + i + 1,
				} )
			);

			const updatedAfter = after.map( ( q, i ) => ( {
				...q,
				question_order: startIndex + updatedCurrentPage.length + i + 1,
			} ) );

			updated = [ ...before, ...updatedCurrentPage, ...updatedAfter ];
		}

		const newQstOrderPayload = updated.map( ( q ) => ( {
			question_id: q.question_id,
			question_order: q.question_order,
		} ) );

		handleUpdateQuestionOrder( values, newQstOrderPayload );

		setFilteredQsts( null );
		setFieldValue( 'questions', updated ).then( () => {
			setCurrentIndex( startIndex );
			toggleStore.updateStore( values.id, startIndex, 'insert' );
			toggleOpen( `qst-${ startIndex }` );
		} );
	};

	return (
		<Flex
			justifyContent="space-between"
			alignItems="center"
			p="12px 16px"
			borderRadius="4px"
			bg="var(--quizpress-background)"
			boxShadow="var(--quizpress-shadow)"
			width="100%"
		>
			<Flex gap={ 3 } alignItems="center">
				<img
					src={ plugin_root_url + 'assets/images/quizpress-logo.svg' }
					alt="logo"
				/>
				<Flex direction="column" gap={ 1 }>
					<Text className="quizpress-title">
						{ __( 'Add questions for the quiz', 'quizpress' ) }
					</Text>
					<Text className="quizpress-sub-title-muted">
						<Span>{ __( 'Total Questions:', 'quizpress' ) }</Span>{ ' ' }
						<Span>{ originalQsts?.length }</Span>
					</Text>
				</Flex>
			</Flex>

			<Flex gap={ 3 } alignItems="center">
				<Button
					variant="outline"
					borderColor="var(--quizpress-primary)"
					color="var(--quizpress-primary)"
					onClick={ handleAddQst }
				>
					<Span className="quizpress-icon quizpress-icon--plus quizpress-primary" />
					{ __( 'Add Question', 'quizpress' ) }
				</Button>

				{ filterOpen && (
					<>
						<Select
							className="quizpress-select"
							classNamePrefix="quizpress-select"
							placeholder={ __(
								'Filter by question type',
								'quizpress'
							) }
							isSearchable
							isClearable
							options={ qstTypeOptions }
							onChange={ ( e ) => handleQuestionTypeFilter( e ) }
						/>
						<Search
							placeholder={ __( 'Search Items', 'quizpress' ) }
							onSearchHandler={ handleSearch }
						/>
						<Button
							variant="outline"
							borderColor="var(--quizpress-placing)"
							onClick={ () => setFilterOpen( false ) }
						>
							<Span className="quizpress-icon quizpress-icon--close quizpress-danger" />
						</Button>
					</>
				) }

				<OptionMenu
					icon="quizpress-icon quizpress-icon--menu-vertical"
					suffix="quiz-question-header-menu"
					options={ [
						{
							type: 'button',
							label: __( 'Filter', 'quizpress' ),
							icon: (
								<Span
									className="quizpress-icon quizpress-icon--filter"
									_before={ {
										fontSize: '14px',
									} }
								/>
							),
							onClick: () => {
								setFilterOpen( true );
							},
						},
						{
							type: 'button',
							label: __( 'CSV Import/Export', 'quizpress' ),
							icon: (
								<Span
									className="quizpress-icon quizpress-icon--file-import has-quizpress-muted-bg"
									_before={ { fontSize: '22px' } }
								/>
							),
							onClick: () => {
								setOpenImportModal( true );
							},
						},
						{
							type: 'button',
							label: __(
								'Import Existing Question',
								'quizpress'
							),
							icon: (
								<span className="quizpress-icon quizpress-icon--import"></span>
							),
							onClick: () => {
								setIsQuestionImportModalOpen( true );
							},
						},
					] }
				/>
			</Flex>
		</Flex>
	);
};

export default QuestionsHeader;
