import * as React from 'react';

import { Edit as EditIcon, Send as SendIcon } from '@mui/icons-material'
import {
    Button, Dialog, DialogActions, DialogContent,
    DialogContentText, DialogTitle
} from '@mui/material'

import * as Yup from 'yup';

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

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

import { Stack, TextField } from '@mui/material';

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
    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);

    let initialValues = {
        id: result?.data?.id,
        pwd: result?.data?.pwd,
        deadpwd: result?.data?.deadpwd,
        state: result?.data?.state,
        dateToActived: result?.data?.dateToActived,
        plaza_id: result?.data?.plaza_id,
    }

    return (
        <Dialog
            open={open}
            onClose={() => handleOpen(false)}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
        >
            <DialogTitle id="alert-dialog-title">
                {pwd}
            </DialogTitle>
            <DialogContent>
                <DialogContentText id="alert-dialog-description">
                    <ModalForm initialValues={initialValues} />
                </DialogContentText>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => handleOpen(false)} autoFocus>
                    Salir
                </Button>
                <Button onClick={() => handleOpen(false)}>Guardar</Button>
            </DialogActions>
        </Dialog>
    )
}

function ModalForm(props) {
    console.log("PROPS >> ", props)

    const pwdSchema = Yup.object().shape({
        id: Yup.number(),
        pwd: Yup.string().required(),
        deadpwd: Yup.date(),
        state: Yup.number().required(),
        dateToActived: Yup.date().required(),
        plaza_id: Yup.number().required()
    })


    const formik = useFormik({
        initialValues: props.initialValues,
        onSubmit: (fields) => {
            console.log('campos> ', fields)
        },
        validationSchema: pwdSchema,
    })

    const { errors, touched, handleSubmit, getFieldProps, values, setValues } = formik;
    console.log('formik values >> ', values )

    return (
        <FormikProvider  value={formik}>
            <Form style={{padding : 15,minWidth:450}} autoComplete="off" noValidate onSubmit={handleSubmit}>
                <Stack spacing={4}>

                    <TextField
                        fullWidth
                        type="text"
                        label="Nombre o identificador"
                        {...getFieldProps('pwd')}
                        error={Boolean(touched.pwd && errors.pwd)}
                        helperText={touched.pwd && errors.pwd}
                    />
                    

                    <TextField
                        fullWidth
                        type="text"
                        label="Nombre o identificador"
                        {...getFieldProps('pwd')}
                        error={Boolean(touched.pwd && errors.pwd)}
                        helperText={touched.pwd && errors.pwd}
                    />

                    <TextField
                        fullWidth
                        type="text"
                        label="Nombre o identificador"
                        {...getFieldProps('pwd')}
                        error={Boolean(touched.pwd && errors.pwd)}
                        helperText={touched.pwd && errors.pwd}
                    />
                    
                    <TextField
                        fullWidth
                        type="text"
                        label="Nombre o identificador"
                        {...getFieldProps('pwd')}
                        error={Boolean(touched.pwd && errors.pwd)}
                        helperText={touched.pwd && errors.pwd}
                    />

                        <LocalizationProvider
                            dateAdapter={DateFnsUtils}>
                            <DesktopDatePicker
                                label="Fecha de Activación"
                                fullWidth
                                inputFormat="dd/MM/yyyy"
                                {...getFieldProps('dateToActived')}
                                value={values.dateToActived}
                                onChange={(val) => setValues({ ...values, dateToActived: new Date(val) })
                                }
                                renderInput={(params) =>
                                    <TextField
                                        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>


                </Stack>
            </Form>
        </FormikProvider >
    )

}

