import React, { useState } from 'react';
import { Service } from '../Utils/HTTP'
import { Box, Paper, Divider, Typography, Button } from '@mui/material'

import toast, { Toaster } from 'react-hot-toast';
import { useParams } from 'react-router-dom'
import { Cleaver } from './Pruebas/Cleaver';
import { Header } from '../Components/Test/Cleaver/Header';
import { useSelector, useDispatch } from 'react-redux';
import { setRole } from '../Slices/userSlice'

export function Prueba() {

  let { id } = useParams();
  // let token = useMemo(() => auth.getToken(), [auth])
  let auth = useSelector((state) => state.token.token)
  let profile = useSelector((state) => state.user)
  let dispatch = useDispatch();
  let [data, setData] = useState({});

  console.log("PROFILE: ", profile)

  useState(() => {
    let rest = new Service(`/prueba/findid/${id}`)
    rest.get(auth.token)
      .then(resp => { 
          setData(resp.data)
        })
      .catch(_e => setData({}))
  }, [id])

  const CreateAssign = () => {

    let now = new Date().toISOString();
    let body = {
      "id": -1,
      "fechaasignacio": now,
      "fechafinexamen": now,
      "estado": "1",
      "score": "0",
      "mensaje": "0",
      "mensaje2": "0",
      //candidatoinpwd -> idSuperContraseña -> viene al hacer login
      "idcontrasenia": profile.role.passid, // ya no se va enviar
      "nombre": "assing CLEVAERR"
      //cattest_id // catalogo de examenes -> viene del api del catalogo del admin
    }

    let rest = new Service("/prueba/asignacion");
    rest.postQuery(body, auth.token)
      .then(({ data: resp }) => {
        let { id: assingid } = resp
        toast.success("Asignación creada: ", assingid)
        dispatch(setRole({ assingid }))
      })
      .catch(() => {
        toast.error("Error al crear la asignación")
      })
  }

  if(profile.role.assingid){
    return <Cleaver />
  }

  return (
    <div  className="content-section">
      <div className="main">
        <Box >
          <Paper>
            <Header/>
          </Paper>
          <Paper className="prueba_body" elevation={1}>
            <h1>{data?.nombre}</h1>
            <Divider />
            <Typography style={{ marginTop: 15, textAlign: 'center' }}>{data?.decription}</Typography>
            <Divider style={{ marginTop: 15 }} />
            <Button  variant="contained" onClick={CreateAssign}>Inicar Prueba</Button>
          </Paper>
        </Box>
        <Toaster
          position="top-left"
          reverseOrder={false}
        />
      </div>
    </div>
  );
}
