import React from 'react';
import { __ } from '@wordpress/i18n';
import { Button, Flex, Menu, Portal, Span, Text } from '@chakra-ui/react';
import { getInitialQuestionValue, makeQstMeta } from '../../helper';
import { useFormikContext } from 'formik';
import { makeRequest, quizpress_nonce } from '@QPUtils/helper';
import { showNotification } from '@QPRedux/Slices/notificationSlice/notificationSlice';
import { useDispatch, useSelector } from 'react-redux';
import Pagination from '@QPComponents/Pagination';
import QuestionImportExport from './QuestionImportExport';
import { updateQuiz } from '@QPRedux/Slices/quizSlice/quizSlice';

const QuestionsFooter = ( {
	originalQsts,
	setFilteredQsts,
	setCurrentIndex,
	toggleOpen,
	openImportModal,
	setOpenImportModal,
	setCurrentPageNumber,
	currentPageNumber,
	rowsPerPage,
	setIsQuestionImportModalOpen,
} ) => {
	const settings = useSelector( ( state ) => state.settings );
	const { setFieldValue, values: quizValues } = useFormikContext();

	const dispatch = useDispatch();

	const getQstByPageChange = ( newPage, rowsPerPage ) => {
		setCurrentPageNumber( newPage );
	};

	const updatePaginationIfNeeded = ( length ) => {
		if ( length > 10 ) {
			setCurrentPageNumber( Math.ceil( length / rowsPerPage ) );
		}
	};

	const handleImportExportCsv = ( values, actions ) => {
		if ( values.type === 'export' ) {
			window.location.href = `admin.php?page=quizpress-question&exportType=questions&security=${ quizpress_nonce }`;
			actions.setSubmitting( false );
			setOpenImportModal( false );
			return;
		}

		if ( values.type === 'import' && ! values?.upload_file ) {
			dispatch(
				showNotification( {
					message: __( 'Please select a file.', 'quizpress' ),
					isShow: true,
					type: 'error',
				} )
			);
			actions.setSubmitting( false );
			return;
		}

		makeRequest( 'import_quiz', { upload_file: values.upload_file }, true )
			.then( ( res ) => {
				if ( ! res?.length ) {
					dispatch(
						showNotification( {
							message: __(
								'Unable to import questions. Something went wrong.',
								'quizpress'
							),
							isShow: true,
							type: 'error',
						} )
					);
					actions.setSubmitting( false );
					return;
				}

				const updated = [ ...originalQsts, ...res ];
				setFieldValue( 'questions', updated );
				setFilteredQsts( null );
				setCurrentIndex( 0 );
				toggleOpen( `qst-${ updated.length - 1 }` );
				updatePaginationIfNeeded( updated.length );
				setTimeout( () => {
					dispatch(
						updateQuiz( {
							params: {
								...quizValues,
								meta: {
									...quizValues.meta,
									quizpress_quiz_questions:
										makeQstMeta( updated ),
								},
							},
							questions: updated,
						} )
					);
				}, 500 );
			} )
			.finally( () => {
				setOpenImportModal( false );
				actions.setSubmitting( false );
			} );
	};

	const handleAddQst = () => {
		const updated = [
			...originalQsts,
			getInitialQuestionValue( settings, originalQsts.length + 1 ),
		];
		setFieldValue( 'questions', updated );
		setFilteredQsts( null );
		setCurrentIndex( updated.length - 1 );
		toggleOpen( `qst-${ updated.length - 1 }` );
		updatePaginationIfNeeded( updated.length );
	};

	return (
		<React.Fragment>
			<Flex
				alignSelf="center"
				gap={ 4 }
				width="fit-content"
				padding="36px 144px"
				borderRadius="4px"
				border="1px dashed var(--quizpress-primary)"
				alignItems="center"
				justifyContent="center"
			>
				<Flex direction="column" gap={ 2 } alignItems="center">
					<Button
						p={ 3 }
						bg="#E3E7FF"
						borderRadius="full"
						onClick={ handleAddQst }
					>
						<Span className="quizpress-icon quizpress-icon--plus quizpress-primary" />
					</Button>
					<Text m={ 0 } color="var(--quizpress-primary)">
						{ __( 'Add Question', 'quizpress' ) }
					</Text>
				</Flex>

				<Menu.Root>
					<Menu.Trigger asChild>
						<Flex direction="column" gap={ 2 } alignItems="center">
							<Button p={ 3 } bg="#E3E7FF" borderRadius="full">
								<Span className="quizpress-icon quizpress-icon--file-export" />
							</Button>
							<Text m={ 0 } color="var(--quizpress-primary)">
								{ __( 'Import/Export', 'quizpress' ) }
							</Text>
						</Flex>
					</Menu.Trigger>
					<Portal>
						<Menu.Positioner>
							<Menu.Content>
								<Menu.Item
									value="new-csv"
									display="flex"
									gap="12px"
									alignItems="center"
									onClick={ () => {
										setOpenImportModal( true );
									} }
								>
									<Span
										className="quizpress-icon quizpress-icon--file-import has-quizpress-muted-bg"
										_before={ { fontSize: '18px' } }
									/>
									<Text m={ 0 }>
										{ __(
											'CSV Import/Export',
											'quizpress'
										) }
									</Text>
								</Menu.Item>
								<Menu.Item
									value="existing-question"
									display="flex"
									gap="12px"
									alignItems="center"
									onClick={ () =>
										setIsQuestionImportModalOpen( true )
									}
								>
									<Span className="quizpress-icon quizpress-icon--import" />
									<Text m={ 0 }>
										{ __(
											'Import Existing Questions',
											'quizpress'
										) }
									</Text>
								</Menu.Item>
							</Menu.Content>
						</Menu.Positioner>
					</Portal>
				</Menu.Root>
			</Flex>

			<Pagination
				currentPageNumber={ currentPageNumber }
				fetchHandler={ getQstByPageChange }
				rowsPerPage={ rowsPerPage }
				totalItems={ originalQsts?.length }
			/>

			{ openImportModal && (
				<QuestionImportExport
					isOpen={ openImportModal }
					onClose={ () => setOpenImportModal( false ) }
					handleSubmit={ handleImportExportCsv }
				/>
			) }
		</React.Fragment>
	);
};

export default QuestionsFooter;
