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

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

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

// project import
import AnimateButton from 'components/@extended/AnimateButton';
import {apiPath} from "auth/utils";
import {POST_LOGIN} from "utils/ApiPathConst";

// assets
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import axios from "axios";
import {useDispatch} from "react-redux";
import {handleLogin} from "auth/index";
import {FormattedMessage} from "react-intl";
// ============================|| 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 handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

  let [posts, setPosts] = useState([]);
  let [userName, setUserName] = useState("");
  let [userPassword, setUserPassword] = useState("");
  const [loginRequestPending, setLoginRequestPending] = useState(false);
  const loginInFlightRef = useRef(false);

  useEffect(() => {
    //console.log("POST: " + posts.accessToken);
  },[posts]);

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

  const tryLogin = () => {
    if (loginInFlightRef.current) {
      return;
    }
    loginInFlightRef.current = true;
    setLoginRequestPending(true);
    axios.post(`${apiPath}${POST_LOGIN}`,
        {
          "username": userName,
          "password": userPassword
        })
        .then((response) => {
          //setPosts("12354")
          // console.log(response.data);
          setPosts(response.data);

          const userData = {
            id: response.data.id,
            fullenName: response.data.name,
            fullchName: response.data.chName,
            email: response.data.email,
            type: response.data.type,
            role: response.data.role,
            abilities: response.data.abilities,
            passwordExpiryDate: response.data.passwordExpiryDate,
            orgPaymentRecord: response.data.orgPaymentRecord,
            orgDnRecord: response.data.orgDnRecord,
            //avatar: require('src/assets/images/users/avatar-3.png').default,
          }
          // const abilities = response.data.abilities
          // ability.update(abilities)

          const data = {...userData, accessToken: response.data.accessToken, refreshToken: response.data.refreshToken}
          dispatch(handleLogin(data))
          navigate('/dashboard');
          //history.push(getHomeRouteForLoggedInUser("user"))

        })
        .catch(error => {
          console.error(error);
          loginInFlightRef.current = false;
          setLoginRequestPending(false);
        });
  }

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

  const onPasswordChange = (event) => {
     setUserPassword(event.target.value);
  }

  function getMaxErrStr(num, fieldname){
    return intl.formatMessage({ id: 'noMoreThenNWords' },{num:num, fieldname:fieldname?intl.formatMessage({ id: fieldname})+": ":""});
}

  return (
    <>
      <Formik
        initialValues={{
          email: '',
          password: '',
          submit: null
        }}
        validationSchema={Yup.object().shape({
          email: Yup.string().max(128,getMaxErrStr(128)).email('Must be a valid email').required('Email is required'),
          password: Yup.string().max(60, getMaxErrStr(60)).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);
          }
        }}
      >
        {({ errors, handleBlur, handleSubmit, isSubmitting, touched }) => (
          <form noValidate onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel htmlFor="email-login">User Name</InputLabel>
                  <OutlinedInput
                    id="username"
                    name="username"
                    onBlur={handleBlur}
                    onChange={onUserNameChange}
                    placeholder="Enter user name"
                    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'}
                    name="password"
                    onBlur={handleBlur}
                    onChange={onPasswordChange}
                    endAdornment={
                      <InputAdornment position="end">
                        <IconButton
                          aria-label={intl.formatMessage({
                            id: showPassword ? "ariaHidePassword" : "ariaShowPassword"
                          })}
                          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}
                          disabled={isSubmitting || loginRequestPending} fullWidth size="large" type="submit" variant="contained" color="primary">
                    <FormattedMessage id="login"/>
                  </Button>
                </AnimateButton>
              </Grid>
            </Grid>
          </form>
        )}
      </Formik>
    </>
  );
};

export default AuthLogin;
