import * as React from 'react';
import {
  Button, Dialog, DialogActions, DialogContent,
  FormControlLabel, Checkbox, Stack,
  TextField, CircularProgress, Divider, Typography
} 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 { candidatos, add , remove } = props

  const formik = useFormik({
    initialValues: {
      nombres: "",
      apellidos: "",
      mail: "",
    },
    onSubmit: () => {
      console.log('submited')
    },
    validationSchema: CandidatoSchema,
  });

  var { 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,
    }
    add(user)
    resetForm();

  }

  return (
    <FormikProvider style={{ padding: 25 }} value={formik}>
      <Typography style={{ padding: 5, marginBottom: 15 }}>Ingresa la informacion del candidato</Typography>
      <Divider />
      <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={remove}
            users={candidatos}
          />

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

export function ModalEdit(props) {

  //TODO:
  //se debe crear un objeto de estado que almacena los nuevos cambios de la password
  //enviar por props las utilizades de edicion y eliminar

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

  React.useEffect(() => {

    let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
    rest.getQuery(auth.token)
      .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) {

  let [candidatos,setCandidatos] = React.useState(null);
  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

  React.useEffect(() => {
    let mapCandi = password.candidatospwds.map(pwd => {
      let { apellidos, nombre, mail } = pwd.candi
      return { nombres: nombre, apellidos, mail }
    })
    setCandidatos(mapCandi)
  },[password.candidatospwds])

  function removeCandidato (umail) {
    console.log('remove:', umail)
    let without = candidatos.filter( user => user.mail !== umail )
    setCandidatos(without)
  }

  function addCandidato (candidato) {
    setCandidatos([...candidatos, candidato ])
  }

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


            </Stack>
          </Form>
          <Toaster position="bottom-right" />
        </FormikProvider >
      </Col>
      <Col>
        <Candidatos
          add={addCandidato} 
          remove={removeCandidato} 
          candidatos={candidatos} 
        />
      </Col>

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

