import { Box, Button, Container, Typography } from '@mui/material';
import { quiz } from "../quizData";
import { useSelector } from 'react-redux';
import { useState } from 'react';
import Matching from './Matching';
import Sorting from './Sorting';
import Choosing from './Choosing';
import type { RootState } from '../../store';
import store from '../../store';
import { useDispatch } from 'react-redux';
import { mixUp, startTesting, stopTesting } from './quizSlice';

function QuizStats() {
  let correctAnswers = useSelector((state: RootState) => state.quiz.correctAnswers);
  const userAnswers = useSelector((state: RootState) => state.quiz.userAnswers);

  const correctCount = (index: number): number => {
    let state = store.getState();
    if (state.quiz.correctAnswers.length <= index) {
      return 0;
    }
    return userAnswers[index].reduce((prev, answ, i) => prev + Number(correctAnswers[index][i] === answ), 0);
  }

  const counts = userAnswers.map((_,index)=>correctCount(index));
  const questionCounts = userAnswers.map((answers)=>answers.length);

  const total= counts.reduce((x,c)=>c+x,0);
  const totalQuestionCount= questionCounts.reduce((x,c)=>c+x,0);

  const donePercentage = Math.round(total/totalQuestionCount*100*100)/100;

  const quizPartText = (counter: number, len: number, taskIndex:number) => {
    if (counter == len) {
      return <Typography key={taskIndex}>Задание {taskIndex+1}: все ответы верные</Typography>
    }
    return  <Typography key={taskIndex}>Задание {taskIndex+1}: верно {counter}/{len}</Typography>
  }


  return (
    <Container sx={{ margin: "auto", d:"flex",flexDirection:"column" }}>
      <h2>Результаты теста</h2>
      {
        counts.map((count,idx)=>quizPartText(count,questionCounts[idx],idx))
      }
      <h3>Итого {donePercentage}% Верно</h3>
    </Container>
  )
}


function Quiz() {
  const dispatch = useDispatch();
  const [displayingResults, setDisplayingResults] = useState(false);
  const resetQuiz = () => {
    setDisplayingResults(false);
    dispatch(mixUp());
    dispatch(startTesting());
  }

  const checkQuiz = () => {
    setDisplayingResults(true);
    dispatch(stopTesting());
  }


  return (
    <Container maxWidth="md">
      {quiz.map((item, index) => (
        <Box key={item.id} component="section" sx={{ m: 2, p: 2}}>
          <Typography variant="h5" gutterBottom>
            {index + 1}. {item.title}
          </Typography>
          {[

            <Matching index={index} tasks={item.tasks} key={index}/>, 
            
            <Sorting index={index} tasks={item.tasks} key={index}/>,
            
            <Choosing index={index} tasks={item.tasks} key={index}/>
             
             ][(["M", "S", "C"].indexOf(item.type))]}
        </Box>
        
      ))}
        <Box sx={{ display: 'flex', justifyContent: 'space-around' }}>
                <Button onClick={checkQuiz} variant="contained">Check</Button>
                <Button onClick={resetQuiz} variant="contained">Reset</Button>
              </Box>

      {displayingResults && <QuizStats />}

    </Container>
  );
}

export default Quiz