import React, {useState} from 'react';
import {useNavigate} from 'react-router-dom';

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

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

// project import
//import FirebaseSocial from './FirebaseSocial';
import AnimateButton from 'components/@extended/AnimateButton';
// assets
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
//import axios from "axios";
import {useDispatch} from "react-redux";
import {handleLogin} from "auth/index";
//import useJwt from "../../../auth/jwt/useJwt";
import axios from "axios";
import {apiPath} from "../../../auth/utils";
import {LOGIN_PATH} from "../../../utils/ApiPathConst";
import {LIONER_LOGIN_THEME} from "../../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";
//import {AbilityContext} from "utils/context/Can"
// ============================|| FIREBASE - LOGIN ||============================ //

const AuthLogin = () => {
  //const ability = useContext(AbilityContext)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  //const [checked, setChecked] = useState(false);

  const [showPassword, setShowPassword] = useState(false);
  const [errors, setErrors] = useState({});
  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

  const [userName, setUserName] = useState("");
  const [userPassword, setUserPassword] = useState("");

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

  const tryLogin = () => {

      const formErrors = {};

      if (userName.length===0) {
          formErrors.loginError = 'Username are required.';
      }

      if (userPassword.length===0){
          formErrors.passwordError = 'Password are required.';
      }

      setErrors(formErrors);

      if (Object.keys(formErrors).length === 0) {
          axios.post(`${apiPath}${LOGIN_PATH}`,
              {username: userName, password: userPassword},
          )
              .then(async (response) => {
                  const userData = {
                      id: response.data.id,
                      fullName: response.data.name,
                      email: response.data.email,
                      role: response.data.role,
                      abilities: response.data.abilities,
                      subDivisionId: response.data.subDivisionId,
                      lotusNotesUser: response.data.lotusNotesUser
                      //avatar: require('src/assets/images/users/avatar-3.png').default,
                  }
                  const data = {
                      ...userData,
                      accessToken: response.data.accessToken,
                      refreshToken: response.data.refreshToken
                  }
                  await dispatch(handleLogin(data))
                  //const abilities = response.data.abilities
                  //ability.update(abilities)
                  const lastPath = localStorage.getItem('lastVisitedPath');

                  await navigate(lastPath === null ? '/lionerDashboard' : lastPath);
                  await window.location.reload();
                  await localStorage.removeItem('lastVisitedPath');

              })
              .catch(error => {
                  const formErrors = {};
                  formErrors.loginError = " ";
                  formErrors.passwordError = error.response.data.message;
                  setErrors(formErrors);

                  return false;
              });

          /*useJwt
            .login({username: userName, password: userPassword})
            .then((response) => {
              const userData = {
                id: response.data.id,
                fullName: response.data.name,
                email: response.data.email,
                role: response.data.role,
                abilities: response.data.abilities,
                //avatar: require('src/assets/images/users/avatar-3.png').default,
              }
              const data = {...userData, accessToken: response.data.accessToken, refreshToken: response.data.refreshToken}
              dispatch(handleLogin(data))
              //const abilities = response.data.abilities
              //ability.update(abilities)
              navigate('/lionerDashboard');
            })
            .catch(error => {
                console.log(error);
                return Promise.reject(error);
            });*/
      }

  }

  const onUserNameChange = (event) => {
    setUserName(event.target.value);
  }

  const onPasswordChange = (event) => {
     setUserPassword(event.target.value);
  }
  return (
    <>
      <Formik
        initialValues={{
          userName: 'test',
          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 {
            setStatus({ success: false });
            setSubmitting(false);
          } catch (err) {
            setStatus({ success: false });
            setErrors({ submit: err.message });
            setSubmitting(false);
          }
        }}
      >
        {({ handleBlur, handleSubmit, isSubmitting /*touched*/ }) => (
          <form onSubmit={handleSubmit}>
              <ThemeProvider theme={LIONER_LOGIN_THEME}>
              <Grid container spacing={3}>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel htmlFor="username">User Name</InputLabel>
                  <TextField
                    id="username"
                    name="username"
                    onBlur={handleBlur}
                    onChange={onUserNameChange}
                    placeholder="Enter user name"
                    fullWidth
                    variant="outlined"
                    error={!!errors.loginError}
                    helperText={errors.loginError}
                  />
                  {/*{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>
                  <TextField
                    fullWidth
                    variant="outlined"
                    error={!!errors.passwordError}
                    helperText={errors.passwordError}
                    id="-password-login"
                    type={showPassword ? 'text' : 'password'}
                    name="password"
                    onBlur={handleBlur}
                    onChange={onPasswordChange}
                    InputProps={{
                        endAdornment: (
                            <InputAdornment position="end">
                                <IconButton
                                    aria-label="toggle password visibility"
                                    onClick={handleClickShowPassword}
                                    onMouseDown={handleMouseDownPassword}
                                    edge="end"
                                    size="large"
                                >
                                    {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="" 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 onClick={tryLogin}
                          sx={{height: '50px'}}
                          disabled={isSubmitting} fullWidth size="large" type="submit" variant="contained" color="primary">
                    Login
                  </Button>
                </AnimateButton>
              </Grid>
              {/*<Grid item xs={12}>*/}
              {/*  <Divider>*/}
              {/*    <Typography variant="caption"> Login with</Typography>*/}
              {/*  </Divider>*/}
              {/*</Grid>*/}
              {/*<Grid item xs={12}>*/}
              {/*  <FirebaseSocial />*/}
              {/*</Grid>*/}
            </Grid>
              </ThemeProvider>
          </form>
        )}
      </Formik>
    </>
  );
};

export default AuthLogin;
