import React, { useMemo } from 'react'
import { Service } from '../../Utils/HTTP'
import useAuth from '../../Auth/useAuth.js';
import { Question } from '../../Components/Test/Cleaver/Question.jsx'
import { Box,Button } from '@mui/material'

export function Cleaver() {

  let auth = useAuth();
  let token = useMemo(() => auth.getToken(), [auth])

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


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

  const handleAddQuestion = () => {
    let currentAnswer  = totalRespondidas[totalRespondidas.length - 1];
    const nextHiddenItem = totalPreguntas.filter(({id}) => id !== currentAnswer.id );
    if (nextHiddenItem) {
      setPreguntas(nextHiddenItem);
      setCurrent(current+1);
      let temp = nextHiddenItem.shift()
      setRespondidas([...totalRespondidas,temp]);
    }
  };

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

  console.log('total respondidas: ', totalRespondidas)
  console.log('total respondidas total: ', totalRespondidas.length)

  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} /> )
        )}
      </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>
    </div>
  )

}


