import React from 'react'
import { Service } from '../../Utils/HTTP'
import { Question } from '../../Components/Test/Cleaver/Question.jsx'
import { Box,Button } from '@mui/material'
import { useSelector } from 'react-redux';
import { useParams } from 'react-router-dom'
import toast, { Toaster } from 'react-hot-toast';

export function Cleaver() {

  let { id } = useParams();
  const auth = useSelector((state) => state.token.token);
  const cleaver = useSelector((state) => state.cleaver);

  const [totalRespondidas, setRespondidas] = React.useState([]);
  const [totalPreguntas, setPreguntas] = React.useState([]);
  const [current, setCurrent] = React.useState(0);
  const [progress, setProgress] = React.useState(0);

  const BadQuestion = () => toast.error("Escoge una respuesta en cada columna") 
  //toast("Escoge una respuesta en cada columna",{ icon : '⚠️' });
  const CalculateProgress = () => {
    let total_preguntas = totalPreguntas.length + totalRespondidas.length
    let x = totalRespondidas.length *100 / (total_preguntas)
    setProgress(x.toFixed(2))
  }

  React.useEffect(() => {
    let rest = new Service(`/prueba/findid/${id}`)
    rest.get(auth.token)
      .then(({ data }) => {
        console.log(data.questions)
        setPreguntas(data.questions)
        setRespondidas(data.questions.slice(0,1))
        setCurrent(0)
      }).catch(console.log)
  }, [id,auth]);

  const handleAddQuestion = () => {
    let currentAnswer  = totalRespondidas[totalRespondidas.length - 1];
    let current_resp = cleaver.responses[currentAnswer.id];

    if(!current_resp){
      return BadQuestion();
    }
    if(parseInt( current_resp.A ) ===0 || parseInt( current_resp.B ) === 0){
      return BadQuestion();
    }
    const nextHiddenItem = totalPreguntas.filter(({id}) => id !== currentAnswer.id );
    if (nextHiddenItem) {
      setPreguntas(nextHiddenItem);
      setCurrent(current+1);
      let temp = nextHiddenItem.shift()
      setRespondidas([...totalRespondidas,temp]);
    }
    CalculateProgress()
  };

  const handleRemoveQuestion = () => {
    let ultimaRespondida = totalRespondidas[totalRespondidas.length - 1];
    setPreguntas([ultimaRespondida,...totalPreguntas]);
    let current_without_last = totalRespondidas.filter(({id}) => id !== ultimaRespondida.id);
    setRespondidas([...current_without_last]);
    setCurrent(current - 1 )
    CalculateProgress()
  }

  return (
    <div  className="content-section question">
      <Box className="question_body">
        {totalRespondidas.map((item,i) => (
          <Question 
            key={item.id} 
            id={item.id} 
            quiz={item} 
            index={i} 
            current={current} 
            progress={progress} 
            />)
        )}
      </Box>

      <div className="question_btn">
        <Button
          className="nextquestion_btn"
          sx={{ backgroundColor: 'var(--main)' }}
          variant="contained"
          disabled={totalRespondidas.length <= 1}
          onClick={handleRemoveQuestion}
        >
          Anterior
        </Button>
        <Button
          className="nextquestion_btn"
          sx={{ backgroundColor: 'var(--main)' }}
          variant="contained"
          disabled={totalPreguntas.length <= 0}
          onClick={handleAddQuestion}
        >
          Siguiente
        </Button>
      </div>
      <Toaster
        position="bottom-right"
        />
    </div>
  )

}


