import * as React from 'react';
import {
  Button, Dialog, DialogActions, DialogContent,
  FormControlLabel, Checkbox, Box, Stack,
  TextField,CircularProgress
} from '@mui/material'

import { AddCircle } from '@mui/icons-material/';
import { MailTable } from './Steps/MailTable';

import { Col, Row } from 'react-bootstrap'

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

import { useQueryClient } from 'react-query'
import { Service } from '../../Utils/HTTP.js'
import { useSelector } from 'react-redux'

import { useFormik, Form, FormikProvider } from 'formik';
import { AdapterDateFns as DateFnsUtils } from '@mui/x-date-pickers/AdapterDateFns';
import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';


function Candidatos(props){

  const CandidatoSchema = Yup.object().shape({
    nombres:
      Yup.string()
        .min(2, 'Demasiado corto!')
        .max(50, 'Demasiado largo!'),
    apellidos:
      Yup.string()
        .min(2, 'Demasiado corto!').max(50, 'Demasiado Largo!'),
    mail:
      Yup.string()
        .email("Correo no valido")
  });

  let [password, setPassword] = React.useState([]);

  let { candidatos } = props
  console.log('operation props candidatos', candidatos)

  const formik = useFormik({
    initialValues: {
      nombres: "",
      apellidos: "",
      mail: "",
    },
    onSubmit: () => {
      if(password.length <= 0){
        toast.error("Seleciona almenos un destino")
        return;
      }
      console.log('submited')
    },
    validationSchema: CandidatoSchema,
  });

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

  const addToList = () => {

    if(!values.nombres || !values.apellidos || !values.mail){
      return toast.error("Completa la informacion del candidato")
    }

    if(!isValid) {
      return toast.error("Completa la informacion del candidato")
    }

    let user = {
      'nombres': values.nombres,
      'apellidos': values.apellidos,
      'mail': values.mail,
    }
    let new_users = [...password.candidatos, user ]

    setPassword({...candidatos, candidatos: new_users })
    resetForm();

  }

  const removeFromList = (umail) => {
    let without = password.candidatos.filter( user => user.mail !== umail )
    setPassword({...password, candidatos: without })
  }

  return (
    <FormikProvider style={{ padding: 25 }} value={formik}>
      <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
        <Stack spacing={3}>
          <Stack style={{paddingTop: 15}} direction={{ xs: 'column', sm: 'row' }} spacing={2}>
            <TextField
              label="Nombre"
              fullWidth
              {...getFieldProps('nombres')}
              error={Boolean(touched.nombres && errors.nombres)}
              helperText={touched.nombres && errors.nombres}
            />

            <TextField
              label="Apellidos"
              fullWidth
              {...getFieldProps('apellidos')}
              error={Boolean(touched.apellidos && errors.apellidos)}
              helperText={touched.apellidos && errors.apellidos}
            />
          </Stack>

          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
            <TextField
              fullWidth
              type="email"
              label="Correo Electronico"
              {...getFieldProps('mail')}
              error={Boolean(touched.mail && errors.mail)}
              helperText={touched.mail && errors.mail}
            />

            <Button onClick={addToList}>
              <AddCircle style={{color:'var(--main)'}}/>
            </Button>

          </Stack>

          <MailTable 
            remove={removeFromList} 
            users={candidatos}
            />

          <Box sx={{ mb: 2 }}>
            <div style={{ paddingTop: 15 }}>
              <Button
                type="submit"
                className="registerBtn"
                variant="contained"
                sx={{ mt: 1, mr: 1 }}
              >
                {'Siguiente'}
              </Button>
              <Button
                disabled={false}
                onClick={() => console.log('regresar')}
                sx={{ mt: 1, mr: 1 }}
              >
                Regresar
              </Button>
            </div>
          </Box>

        </Stack>
        <Toaster position="top-right" />
      </Form>
    </FormikProvider>
  );
}

export function ModalEdit(props) {

  const auth = useSelector((state) => state.token)
  let [data, setData] = React.useState(null)
  let { password, open, handleOpen } = props
  let { pwd, plz } = password

  React.useEffect(() => {

    const getPassword = async () => {
      let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
      return await rest.getQuery(auth.token)
    }

    getPassword()
      .then(resp => setData(resp.data))
      .catch(error => console.log(error))
  }, [auth.token, pwd, plz])

  return (
    <Dialog
      fullWidth="md"
      maxWidth="md"
      open={open}
      onClose={() => handleOpen(false)}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
    >
      <DialogContent>
        {
          data ?
            <ModalForm
              password={data}
              handleOpen={handleOpen}
              token={auth.token}
            /> : <Loading />
        }
      </DialogContent>
    </Dialog>
  )
}

function Loading() {
  return (
    <CircularProgress style={{ color: 'var(--main)' }} />
  )
}

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"),
  })

  const queryClient = useQueryClient();
  let { password } = props
  console.log("227 PWD: ", password)

  let candidatos = password.candidatospwds.map( pwd => {
    let { apellidos, nombre,mail} = pwd.candi
    return { nombres: nombre, apellidos, mail }
  })

  const formik = useFormik({
    initialValues: {
      state: 1,
      pwd: atob(password.pwd),
      deadpwd: password.deadpwd,
      dateToActived: password.dateToActived,
    },
    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;

  return (
    <Row>
      <Col>
        <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>
              <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 >
      </Col>
      <Col>
        <Candidatos candidatos={candidatos} />
      </Col>
    </Row>
  )
}

