import React, { useMemo, 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 useAuth from '../Auth/useAuth.js';
import { Cleaver } from './Pruebas/Cleaver';
import { Header } from '../Components/Test/Cleaver/Header';

export function Prueba() {

  let { id } = useParams();
  let auth = useAuth();
  let token = useMemo(() => auth.getToken(), [auth])
  let [data, setData] = useState({});
  // let profile = auth.getProfile();
  let [profile, setProfile] = useState(auth.getProfile)

  useState(() => {
    let rest = new Service(`/prueba/findid/${id}`)
    rest.get(token.toString())
      .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",
      "idcontrasenia": profile.passid,
      "nombre": "assing CLEVAERR"

    }

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

  if(profile.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>
  );
}
