import React, { useEffect, useState } from 'react';
// import { Link as RouterLink } from 'react-router-dom';

// material-ui
import {
  Button,
  // Checkbox,
  // FormControlLabel,
  FormHelperText,
  Grid,
  // Link,
  InputAdornment,
  InputLabel,
  OutlinedInput,
  Stack
  // Typography
} from '@mui/material';

// third party
import * as Yup from 'yup';
import { Formik } from 'formik';
import { enqueueSnackbar } from 'notistack';

// project import
import useAuth from 'hooks/useAuth';
import useScriptRef from 'hooks/useScriptRef';
import IconButton from 'components/@extended/IconButton';
import AnimateButton from 'components/@extended/AnimateButton';

// assets
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import axios from 'axios';
import Loader from 'components/Loader';

// ============================|| JWT - LOGIN ||============================ //

const opentoast = (message, color, time) => {
  enqueueSnackbar(message, {
    variant: color,
    anchorOrigin: { vertical: 'top', horizontal: 'right' },
    autoHideDuration: time
  });
};

const AuthLogin = () => {
  // const [checked, setChecked] = React.useState(false);
  const { login } = useAuth();
  const scriptedRef = useScriptRef();
  const [showPassword, setShowPassword] = React.useState(false);
  const [showPassword1, setShowPassword1] = React.useState(false);
  const [showPassword2, setShowPassword2] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [password1, setPassword1] = React.useState('');
  const [password2, setPassword2] = React.useState('');
  const [loading, setLoading] = useState(false);
  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };
  const handleClickShowPassword1 = () => {
    setShowPassword1(!showPassword1);
  };
  const handleClickShowPassword2 = () => {
    setShowPassword2(!showPassword2);
  };
  const handleMouseDownPassword = (event) => {
    event.preventDefault();
  };

  const [loginstatus, setLoginStatus] = useState(localStorage.getItem('loginstatus'));

  useEffect(() => {
    console.log('loginstatus', loginstatus);
  }, [loginstatus]);

  // ============================|| weblogin ||============================ //

  const weblogin = async () => {
    console.log('email', email);

    setLoading(true);
    if (!email) {
      opentoast('Enter valid email', 'error', 2000);
    } else {
      try {
        const response = await axios.post(`${process.env.REACT_APP_URL}/users/applogin`, {
          authname: email,
          configid: 1
        });
        console.log('weblogin', response.data);
        // invalid authname // email not found
        if (response.data.code == 409 && response.data.status == false) {
          opentoast(response.data.message, 'error', 2000);
        }
        // email correct, password is not set
        else if (response.data.code == 409 && response.data.status == true) {
          opentoast(response.data.message, 'success', 2000);
          localStorage.setItem('loginstatus', 1);
          localStorage.setItem('userid', response.data.details.userid);
          setLoginStatus(1);
        } else if (response.data.code == 401) {
          opentoast(response.data.message, 'success', 2000);
          localStorage.setItem('loginstatus', 2);
          setLoginStatus(2);
        }
      } catch (error) {
        console.log(`webLogin, ${error.message}`);
        opentoast(error.message, 'error', 2000);
      } finally {
        setLoading(false);
      }
    }
    setLoading(false);
  };

  // ============================|| updateuser ||============================ //

  const updateuser = async () => {
    setLoading(true);
    if (password1 != password2) {
      opentoast('Password Mismatch', 'error', 2000);
    } else {
      try {
        const response = await axios.put(`${process.env.REACT_APP_URL}/users/update`, {
          authname: email,
          password: password1,
          userid: +localStorage.getItem('userid')
        });
        console.log('updateuser', response);
        if (response.data.code == 202) {
          localStorage.setItem('loginstatus', 2);
          setLoginStatus(2);
          opentoast(response.data.message, 'success', 2000);
        }
      } catch (error) {
        console.log(`webLogin, ${error.message}`);
      } finally {
        setLoading(false);
      }
    }
    setLoading(false);
  };

  return (
    <>
      {loading && <Loader />}
      <Formik
        initialValues={{
          // email: '',
          // password: '123456',
          email: '',
          password: '',
          submit: null
        }}
        validationSchema={Yup.object().shape({
          email: Yup.string().email('Must be a valid email').max(255).required('Email is required'),
          password: Yup.string().max(255).required('Password is required')
        })}
        onSubmit={async (values, { setErrors, setStatus, setSubmitting }) => {
          try {
            await login(values.email, values.password);
            if (scriptedRef.current) {
              setStatus({ success: true });
              setSubmitting(false);
            }
          } catch (err) {
            console.error(err);
            if (scriptedRef.current) {
              setStatus({ success: false });
              setErrors({ submit: err.message });
              setSubmitting(false);
            }
          }
        }}
      >
        {({ errors, handleBlur, handleChange, handleSubmit, isSubmitting, touched, values }) => (
          <form noValidate onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              {/* to set up password, hide enter email, only enter and re enter password visible, once the mail id is verified , status 0 to 1 */}
              {loginstatus != 1 && (
                <Grid item xs={12}>
                  <Stack spacing={1}>
                    <InputLabel htmlFor="email-login">Email Address</InputLabel>
                    <OutlinedInput
                      autoFocus
                      id="email-login"
                      type="email"
                      value={values.email}
                      name="email"
                      onBlur={handleBlur}
                      onChange={(e) => {
                        handleChange(e);
                        setEmail(e.target.value);
                      }}
                      placeholder="Enter Email Address"
                      fullWidth
                      error={Boolean(touched.email && errors.email)}
                    />
                    {touched.email && errors.email && (
                      <FormHelperText error id="standard-weight-helper-text-email-login">
                        {errors.email}
                      </FormHelperText>
                    )}
                  </Stack>
                </Grid>
              )}{' '}
              {/* to enter and reenter password */}
              {loginstatus == 1 && (
                <>
                  <Grid item xs={12}>
                    <Stack spacing={1}>
                      <InputLabel htmlFor="password-login">Create Password</InputLabel>
                      <OutlinedInput
                        fullWidth
                        autoFocus
                        id="-password-login"
                        type={showPassword1 ? 'text' : 'password'}
                        name="password"
                        onChange={(e) => {
                          setPassword1(e.target.value);
                        }}
                        endAdornment={
                          <InputAdornment position="end">
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={handleClickShowPassword1}
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                              color="primary"
                            >
                              {showPassword1 ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                            </IconButton>
                          </InputAdornment>
                        }
                        placeholder="Enter password"
                      />
                      {touched.password && errors.password && (
                        <FormHelperText error id="standard-weight-helper-text-password-login">
                          {errors.password}
                        </FormHelperText>
                      )}
                    </Stack>
                  </Grid>
                  <Grid item xs={12}>
                    <Stack spacing={1}>
                      <InputLabel htmlFor="password-login">Confirm Password</InputLabel>
                      <OutlinedInput
                        fullWidth
                        id="-password-login"
                        type={showPassword2 ? 'text' : 'password'}
                        name="password"
                        error={password2.length > 0 && password1 != password2}
                        onChange={(e) => {
                          setPassword2(e.target.value);
                        }}
                        endAdornment={
                          <InputAdornment position="end">
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={handleClickShowPassword2}
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                              color="primary"
                            >
                              {showPassword2 ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                            </IconButton>
                          </InputAdornment>
                        }
                        placeholder="Enter password"
                      />
                      {touched.password && errors.password && (
                        <FormHelperText error id="standard-weight-helper-text-password-login">
                          {errors.password}
                        </FormHelperText>
                      )}
                    </Stack>
                  </Grid>
                </>
              )}
              {/* final login, when loginstatus ==2 , now email and enter password feild starts to visible */}
              {/* when hit login while status == 2, it call login from jwtcontext */}
              {loginstatus == 2 && (
                <Grid item xs={12}>
                  <Stack spacing={1}>
                    <InputLabel htmlFor="password-login">Password</InputLabel>
                    <OutlinedInput
                      autoFocus
                      fullWidth
                      error={Boolean(touched.password && errors.password)}
                      id="-password-login"
                      type={showPassword ? 'text' : 'password'}
                      value={values.password}
                      name="password"
                      onBlur={handleBlur}
                      onChange={handleChange}
                      endAdornment={
                        <InputAdornment position="end">
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                            color="primary"
                          >
                            {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                          </IconButton>
                        </InputAdornment>
                      }
                      placeholder="Enter password"
                    />
                    {touched.password && errors.password && (
                      <FormHelperText error id="standard-weight-helper-text-password-login">
                        {errors.password}
                      </FormHelperText>
                    )}
                  </Stack>
                </Grid>
              )}
              {/* <Grid item xs={12} sx={{ mt: -1 }}>
                <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}></Stack>
              </Grid> */}
              {errors.submit && (
                <Grid item xs={12}>
                  <FormHelperText error>{errors.submit}</FormHelperText>
                </Grid>
              )}
              <Grid item xs={12}>
                <AnimateButton>
                  {loginstatus == 2 && (
                    <Button
                      disableElevation
                      disabled={isSubmitting}
                      fullWidth
                      size="large"
                      type="submit"
                      variant="contained"
                      // style={{ backgroundColor: '#662582', color: '#FFFFFF' }}
                    >
                      Login
                    </Button>
                  )}
                  {loginstatus != 2 && (
                    <Button
                      type="submit"
                      disableElevation
                      disabled={loading}
                      fullWidth
                      size="large"
                      variant="contained"
                      color="primary"
                      onClick={() => {
                        loginstatus == 0 ? weblogin() : loginstatus == 1 ? updateuser() : null;
                      }}
                    >
                      Continue
                    </Button>
                  )}
                </AnimateButton>
              </Grid>
            </Grid>
          </form>
        )}
      </Formik>
    </>
  );
};

export default AuthLogin;
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// ======================================================================================================================================
// import React from 'react';
// import { Link as RouterLink } from 'react-router-dom';

// // material-ui
// import {
//   Button,
//   Checkbox,
//   FormControlLabel,
//   FormHelperText,
//   Grid,
//   Link,
//   InputAdornment,
//   InputLabel,
//   OutlinedInput,
//   Stack,
//   Typography
// } from '@mui/material';

// // third party
// import * as Yup from 'yup';

// import { Formik } from 'formik';

// // project import
// import useAuth from 'hooks/useAuth';
// import useScriptRef from 'hooks/useScriptRef';
// import IconButton from 'components/@extended/IconButton';
// import AnimateButton from 'components/@extended/AnimateButton';

// // assets
// import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';

// // ============================|| JWT - LOGIN ||============================ //

// const AuthLogin = () => {
//   const [checked, setChecked] = React.useState(false);

//   const { login } = useAuth();
//   const scriptedRef = useScriptRef();

//   const [showPassword, setShowPassword] = React.useState(false);
//   const handleClickShowPassword = () => {
//     setShowPassword(!showPassword);
//   };

//   const handleMouseDownPassword = (event) => {
//     event.preventDefault();
//   };

//   return (
//     <>
//       <Formik
//         initialValues={{
//           email: 'info@codedthemes.com',
//           password: '123456',
//           submit: null
//         }}
//         validationSchema={Yup.object().shape({
//           email: Yup.string().email('Must be a valid email').max(255).required('Email is required'),
//           password: Yup.string().max(255).required('Password is required')
//         })}
//         onSubmit={async (values, { setErrors, setStatus, setSubmitting }) => {
//           try {
//             await login(values.email, values.password);
//             if (scriptedRef.current) {
//               setStatus({ success: true });
//               setSubmitting(false);
//             }
//           } catch (err) {
//             console.error(err);
//             if (scriptedRef.current) {
//               setStatus({ success: false });
//               setErrors({ submit: err.message });
//               setSubmitting(false);
//             }
//           }
//         }}
//       >
//         {({ errors, handleBlur, handleChange, handleSubmit, isSubmitting, touched, values }) => (
//           <form noValidate onSubmit={handleSubmit}>
//             <Grid container spacing={3}>
//               <Grid item xs={12}>
//                 <Stack spacing={1}>
//                   <InputLabel htmlFor="email-login">Email Address</InputLabel>
//                   <OutlinedInput
//                     id="email-login"
//                     type="email"
//                     value={values.email}
//                     name="email"
//                     onBlur={handleBlur}
//                     onChange={handleChange}
//                     placeholder="Enter email address"
//                     fullWidth
//                     error={Boolean(touched.email && errors.email)}
//                   />
//                   {touched.email && errors.email && (
//                     <FormHelperText error id="standard-weight-helper-text-email-login">
//                       {errors.email}
//                     </FormHelperText>
//                   )}
//                 </Stack>
//               </Grid>
//               <Grid item xs={12}>
//                 <Stack spacing={1}>
//                   <InputLabel htmlFor="password-login">Password</InputLabel>
//                   <OutlinedInput
//                     fullWidth
//                     error={Boolean(touched.password && errors.password)}
//                     id="-password-login"
//                     type={showPassword ? 'text' : 'password'}
//                     value={values.password}
//                     name="password"
//                     onBlur={handleBlur}
//                     onChange={handleChange}
//                     endAdornment={
//                       <InputAdornment position="end">
//                         <IconButton
//                           aria-label="toggle password visibility"
//                           onClick={handleClickShowPassword}
//                           onMouseDown={handleMouseDownPassword}
//                           edge="end"
//                           color="secondary"
//                         >
//                           {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
//                         </IconButton>
//                       </InputAdornment>
//                     }
//                     placeholder="Enter password"
//                   />
//                   {touched.password && errors.password && (
//                     <FormHelperText error id="standard-weight-helper-text-password-login">
//                       {errors.password}
//                     </FormHelperText>
//                   )}
//                 </Stack>
//               </Grid>

//               <Grid item xs={12} sx={{ mt: -1 }}>
//                 <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
//                   <FormControlLabel
//                     control={
//                       <Checkbox
//                         checked={checked}
//                         onChange={(event) => setChecked(event.target.checked)}
//                         name="checked"
//                         color="primary"
//                         size="small"
//                       />
//                     }
//                     label={<Typography variant="h6">Keep me sign in</Typography>}
//                   />
//                   <Link variant="h6" component={RouterLink} to="/forgot-password" color="text.primary">
//                     Forgot Password?
//                   </Link>
//                 </Stack>
//               </Grid>
//               {errors.submit && (
//                 <Grid item xs={12}>
//                   <FormHelperText error>{errors.submit}</FormHelperText>
//                 </Grid>
//               )}
//               <Grid item xs={12}>
//                 <AnimateButton>
//                   <Button disableElevation disabled={isSubmitting} fullWidth size="large" type="submit" variant="contained" color="primary">
//                     Login
//                   </Button>
//                 </AnimateButton>
//               </Grid>
//             </Grid>
//           </form>
//         )}
//       </Formik>
//     </>
//   );
// };

// export default AuthLogin;
