import React, {
  useEffect,
  useState} from 'react';
import { Link as RouterLink } from 'react-router-dom';
import {useNavigate} from 'react-router-dom';
import {useForm,} from 'react-hook-form'

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

// third party
import * as yup from 'yup';
import { useFormik,FormikProvider } 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 iAmSmartICon from 'assets/images/icons/icon_iAmSmart.png';
import {useDispatch} from "react-redux";
import {handleLogin} from "auth/index";
import useJwt from "../../../auth/jwt/useJwt";

// ============================|| FIREBASE - LOGIN ||============================ //

const AuthLoginCustom = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()

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

  // let [posts, setPosts] = useState([]);
  const [isValid, setisValid] = useState(false);
  const [isSuccess, setSuccess] = useState();
  const [isSumitting, setSumitting] = useState();

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

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

  const tryLogin = () => {
    if(isValid){
      setSumitting(true)
      useJwt
        .login({username: values.username, password: values.password})
        .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}
          setSuccess(true)
          dispatch(handleLogin(data))
          navigate('/dashboard');
          setSumitting(false)
          console.log(isSuccess)
        })
        .catch((error) => {
          setSuccess(false)
          console.error(error)
        });
    }
  }

  const formik = useFormik({
    initialValues:({
        username: '',
        password: '',
        submit: null
    }),
    validationSchema:yup.object().shape({
        username: yup.string().min(6,'用戶名稱最少6位').required('請輸入用戶名稱'),
        password: yup.string().min(8,'請輸入最少8位密碼').required('請輸入密碼')
            .matches(/^(?=.*[a-z])/, '請包括最少1個小寫字母')
            .matches(/^(?=.*[A-Z])/, '請包括最少1個大寫字母')
            .matches(/^(?=.*[0-9])/, '請包括最少1個數字')
            .matches(/^(?=.*[!@#%&])/, '請包括最少1個特殊字符'),
    }),
  });

  const checkDataField = (data)=> {
    if (data.username !==""&&
        data.password !==""&&
        handlePassword(data.password)&&
        handle8Digi(data.username)
    )
    {
        setisValid(true)
        return isValid
    }else{
        setisValid(false)
        return isValid
    }
  };

  function handlePassword(password) {
    let new_pass = password;
    // regular expressions to validate password
    var lowerCase = /[a-z]/g;
    var upperCase = /[A-Z]/g;
    var numbers = /[0-9]/g;
    if (!new_pass.match(lowerCase)) {
        return false;
    } else if (!new_pass.match(upperCase)) {
        return false;
    } else if (!new_pass.match(numbers)) {
        return false;
    } else if (new_pass.length < 8) {
        return false;
    } else {
        return true;
    }
  }

  function handle8Digi(value) {
        if (value.length < 8) {
            return false;
        } else {
            return true;
        }
  }

  const { values } = formik
    useEffect(() => {
      checkDataField(values)
    }, [values])

  const {handleSubmit} = useForm({})

  return (
      <FormikProvider value={formik}>
        <form onSubmit={handleSubmit(tryLogin)}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Stack spacing={1}>
                {!isSuccess && isSumitting && (
                  <FormHelperText error id="standard-weight-helper-text-username-login">
                    用戶登入名稱或密碼錯誤
                  </FormHelperText>
                )}
                <InputLabel htmlFor="email-login">用戶登入名稱</InputLabel>
                <OutlinedInput
                  id="username"
                  name="username"
                  onChange={formik.handleChange}
                  placeholder=""
                  fullWidth
                  value={formik.values.username}
                  error={Boolean(formik.touched.username && formik.errors.username)}
                  onBlur={formik.handleBlur}
                  inputProps={{
                    maxLength: 20,
                    onKeyDown: (e) => {
                        if (e.key === 'Enter') {
                            e.preventDefault();
                        }
                    },
                }}
                />
                {formik.touched.username && formik.errors.username && (
                  <FormHelperText error id="standard-weight-helper-text-username-login">
                    {formik.errors.username}
                  </FormHelperText>
                )}
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel htmlFor="password-login">密碼</InputLabel>
                <OutlinedInput
                  fullWidth
                  id="password-login"
                  type={showPassword ? 'text' : 'password'}
                  name="password"
                  value={formik.values.password}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={Boolean(formik.touched.password && formik.errors.password)}
                  endAdornment={
                    <InputAdornment position="end">
                      <IconButton
                        aria-label="toggle password visibility"
                        onClick={handleClickShowPassword}
                        onMouseDown={handleMouseDownPassword}
                        edge="end"
                        size="large"
                      >
                        {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                      </IconButton>
                    </InputAdornment>
                  }
                  placeholder=""
                />
                {formik.touched.password && formik.errors.password && (
                  <FormHelperText error id="standard-weight-helper-text-password-login">
                    {formik.errors.password}
                  </FormHelperText>
                )}
              </Stack>
            </Grid>

            <Grid item xs={12}>
              <AnimateButton>
                <Button disableElevation onClick={tryLogin}
                        fullWidth size="large" type="submit" variant="contained" color="primary">
                  登錄
                </Button>
              </AnimateButton>
            </Grid>
            <Grid item xs={12}>
              <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                <Link variant="h6" component={RouterLink} to="" color="text.primary">
                  <Typography align="center">
                  忘記密碼?
                  </Typography> 
                </Link>
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                <Button fullWidth size="large" variant="outlined" startIcon={<img src={iAmSmartICon} alt="iAM Smart" width="30" />}>智方便登入</Button>
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                <Link href="#">了解更多智方便</Link>
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                <Button fullWidth size="large" variant="outlined" href="/register" >建立/重新啟動帳戶</Button>
              </Stack>
            </Grid>
            {/* <Grid item xs={12}>*/}
            {/*  <Divider>*/}
            {/*    <Typography variant="caption"> Login with</Typography>*/}
            {/*  </Divider>*/}
            {/*</Grid>*/}
            {/*<Grid item xs={12}>*/}
            {/*  <FirebaseSocial />*/}
            {/*</Grid> */}
          </Grid>
        </form>
      </FormikProvider>
  );
};

export default AuthLoginCustom;
