import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Button, Flex, Span, Box } from '@chakra-ui/react';
import Select from 'react-select';
import { useFormikContext } from 'formik';
import { outlineBtn } from '../../../../../../../../assets/scss/chakra/recipe';
import QuizPressCheckbox from '@QPComponents/QuizPressCheckbox';
import {
	API,
	makeRequest,
	namespace,
	questionTypeOptions,
	reactDebounce,
} from '@QPUtils/helper';
import Search from '@QPComponents/Search';
import Preloader from '@QPComponents/Loader/Preloader';
import Pagination from '@QPComponents/Pagination';

const FormInner = ( {
	quizValues,
	handleDefaultChange,
	setFilterData,
	filterData,
	questions,
	setQuestions,
	fetchQuestions,
	loading,
	setLoading,
	rowsPerPage,
} ) => {
	const { handleSubmit } = useFormikContext();

	const [ quizOptions, setQuizOptions ] = useState( [] );
	const [ filters, setFilters ] = useState( {
		search: '',
		quizId: null,
		type: null,
	} );

	useEffect( () => {
		makeRequest( 'admin/get_quiz_options' ).then( ( res ) => {
			const newQuizzes = res.filter(
				( q ) => Number( q.id ) !== Number( quizValues.id )
			);
			setQuizOptions(
				newQuizzes.map( ( q ) => ( {
					value: q.id,
					label: q.post_title,
				} ) )
			);
		} );
	}, [ quizValues.id ] );

	const handleSearch = reactDebounce( ( value ) => {
		setFilters( ( prev ) => ( { ...prev, search: value } ) );
		setQuestions( ( prev ) => ( { ...prev, currentPage: 1 } ) );
	}, 500 );

	const handleQuizFilter = async ( option ) => {
		setLoading( true );
		try {
			if ( option?.value ) {
				const res = await API.get(
					`${ namespace }quizpress_quiz/${ option.value }`
				);
				const quizQuestions = res?.data?.questions || [];

				setQuestions( {
					data: quizQuestions,
					totalItems: quizQuestions.length,
					currentPage: 1,
				} );

				setFilters( ( prev ) => ( { ...prev, quizId: option.value } ) );
			} else {
				setFilters( ( prev ) => ( { ...prev, quizId: null } ) );
				fetchQuestions( 1 );
			}
		} catch ( err ) {
			console.error( 'Error filtering quiz:', err );
		} finally {
			setLoading( false );
		}
	};

	const handleQuestionTypeFilter = ( option ) => {
		setFilters( ( prev ) => ( { ...prev, type: option?.value || null } ) );
		setQuestions( ( prev ) => ( { ...prev, currentPage: 1 } ) );
	};

	// Compute filtered questions dynamically
	let filteredQuestions = [ ...questions.data ];

	if ( filters.search ) {
		const term = filters.search.toLowerCase();
		filteredQuestions = filteredQuestions.filter( ( q ) =>
			q.question_title.toLowerCase().includes( term )
		);
	}

	if ( filters.type ) {
		filteredQuestions = filteredQuestions.filter(
			( q ) => q.question_type === filters.type
		);
	}

	// Determine total items
	const totalItems =
		filters.quizId || filters.search || filters.type
			? filteredQuestions.length
			: questions.totalItems;

	// Pagination
	const totalPages = Math.ceil( totalItems / rowsPerPage );
	const startIndex = ( questions.currentPage - 1 ) * rowsPerPage;
	const endIndex = startIndex + rowsPerPage;
	const paginatedQuestions = filteredQuestions.slice( startIndex, endIndex );

	const handlePageChange = ( page ) => {
		setQuestions( ( prev ) => ( { ...prev, currentPage: page } ) );
		fetchQuestions( page );
	};

	const handleSelectAll = ( e ) => {
		const allIds = paginatedQuestions.map( ( q ) =>
			Number( q.question_id )
		);
		setFilterData( e.checked ? allIds : [] );
	};

	const QuestionCard = ( { id, title } ) => (
		<Flex
			key={ id }
			padding="16px 24px"
			border="1px solid var(--quizpress-border-color)"
			borderRadius="4px"
			justifyContent="space-between"
			alignItems="center"
		>
			<QuizPressCheckbox
				title={ title }
				fontSize="1rem"
				fontWeight="600"
				rootStyles={ { alignItems: 'center' } }
				onChange={ ( e ) => handleDefaultChange( id, e ) }
				checked={ filterData.includes( Number( id ) ) }
			/>
			<Button
				{ ...outlineBtn }
				size="xs"
				onClick={ () => {
					handleDefaultChange( id, { checked: true } );
					handleSubmit();
				} }
			>
				<Span className="quizpress-icon quizpress-icon--plus" />
				{ __( 'Add', 'quizpress' ) }
			</Button>
		</Flex>
	);

	return (
		<Flex direction="column" gap={ 4 } width="100%">
			{ /* Filter Row */ }
			<Flex gap={ 3 } alignItems="center" flexWrap="wrap">
				<Box
					p={ 3 }
					border="1px solid var(--quizpress-border-color)"
					borderRadius="4px"
				>
					<QuizPressCheckbox
						title={ __( 'Select All' ) }
						fontSize="0.875rem"
						fontWeight="500"
						rootStyles={ { alignItems: 'center' } }
						onChange={ handleSelectAll }
					/>
				</Box>

				<Search
					onSearchHandler={ handleSearch }
					placeholder={ __( 'Search Question', 'quizpress' ) }
				/>

				<Select
					name="quiz_filter"
					placeholder={ __( 'Select Quiz', 'quizpress' ) }
					className="quizpress-select"
					classNamePrefix="quizpress-select"
					isClearable
					isSearchable
					options={ quizOptions }
					value={
						quizOptions.find(
							( opt ) => opt.value === filters.quizId
						) || null
					}
					onChange={ handleQuizFilter }
				/>

				<Select
					name="question_type_filter"
					placeholder={ __( 'Select Question Type', 'quizpress' ) }
					className="quizpress-select"
					classNamePrefix="quizpress-select"
					isClearable
					isSearchable
					options={ questionTypeOptions.flatMap(
						( g ) => g.options
					) }
					value={
						questionTypeOptions
							.flatMap( ( g ) => g.options )
							.find( ( opt ) => opt.value === filters.type ) ||
						null
					}
					onChange={ handleQuestionTypeFilter }
				/>
			</Flex>

			{ /* Question List */ }
			{ loading ? (
				<Preloader />
			) : (
				paginatedQuestions.map( ( q ) => (
					<QuestionCard
						key={ q.question_id }
						id={ q.question_id }
						title={ q.question_title }
					/>
				) )
			) }

			{ /* Pagination – Always visible if data > 10 */ }
			{ totalItems > rowsPerPage && (
				<Pagination
					currentPageNumber={ questions.currentPage }
					fetchHandler={ handlePageChange }
					rowsPerPage={ rowsPerPage }
					totalItems={ totalItems }
					totalPages={ totalPages }
				/>
			) }
		</Flex>
	);
};

export default FormInner;
