import { useQuery } from '@QPUtils/helper';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Dashboard from './pages/Dashboard';
import Quizzes from './pages/Quizzes';
import Question from './pages/Question';
import QuizInsights from './pages/QuizInsights';
import Settings from './pages/Settings';
import Notification from '@QPComponents/Notification';
import Category from './pages/Category';
import CreateQuiz from './pages/Quizzes/newQuiz';
import QuestionOperation from './pages/Question/QuestionOperation';
import { fetchSettings } from '@QPRedux/Slices/settingsSlice/settingsSlice';
import AttemptDetails from './pages/QuizInsights/AttemptDetails';
import QuizLeaderboard from './pages/Quizzes/QuizLeaderboard';
import Addons from './pages/Addon';
import Certificate from './pages/Certificate';
import Tools from './pages/Tools';
import { fetchAddons } from '@QPRedux/Slices/addonSlice/addonSlice';

const renderSwitch = ( page, id, action, path ) => {
	switch ( page ) {
		case 'quizpress':
			return <Dashboard />;

		case 'quizpress-quizzes':
			if ( action === 'leaderboard' ) {
				return <QuizLeaderboard id={ id } />;
			}

			if ( action || id ) {
				return <CreateQuiz action={ action } id={ id } />;
			}
			return <Quizzes />;

		case 'quizpress-question':
			if ( path === 'category' ) {
				return <Category />;
			}
			if ( action || id ) {
				return <QuestionOperation id={ id } />;
			}
			return <Question />;

		case 'quizpress-quiz-insights':
			if ( id ) {
				return <AttemptDetails />;
			}
			return <QuizInsights />;
		case 'quizpress-certificates':
			return <Certificate />;

		case 'quizpress-settings':
			return <Settings />;
		case 'quizpress-tools':
			return <Tools />;

		case 'quizpress-addons':
			return <Addons />;

		default:
			return <>No route Found</>;
	}
};

export default function BackendDashboard() {
	const query = useQuery();
	const dispatch = useDispatch();
	const settings = useSelector( ( state ) => state.settings );
	useEffect( () => {
		if ( ! settings?.data?.length ) {
			dispatch( fetchSettings() );
			dispatch( fetchAddons() );
		}
	}, [] );

	return (
		<>
			<Notification />
			{ renderSwitch(
				query.get( 'page' ),
				Number( query.get( 'id' ) ),
				query.get( 'action' ),
				query.get( 'path' )
			) }
		</>
	);
}
