import * as React from 'react';

import { Edit as EditIcon, Send as SendIcon } from '@mui/icons-material'
import {
    Button, Dialog, DialogActions, DialogContent, //DialogTitle,
    FormControlLabel, Checkbox,
    TextField, Stack,
    // Autocomplete
} from '@mui/material'

import toast, { Toaster } from 'react-hot-toast';
import * as Yup from 'yup';

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

import { useFormik, Form, FormikProvider } from 'formik';

import DateFnsUtils from '@date-io/date-fns';
import { DesktopDatePicker, LocalizationProvider } from '@mui/lab';

export function Operation(props) {

    let [open, setOpen] = React.useState(false);
    const handleOpen = (status) => setOpen(status);

    return (
        <div>
            <div className="operation_buttons">
                <EditIcon onClick={() => setOpen(true)} className="icon_op" />
                <SendIcon className="icon_op" />
            </div>
            {
                open ?
                    <ModalEdit
                        password={props}
                        open={open}
                        handleOpen={handleOpen}
                    />
                    : null
            }
        </div>
    )
}

function ModalEdit(props) {

    let { password, open, handleOpen } = props
    const now = React.useRef(new Date());
    let { pwd, plz } = password
    const auth = useAuth();
    const token = React.useRef(auth.getToken());
    const getPassword = async () => {
        let rest = new Service(`/contrasenia/${pwd}/${plz}`)
        return await rest.getQuery(token.current)
    }

    let { data: result } = useQuery('contra', getPassword);
    console.log('PWD INFO ',result)
    //
    // const getPuestos = async () => {
    //     let rest = new Service('/plaza/getall')
    //     return rest.getQuery(token.current);
    // }
    //
    // let { data } = useQuery('puestos', getPuestos)
    // let puestos = data ? data.data.map(({ nombrepuesto, id }) => ({ nombrepuesto, id })) : []

    let initialValues = {
        id: result?.data?.id,
        pwd: result?.data?.pwd,
        deadpwd: result?.data?.deadpwd ? new Date(result?.data?.deadpwd) : now.current,
        state: result?.data?.state,
        dateToActived: result?.data.dateToActived ? new Date(result?.data?.dateToActived) : now.current,
        plaza_id: result?.data?.plaza_id,
        candidato_id : result?.data?.candidato_id
    }

    return (
        <Dialog
            open={open}
            onClose={() => handleOpen(false)}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
        >
            <DialogContent>
                <ModalForm
                    //puestos={puestos}
                    initialValues={initialValues}
                    handleOpen={handleOpen}
                    token={token.current}
                />
            </DialogContent>
        </Dialog>
    )
}

function ModalForm(props) {

    const pwdSchema = Yup.object().shape({
        id: Yup.number(),
        pwd: Yup.string().required("Escoge un nombre valido"),
        deadpwd: Yup.date().required("Escoge una fecha valida"),
        state: Yup.number(),
        dateToActived: Yup.date('Escoge una fecha valida').required("Escoge una fecha valida"),
        //plaza_id: Yup.array().required("Escoge una plaza valida")
        //plaza_id: Yup.array().required("Escoge una plaza valida")
    })

    const queryClient = useQueryClient();

    const formik = useFormik({
        initialValues: {
            state: 1,
            pwd:"",
            deadpwd:"",
            dateToActived:"",
            // plaza_id:[],
        },
        onSubmit: (fields) => {

            let rest = new Service('/contrasenia/create');
            let { deadpwd,dateToActived,pwd } = fields
            
            fields['pwd'] = btoa(pwd);
            fields['deadpwd'] = new Date(deadpwd).toISOString();
            fields['dateToActived'] = new Date(dateToActived).toISOString();
            fields['candidato_id'] = props.initialValues.candidato_id
            fields['plaza_id'] = props.initialValues.plaza_id

            rest.put(fields, props.token)
                .then(result => {
                    queryClient.invalidateQueries('passwords')
                    console.log(result)
                    setTimeout(()=>{
                        props.handleOpen(false)
                    },1000)
                    toast.success("Contraseña Actualizada")
                })
                .catch(bad => {
                    console.log('ERROR',bad)
                    toast.error("Ocurrio un error")
                })
        },
        validationSchema: pwdSchema,
    })

    const { errors, touched, handleSubmit, getFieldProps, values, setValues } = formik;

    React.useEffect(() => {
        setValues({ 
            ...props.initialValues,
            pwd : props.initialValues.pwd ? atob( props.initialValues.pwd ) : 'loading'
        })
    }, [props, setValues])

    return (
        <FormikProvider value={formik}>
            <Form style={{ padding: 20, maxWidth: 950 }} autoComplete="off" noValidate onSubmit={handleSubmit}>
                <Stack spacing={4}>
                    <TextField
                        value={btoa( values.pwd )}
                        variant="filled"
                        disabled
                        fullWidth
                        type="text"
                        label="Contraseña Cifrada"
                        />

                    <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>

                        <TextField
                            type="text"
                            label="Contraseña"
                            {...getFieldProps('pwd')}
                            error={Boolean(touched.pwd && errors.pwd)}
                            helperText={touched.pwd && errors.pwd}
                        />

                        <FormControlLabel
                            control={
                                <Checkbox
                                    checked={values.state === 1}
                                    onChange={(event) => {
                                        let check = event.target.checked;
                                        setValues({
                                            ...values,
                                            state: check ? 1 : 0
                                        })
                                    }}
                                />
                            }
                            label="Activa"
                        />

                    </Stack>
                        

                    <LocalizationProvider
                        dateAdapter={DateFnsUtils}>
                        <DesktopDatePicker
                            label="Fecha de Activación"
                            fullWidth
                            inputFormat="dd/MM/yyyy"
                            value={values.dateToActived}
                            onChange={(val) => setValues({ ...values, dateToActived: val }) }
                            renderInput={(params) =>
                                <TextField
                                    {...getFieldProps('dateToActived')}
                                    error={Boolean(touched.dateToActived && errors.dateToActived)}
                                    helperText={touched.dateToActived && errors.dateToActived}
                                    disabled={true}
                                    label="Fecha de Activación"
                                    fullWidth
                                    {...params}
                                />}
                        />
                    </LocalizationProvider>

                    <LocalizationProvider
                        dateAdapter={DateFnsUtils}>
                        <DesktopDatePicker
                            label="Fecha de Vencimiento"
                            fullWidth
                            inputFormat="dd/MM/yyyy"
                            {...getFieldProps('deadpwd')}
                            value={values.deadpwd}
                            onChange={(val) => setValues({ ...values, deadpwd: new Date(val) })
                            }
                            renderInput={(params) =>
                                <TextField
                                    error={Boolean(touched.deadpwd && errors.deadpwd)}
                                    helperText={touched.deadpwd && errors.deadpwd}
                                    disabled={true}
                                    label="Fecha de Vencimiento"
                                    fullWidth
                                    {...params}
                                />}
                        />
                    </LocalizationProvider>


                    {/*
                    <Autocomplete
                        {...getFieldProps('plaza_id')}
                        onChange={(_a,current_list,_c,_individual,_f) => {
                            console.log("CURRENT LIST : ",current_list)
                            setValues({
                                ...values,
                                plaza_id:current_list
                            })
                        }}
                        value={props.puestos.filter(p=> p.id=== values.plaza_id ).shift()}
                        id="combo-box-demo"
                        options={props.puestos}
                        isOptionEqualToValue={
                            (option, value) => option.nombrepuesto === value.nombrepuesto
                        }
                        getOptionLabel={(option) => {
                            return option.nombrepuesto
                        }}
                        renderInput={(params) =>
                            <TextField
                                {...params}
                                label="Puesto"
                            />
                        }
                    />
*/}

                    <DialogActions>
                        <Button onClick={() => props.handleOpen(false)}>
                            Cerrar
                        </Button>
                        <Button
                            type="submit"
                            className="registerBtn"
                            style={{ color: 'white' }}
                            >
                            Guardar
                        </Button>
                    </DialogActions>

                </Stack>
            </Form>
            <Toaster position="bottom-right" />
        </FormikProvider >
    )

}

