import * as React from 'react';

import { Table } from 'react-bootstrap';
import {
    Box, Button, LinearProgress,
    Backdrop, CircularProgress
} from '@mui/material';

import toast, { Toaster } from 'react-hot-toast';

import { useMutation } from 'react-query';
import { Service } from '../../../Utils/HTTP.js'
import useAuth from '../../../Auth/useAuth.js'

import { createTheme, ThemeProvider } from '@mui/material/styles';

let theme = createTheme({
    status: {
        success: '#fd4b4b'
    },
    palette: {
        primary: {
            main: '#fd4b4b',
        },
        secondary: {
            main: '#fd4b4b',
        },
    },
});

export function Resume(props) {

    let { handleBack, password: key } = props
    const fmt = React.useRef({ weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' })
    const [pwdID, setPwdID] = React.useState(null);
    const [loading, setLoading] = React.useState(false);
    const auth = useAuth();
    const token = auth.getToken();

    const savePassword = async (body) => {
        let rest = new Service('/contrasenia/create')
        return await rest.postQuery(body, token)
    }

    const saveCandidato = async (body) => {
        let rest = new Service('/passwordcandidato/candidato')
        return await rest.postQuery(body, token)
    }

    const pwdMutation = useMutation('password', savePassword);
    const candiMutation = useMutation('candidato', saveCandidato);

    const saveStepper = () => {

        setLoading(true);

        let {
            deadpwd, dateToActived, puesto, pwd,
            nombres, apellidos, sendmail, nombrepuesto, nombreEmpresa
        } = key;
        console.log("KEY: ", key)

        let pwdBody = {
            id: -1,
            pwd,
            link: "www.psicoadmin.com",
            deadpwd: new Date(deadpwd).toISOString(),
            state: 1,
            dateToActived: new Date(dateToActived).toISOString(),
            plaza_id: puesto[0].id
        }

        pwdMutation.mutate(pwdBody, {
            onSuccess: (data) => {

                let { id: password_id } = data.data;
                setPwdID(password_id);

                let candidatoBody = {
                    id: -1,
                    nombres,
                    apellidos,
                    sendmail: sendmail ? 1 : 0,
                    idContrasenia: password_id,
                    nombrepuesto,
                    nombreEmpresa
                }

                candiMutation.mutate(candidatoBody, {
                    onSuccess: (data) => {
                        console.log("OK LETS GO >> ", data)
                        toast.success("Contraseña agregada exitosamente!!")
                        setLoading(false);
                    },
                    onError: () => {
                        toast.error("Ups!! error al crear el candidato")
                        setLoading(false);
                    }
                })


            },
            onError: () => {
                console.log("No se pudo guardar pwd")
                setLoading(false);
                toast.error("Ups!! Ocurrio un error, inténtalo más tarde")
            }
        })
    }

    return (
        <React.Fragment>
            <ThemeProvider theme={theme}>
                {loading ? (
                    <Box sx={{ paddingBottom: 3 }}>
                        <LinearProgress color="inherit" />
                    </Box>
                ) : null}
                <Table>
                    <thead>
                        <tr>
                            <th>{key.pwd} ✅</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td className="title_td">{"Candidato"}</td>
                            <td colSpan={2}>{key.nombres + " " + key.apellidos} - {key.mail}</td>
                        </tr>
                        <tr>
                            <td className="title_td">{"Puesto"}</td>
                            <td colSpan={2}>{key.puesto[0].nombrepuesto}</td>
                        </tr>
                        <tr>
                            <td className="title_td">{"Empresa"}</td>
                            <td colSpan={2}>{key.nombreEmpresa}</td>
                        </tr>
                        <tr>
                            <td className="title_td">{"Fecha Activación"}</td>
                            <td colSpan={2}>{new Date(key.dateToActived).toLocaleDateString('es-GT', fmt.current)}</td>
                        </tr>
                        <tr>
                            <td className="title_td">{"Fecha de Vencimiento"}</td>
                            <td colSpan={2}>{new Date(key.deadpwd).toLocaleDateString('es-GT', fmt.current)}</td>
                        </tr>
                    </tbody>
                </Table>


                <Box sx={{ mb: 2 }}>
                    <div style={{ paddingTop: 15 }}>
                        <Button
                            disabled={loading}
                            style={{
                                color: loading ? 'white' : ''
                            }}
                            onClick={saveStepper}
                            className="registerBtn"
                            variant="contained"
                            sx={{ mt: 1, mr: 1 }}
                        >
                            {'Guardar'}
                        </Button>
                        <Button
                            disabled={loading}
                            onClick={handleBack}
                            sx={{ mt: 1, mr: 1 }}
                        >
                            Regresar
                        </Button>
                    </div>
                </Box>
            </ThemeProvider>
            <Backdrop
                sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
                open={loading}
                onClick={() => console.log("close fetching")} >
                <CircularProgress color="inherit" />
            </Backdrop>
            <Toaster position="bottom-right" />
        </React.Fragment>
    )
}
